I'm trying to secure a page using a jwt token in a session in NextJS, I was looking at similar questions on the forum and I saw that they recommended using useeffect to get access but I still can't recover anything.
The code I started with:
"use client";
import {
useEffect,
useState
} from "react";
import {
useRouter
} from 'next/navigation'
import {
valJwt
} from "@/libs/jwtSec";
import Cookies from "js-cookie";
export default function isAuth(Component: any) {
return function IsAuth(props: any) {
const auth = valJwt(sessionStorage.getItem("token_test"));
useEffect(() => {
if (!auth) {
return redirect("/");
}
}, []);
if (!auth) {
return null;
}
return < Component {
...props
}
/>;
};
}
Output:
ReferenceError: sessionStorage is not defined
And the edition with which I do not recover anything is this:
"use client";
import {
useEffect,
useState
} from "react";
import {
useRouter
} from 'next/navigation'
import {
valJwt
} from "@/libs/jwtSec";
import Cookies from "js-cookie";
export default function isAuth(Component: any) {
return function IsAuth(props: any) {
const [token, setToken] = useState(null);
useEffect(() => {
let tok_ses = sessionStorage.getItem("token_test");
if (tok_ses) {
setToken(tok_ses);
}
}, []);
useEffect(() => {
if (token) {
const auth = valJwt(sessionStorage.getItem("token_test"));
if (!auth) {
return redirect("/");
}
}
}, [token]);
};
}
I tried with js-cookie but I can't get access from the same function either, how could I get access?
I need to access the content of a sessionStorage from NextJS on the client side.
The
sessionStorageis a browser API that is not available in the server-side rendering (SSR) environment of Next.js. This is why you're getting theReferenceError: sessionStorage is not definederror.To access the
sessionStoragein Next.js, you need to use the useEffect hook and check ifwindowandwindow.sessionStorageare available before attempting to accesssessionStorage