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!
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 /pages directory and export a middleware function.
// pages/_middleware.js
// this function runs before every request.
export function middleware(req, ev) {
// define your authentication logic here
return new Response('Hello, world!')
}
the only downside is Native Node.js APIs are not supported.
Given your question is around API routes, You need API routes with middleware
The new middleware for pages can be confusing but this uses the incoming request for an api as an intermediary e (e.g: api/auth.js) that receives a req object that you can then further inspect for the token.
See their example using API Routes with Middleware (no _middleware.js involved.
It get the incoming request to /api/cookie and adds a cookie header
pages/index.js calls /api/cookie - this you will incorporate around your routespages/api/cookie.js acts as your api route handlerpages/api/cookie.js imports cookie logic (in your case jwt cookieshttps://github.com/vercel/next.js/tree/canary/examples/api-routes-middleware
// next.js middleware does not take res as argument
export default async function handler(req, ev) {
console.log('what is ev',ev)
const token = await getToken({ req, secret });
// sinde you use jwt, you have to somehow extract userId
const userId = await verifyToken(token);
// you do not need to check for authentication if user wants to login
const { pathname } = req.nextUrl;
// static is folder that you Load images. You might use something else. if you dont add check, your images wont load
if (
pathname.includes("/api/login") ||
userId ||
pathname.includes("/static")
) {
return NextResponse.next();
}
if (!token && pathname !== "/login") {
return NextResponse.redirect("/login");
}
}