Ubeydullah Yılmaz
Ubeydullah Yılmaz

Reputation: 117

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

Upvotes: 0

Views: 18520

Answers (3)

msabic22
msabic22

Reputation: 363

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.

Upvotes: 0

Kaneda
Kaneda

Reputation: 721

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

Upvotes: 0

Yilmaz
Yilmaz

Reputation: 49551

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

Upvotes: 3

Related Questions