How to protect API routes in Next.js?

Viewed 7635

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?

3 Answers

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.

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

Related