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

469
Visualizações
How to protect API routes in Next.js?

I am using Next.js API routes - https://nextjs.org/docs/api-routes/introduction but I don't know how to protect them from public.

Now those routes are public in my production server.

For example: when I go to mysite.com/api/cats in browser, it returns -

{ success: true, data: [...] }

Please help, how do I hide those API routes from public?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

If you prevent the browser from requesting the URL then the user won't see the data when they type the URL into the address bar and your JavaScript won't see it when it makes an Ajax request to the same URL.

You can't hide the data from the user of the browser while still allowing your application running in the same browser to access it.

over 4 years ago · Santiago Trujillo Relatório

0

Using getSession()# You can protect API routes using the getSession() method.

Using getToken()# If you are using JSON Web Tokens you can use the getToken() helper to access the contents of the JWT without having to handle JWT decryption / verification yourself. This method can only be used server side.

See here : https://next-auth.js.org/tutorials/securing-pages-and-api-routes#:~:text=You%20can%20protect%20API%20routes%20using%20the%20getSession()%20method.

over 4 years ago · Santiago Trujillo Relatório

0

1.Use Authentication :

export default async function apiRouteName(req, res) {
  //way of getting the token totally depends on your preference
  let token = req.cookies.jwtToken || req.headers.jwtToken || req.query.jwtToken
  
  if(!token) {
    return res.status(401).json({message:"you are not allowed"});
  }
  
  let data = {}; //store your data in  this variable
  return res.status(200).json({data})
  
}

2.Middleware :

import { NextResponse } from "next/server";

export function  middleware (req  ,  event ) {
   //way of getting the token totally depends on your preference
   let token = req.cookies.jwtToken || req.headers.jwtToken
   if (!token ) {
     return NextResponse.redirect('/login');
   }
   
    return NextResponse.next();
}

over 4 years ago · Santiago Trujillo 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