Search code examples
node.jsauthenticationnext.jsmiddlewareserver-side-rendering

How do I check if a user is logged in on every request in Next.js?


I need help with my Next.js project. I take the token in the cookie from the serverSideProps of each page and bring the profile information. The appearance of the profile information means that the user is logged in. I am using this code on every page. that didn't feel right. How will I check if the profile information exists in every query? And when is a protected route I need to redirect the user to the login page.

export async function getServerSideProps(context) {
  const token = await getToken(context);
  if (token) {
    const profile = await getProfile(token);
    if (profile) {
      return {
        props: {
          profile: profile.data.user,
          token,
        },
      };
    }
    //if user is not found redirect
    return {
      redirect: {
        destination: "/",
        permanent: false,
      },
    };
  }
  return {
    props: {},
  };
}

Solution

  • You can use middleware. in pages directory, create _middleware.js.

    import { NextResponse } from "next/server";
    
    // we are not exporting by default
    export async function middleware(req, ev) {
      
      const token = req ? req.cookies?.token : null;
      const profile = await getProfile(token);
      // if profile exists you want to continue. Also
      // maybe user sends request for log-in, and if a user wants to login, obviously it has no token
      const { pathname } = req.nextUrl;
      if (
        // whatever your api route for login is
        pathname.includes("/api/login") || profile 
      ) {
        return NextResponse.next();
      }
    
      
      if (!profile && pathname !== "/login") {
        // since you want to redirect the user to "/"
        return NextResponse.redirect("/");
      }
    }