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()
}
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.
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.