最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to protect API routes in Next.js? - Stack Overflow

programmeradmin6浏览0评论

I am using Next.js API routes - 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/api/cats in browser, it returns -

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

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

I am using Next.js API routes - https://nextjs/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./api/cats in browser, it returns -

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

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

Share Improve this question edited Feb 26, 2021 at 11:38 Swix asked Feb 26, 2021 at 11:35 SwixSwix 2,11311 gold badges38 silver badges57 bronze badges 2
  • 2 Define "public". Are you trying to stop people using your app from accessing the API? How is the app supposed to access the API then? – Quentin Commented Feb 26, 2021 at 11:44
  • My app has only one page (index), / and it doesn't use authentication. For example when you go to mysite./api/cats in browser, you will see the raw json data. I just want to prevent that. Is it possible? – Swix Commented Feb 26, 2021 at 11:52
Add a ment  | 

4 Answers 4

Reset to default 3

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

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
}

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/tutorials/securing-pages-and-api-routes#:~:text=You%20can%20protect%20API%20routes%20using%20the%20getSession()%20method.

发布评论

评论列表(0)

  1. 暂无评论