Satish Baghel
Satish Baghel

Reputation: 55

Next Authentication with node js api

Please guide me on what I should use to authenticate.

Thanks in advance.

Upvotes: 0

Views: 870

Answers (1)

Spangle
Spangle

Reputation: 822

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.

Upvotes: 1

Related Questions