Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Require jwt for all api routes

I have been searching through nextjs documentation and I found this thing.

import { getToken } from "next-auth/jwt"

const secret = process.env.NEXTAUTH_SECRET

export default async function handler(req, res) {
  // if using `NEXTAUTH_SECRET` env variable, we detect it, and you won't actually need to `secret`
  // const token = await getToken({ req })
  const token = await getToken({ req, secret })
  console.log("JSON Web Token", token)
  res.end()
}

source

This gives you the possibility to get the authentication, but I don’t know where to use it or how to implement it in all routes. I think it has to be in the /api/auth/[...nextauth.js] but I haven’t found any information about it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have all my api routes inside api folder.

Help is needed, thanks in advance!

>Solution :

Nextjs 12 has a new middleware feature, which is a good suit for your authentication, all you have to do is create _middleware.js file your API routes directory and export a middleware function.

// pages/_middleware.js
// this function runs before every request.
export function middleware(req, ev) {
 // define your authentication login here
  return new Response('Hello, world!')
}

the only downside is Native Node.js APIs are not supported.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading