Next.js Discord

Discord Forum

API Routes Cors

Answered
Japanese flying squid posted this in #help-forum
Open in Discord
Japanese flying squidOP
As I knew, API Routes can be used only from the app itself. So for example if domain is example.com, only example.com can send API reuqests to Next API Routes, but as I've tested, it can be accessed from anywhere.
Answered by B33fb0n3
yes, api routes can be accessed from everywhere and that's the intended way. To make only your app be able to execute your routes, check a secret token inside your protected routes, that only your app knows. It could look something like this:

export async function GET() {
  const headersList = headers()
  const auth = headersList.get('token')

  if(auth !== process.env.ROUTE_HANDLER_SECRET_TOKEN)
    return Response.json(null, {status: 401}) // unauthorized
 
// do regular stuff 
  return Response.json({ data }) // actual data
}
View full answer

4 Replies

Japanese flying squidOP
How to fix it?
@Japanese flying squid As I knew, API Routes can be used only from the app itself. So for example if domain is example.com, only example.com can send API reuqests to Next API Routes, but as I've tested, it can be accessed from anywhere.
yes, api routes can be accessed from everywhere and that's the intended way. To make only your app be able to execute your routes, check a secret token inside your protected routes, that only your app knows. It could look something like this:

export async function GET() {
  const headersList = headers()
  const auth = headersList.get('token')

  if(auth !== process.env.ROUTE_HANDLER_SECRET_TOKEN)
    return Response.json(null, {status: 401}) // unauthorized
 
// do regular stuff 
  return Response.json({ data }) // actual data
}
Answer
if only these people should have access, then yes