Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
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.

I have all my api routes inside api folder.

Help is needed, thanks in advance!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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

  1. pages/index.js calls /api/cookie - this you will incorporate around your routes
  2. pages/api/cookie.js acts as your api route handler
  3. pages/api/cookie.js imports cookie logic (in your case jwt cookies

https://github.com/vercel/next.js/tree/canary/examples/api-routes-middleware

about 4 years ago · Juan Pablo Isaza Relatório

0

// 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");
  }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda