Home > Enterprise >  JWT Authentication with NextJS
JWT Authentication with NextJS

Time:08-22

I've searched around a bit, but have not found any clear, up-to-date, answers on this topic.

I'm trying to implement JWT authentication in my NextJS application. The following is what I have so far.

  • /login endpoint that will (1) check that the user/pass exists and is valid, and (2) create a JWT token based on a private RS256 key.
  • Created a middleware layer to verify the JWT

The creation of the JWT is fine - it works perfectly well reading the key from the file-system and signing a JWT.

However, I've run into the problem of the middleware being unable to use node modules (fs and path) because of the edge runtime (read here). This makes it so I'm unable to read the public key from the FS.

What is the proper way to verify a JWT token on every request? I've read that fetching from middleware is bad practice and should be avoided. All other reference on this topic (that I found) either uses a "secret" instead of a key (and can therefor be put into process.env and used in middleware) or glosses over the fact (1). Or should I just create a separate express application to handle JWT creation/verifying?

CodePudding user response:

What I do is add a file (_middleware.tsx) within pages. This ensures the file runs each page load but is not treated as a standard page. In this file lives an Edge function. If the user is not signed in (no JWT in cookies) and tries to access a protected page, he is immediately redirected to /signin before the server is even hit.

import { NextResponse } from "next/server";

const signedInPages = ["/admin", "/members "];

export default function middleware(req) {
  if (signedInPages.find((p) => p === req.nextUrl.pathname)) {
    const { MY_TOKEN: token } = req.cookies;

    if (!token) {
      return NextResponse.redirect("/signin");
    }
  }
}

CodePudding user response:

you send the token in the post request header.

{Authorization: 'Bearer '   token}

And then verify that token on the server, before sending data back

To verify the token you create a middleware function, then use that function on any route you want to portect

router.get("/", middlewarefunction, function (req: any, res: any, next: any) {
  res.send("/api")
})
  • Related