简体   繁体   中英

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: {},
  };
}

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("/");
  }
}

If you are using Next.js version 12 and higher, you can use next middleware .

If not, you can use getServerSideProps in app.js , and pass the result to the page (Component) as prop. As shown here.

Next.js has a middleware feature to filter requests and run code before the request is completed, so then you can modify the response, redirect do anything you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM