Sorry for poor English, it is my second language.
I am using Next.js 14.
I want to make a function that checks localStorage item before moving user into a specific page. Else it redirects user to the home page. (Similar to profile page requring logged in info)
However, since I am already using metdata(which runs in SSR I guess), it is not possible for me to access the localStorage without "use client". How should I fix the structure in this case? Is there way to get localStorage item here? Or is there a way to fix the page title without using metadata?
import * as React from "react";
import { redirect } from "next/navigation";
export const metadata = {
title: "My Profile",
};
export default function StarforceProfileLayout({ children }) {
const apiKey = localStorage.getItem("api-key");
if (!apiKey) {
redirect("/");
}
return <>{children}</>;
}
2
Answers
To achieve what you want in Next.js 14, you can use a combination of useEffect and conditional rendering to check for the localStorage item on the client side. You can also manage the title without using metadata.
Here’s an example of how you can structure your StarforceProfileLayout component:
In this example, useEffect is used to run the code that checks for the localStorage item only on the client side after the component mounts. The useRouter hook is used to access the Next.js router, and router.push("/") is used for redirection.
Regarding the page title, you can manage it directly in the component using the useEffect hook as well. Here’s an example:
This way, you can manage both the redirection and the page title directly within your component without relying on metadata for the title.
Store Your api-key in cookies. you have access to cookies in ssr via next/headers.