Noman Ansari
Noman Ansari

Reputation: 1

Navbar State Update by using cookies in src/app directory using cookies in pages system and Cookie next/header didn't allow

this is src/Utills Where we are getting the jwt from the cookie and the data from the jwt cookie

Navbar State Update by using cookies in src/app directory using cookies in pages system and Cookie next/header didn't allow so I need an authentic solution to solve this bug and one here to manage this state issue

// src/Utills/auth.js
import { jwtDecode } from "jwt-decode";
import redisClient from "@/Utils/redis";

export async function verifyJWTWithRedis({ cookies }) {
  const tokenCookie = cookies["access_token"];
  const firstCookie = cookies["first_1"];

  if (!tokenCookie || !firstCookie) {
    return {
      redirect: {
        destination: "/sign-in",
        permanent: false,
      },
    };
  }

  try {
    const decoded = jwtDecode(tokenCookie);
    const userId = decoded.id;

    const redisToken = await new Promise((resolve, reject) => {
      redisClient.get(`user:${userId}:token`, (err, data) => {
        if (err) reject(err);
        resolve(data);
      });
    });

    if (redisToken !== tokenCookie) {
      return {
        redirect: {
          destination: "/sign-in",
          permanent: false,
        },
      };
    }

    return {
      props: {
        isAuthenticated: true,
        user: decoded,
        access_token: tokenCookie,
      },
    };
  } catch (error) {
    console.error("Error verifying token:", error);
    return {
      redirect: {
        destination: "/sign-in",
        permanent: false,
      },
    };
  }
}

When is signed in, signed up, and signed out from the app, the state remains the same, but on refresh, it catches the data. Could you Give me the solution for this @Next.js?

If you have better solution then quickly answer my questions

import Navbar from "@/components/Navbar";
import "../globals.css";
import Footer from "@/components/Footer";
import { ToastProvider } from "@/context/ToastContext";
import { verifyJWTWithRedis } from "@/Utils/auth";
import { cookies } from "next/headers";

export default async function RootLayout({ children }) {
  const cookieStore = cookies();
  const tokenCookie = cookieStore.get("access_token");
  const firstCookie = cookieStore.get("first_1");

  const { props = {} } = await verifyJWTWithRedis({
    cookies: {
      access_token: tokenCookie?.value,
      first_1: firstCookie?.value,
    },
  });

  const { user = {}, isAuthenticated, access_token } = props;

  return (
    <div className="client-layout">
      <Navbar
        user={user}
        isAuthenticated={isAuthenticated}
        access_token={access_token}
      />
      <main className="content" role="main">
        {children}
      </main>
      <Footer />
    </div>
  );
}

Upvotes: 0

Views: 9

Answers (0)

Related Questions