简体   繁体   中英

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?

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM