I am trying to use Next.js to create a web app with authentication and global user state. Once a user is signed in I would like to display the user in the navbar, and also share that user state with the child components which may make API calls that require the user information. I am using Next.js 13 with the app
directory and the app/layout.js
file to store my navbar and user state.
My issue is that the navbar in app/layout.js
is able to consistently display the username once it is decoded from the JSON web token, however this is not displayed within my child component (app/loginsuccess/page.jsx
) which needs to have the user state too.
context/MyContext.js
import { createContext, useState } from "react";
const MyContext = createContext({
value: null,
setValue: () => {},
});
export const MyProvider = ({ children }) => {
const [value, setValue] = useState(null);
return (
<MyContext.Provider value={{ value, setValue }}>
{children}
</MyContext.Provider>
);
};
export default MyContext;
app/layout.jsx
"use client";
import "./globals.css";
import Link from "next/link";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Cookies from "js-cookie";
import { MyProvider } from "@/context/MyContext";
const getUserFromJWTCookie = async () => {
const authToken = Cookies.get("token");
const response = await fetch("/api/session", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ token: authToken }),
});
const responseData = await response.json();
const username = responseData.username;
if (username) {
console.log("getUserFromJWTCookie", username);
return username;
}
};
export default function RootLayout({ children }) {
const router = useRouter();
const [user, setUser] = useState("");
useEffect(() => {
(async () => {
const user = await getUserFromJWTCookie();
setUser(user);
if (!user) {
router.replace("/logintest");
}
})();
}, [router]);
return (
<MyProvider value={{ value: user, setValue: setUser }}>
<html lang="en">
<body>
<nav className="bg-gray-800 text-white p-4">
<ul className="flex justify-center space-x-4">
<li className="hover:bg-gray-700 rounded-md p-2">
<Link href="/show">
<h1 className="text-xl font-semibold">Shows</h1>
</Link>
</li>
<li className="hover:bg-gray-700 rounded-md p-2">
<Link href="/user">
<h1 className="text-xl font-semibold">Users</h1>
</Link>
</li>
<li className="hover:bg-gray-700 rounded-md p-2">
<Link href="/loginsuccess">
<h1 className="text-xl font-semibold">{user}</h1>
</Link>
</li>
</ul>
</nav>
<main>{children}</main>
</body>
</html>
</MyProvider>
);
}
app/loginsuccess/page.jsx
"use client";
import { useContext, useState, useEffect } from "react";
import MyContext from "@/context/MyContext";
const ProtectedPage = () => {
const { value } = useContext(MyContext);
const [user, setUser] = useState("");
useEffect(() => {
setUser(value);
}, [value]);
return <div>Welcome! {user}</div>;
};
export default ProtectedPage;
Any help in making this render at the same time in my child component is greatly appreciated 🙂