Redirect to Login page using Next JS middleware using localstorage or context API

816 Views Asked by At

I am working on the next 13 and I want to redirect users back to login page if they access the page without login. I have already done the login page

Once the user logs in i am I have to manage the AuthContext and everywhere I will get the status that the user is login or not

context/AuthContext.js

import React, { useState } from "react";

export const Context = React.createContext();

const Provider = props => {
  const aCallback = () => {
    alert("HEY FROM METHOD");
    setAuth("");
  };

  const isSignedIn = window.localStorage.getItem("AuthToken");
  const [auth, setAuth] = useState(isSignedIn ? true : false);

  return (
    <Context.Provider
      value={{
        auth,
        updateAuth: auth => setAuth(auth),
        aCallback: aCallback
      }}
    >
      {props.children}
    </Context.Provider>
  );
};

export default Provider;

middleware.js

import { useContext } from 'react';
import { Context } from "@/context/AuthContext";
import { NextResponse } from "next/server";
import { redirect } from "next/navigation.js";
export default async function middleware(req) {
   const { auth, updateAuth } =  useContext(Context);
   if (auth) {
   }
   if(req.nextUrl.path !="/login" && !auth){
      if(req.nethod != 'POST'){
         return redirect("/");
         //return new NextResponse("Cannot access this endpoint with " + req.method, { status: 400})
      }
   return NextResponse.next();
   }
}

I have tried to redirect users if they are not logged from middleware but it returns the error TypeError: Cannot read properties of null (reading 'useContext')

Please guid me on this

Thank you!

1

There are 1 best solutions below

0
On

Next's API routes run outside of the React "tree" and therefore do not have access to any of the React Context providers in your Next application. Next has no other mechanism to share this data other than down the React tree. You cannot using authcontext in middleware