how to hide nextjs api routes from being directly accessible through url?

Viewed 4966

Is there any way to make next.js API routes response data hidden when accessing it through URL? I want to hide the routes because there is some data I don't want to be directly accessed by the user.

3 Answers

Probably quick & simple way to protect the API routes is through the stateless session management libraries like iron-session with save / creation and destroy endpoints to validate and invalidate the Next JS api routes

Try this github example by Vercel. This might a be good starting point.

Remember: Always use a best authentication mechanism to protect any direct api route call with appropriate privileges in place. DYOR

There is no way to hide API routes from users through url in nextjs. In fact, nextjs API routes are publically available to anyone when you host the website without exporting and hosting from out folder. I ended making server-side routes using node express and then connected to the frontend in nextjs.

Related