0
  • I'm new to the Next js and developing the Next js website. I am stuck in multiple authentications with different routes and roles. How can I handle it in the next js?
  • Frontend: Next js
  • Backend: Node js with JWT (JSON web token).

Please guide me on what I should use to authenticate.

Thanks in advance.

1
  • use the getServerSideProps method to fetch data for a page on the server-side and pass it to the page as props. Commented Dec 5, 2022 at 4:33

1 Answer 1

1

I am assuming you have done a couple things with my answer below:

  1. you are setting a http only authenticated cookie / signing it, expiring it etc
  2. On api requests, you are validating this cookie

You can create a middleware.ts / .js file on the root of your project, something like the following (note I was using typescript, you can just remove the types if using javascript):

// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

const protectedPages = ["/something", "/foo", "/profile"];

export function middleware(request: NextRequest) {
  if (protectedPages.find((page) => page === request.nextUrl.pathname)) {
    const token = request.cookies.get("YOUR_TOKEN_NAME");
    if (!token) {
      // send the user back to the sign in / home page or wherever
      const url = request.nextUrl.clone();
      url.pathname = "/home";
      return NextResponse.redirect(url);
    }
  }
}

You do not need to import this anywhere, just do this, get the cookie and you are done. No Cookie with the name you gave it, show them the door.

Take a read of the docs from if you want to know more, they explain things better than me :) https://nextjs.org/docs/advanced-features/middleware

Can also combine this with the above suggestion with getServerSideProps to pass the data as a prop to the component.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.