Swix
Swix

Reputation: 2113

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?

Upvotes: 10

Views: 31805

Answers (4)

TeeBeeGee
TeeBeeGee

Reputation: 368

If I understand your question, you want to know how to secure the endpoints so that you can only access them with a token right?

If so, a quick and easy way is to use Next-Auth along with the getSession hook.

    import { getSession } from 'next-auth/react';
          
    export default async function handler(
            req: NextApiRequest,
            res: NextApiResponse<Data>
        ) {
            const session = await getSession({ req });

            if (!session)
                return res.status(401).send({
                    message: 'Unauthenticated user. Your IP has been logged',
                });
            //handle the request here
}

Upvotes: 2

Moein Moeinnia
Moein Moeinnia

Reputation: 2341

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

Upvotes: 3

Quentin
Quentin

Reputation: 943097

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.

Upvotes: 3

Nitin Sharma
Nitin Sharma

Reputation: 27

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.

Upvotes: 1

Related Questions