Securing routes with sessionStorage in NextJS

28 Views Asked by At

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.

1

There are 1 best solutions below

0
Hashan Hemachandra On BEST ANSWER

The sessionStorage is a browser API that is not available in the server-side rendering (SSR) environment of Next.js. This is why you're getting the ReferenceError: sessionStorage is not defined error.

To access the sessionStorage in Next.js, you need to use the useEffect hook and check if window and window.sessionStorage are available before attempting to access sessionStorage

"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { valJwt } from "@/libs/jwtSec";

export default function isAuth(Component: any) {
  return function IsAuth(props: any) {
    const [token, setToken] = useState<string | null>(null);
    const router = useRouter();

    useEffect(() => {
      if (typeof window !== "undefined") {
        const tok_ses = window.sessionStorage.getItem("token_test");
        if (tok_ses) {
          setToken(tok_ses);
        }
      }
    }, []);

    useEffect(() => {
      if (token) {
        const auth = valJwt(token);
        if (!auth) {
          router.push("/");
        }
      }
    }, [token, router]);

    if (!token) {
      return null;
    }

    return <Component {...props} />;
  };
}