Shivam Modi
Shivam Modi

Reputation: 150

How to hide nextjs API routes from being directly accessible through URL?

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.

Upvotes: 10

Views: 28962

Answers (7)

Athar Qadri
Athar Qadri

Reputation: 1

I have searched a lot for the proper way. But it seems only solution is to use Nginx as reverse proxy server which can hide the api routes and only allow selected routes.

Upvotes: 0

MBŠ
MBŠ

Reputation: 397

you can do this by implementing a secret token that you pass in the headers of each request to the api and you can in the backend check if the token is not here you can display another message to the user

Upvotes: 0

Dupflo
Dupflo

Reputation: 396

In Next.js version 13 you can use middleware to stuck the user from directly checking the route of your api by checking the req.referer then only your app can call and api of your app. Auth token can also be use inside middleware.

https://nextjs.org/blog/next-13-1#nextjs-advanced-middleware

import { NextResponse } from 'next/server'

import type { NextRequest } from 'next/server'

export function middleware(req: NextRequest) {

    const url = req.nextUrl
    const { pathname } = url

    if (pathname.startsWith(`/api/`)) {
        if (!req.headers.get("referer")?.includes(process.env.APP_URL as string)) {
        return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
        }
      }

     return NextResponse.next()

}

export const config = {
  matcher: ['/((?!_next|fonts|examples|svg|[\\w-]+\\.\\w+).*)'],
}

process.env.APP_URL is the url of your app for example : http://localhost:3000

Upvotes: 11

stanley355
stanley355

Reputation: 171

You can set an authorization header that checks auth key everytime user access that API, that way normal user wont be able to access the page without knowing the auth key

Upvotes: 1

Rugved Patel
Rugved Patel

Reputation: 70

It is extremely unworthy effort to hide API routes. and for protecting essential data in API..there is CORS and Authentication methods can prevent noicy unwanted traffic I found brilliant blog on this

https://dev.to/a7u/how-to-protect-nextjs-api-routes-from-other-browsers-3838

Upvotes: 0

NiRUS
NiRUS

Reputation: 4259

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

Upvotes: 2

Shivam Modi
Shivam Modi

Reputation: 150

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.

Upvotes: 0

Related Questions