API Routes Cors
Answered
Japanese flying squid posted this in #help-forum
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
}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
@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:
tsx
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
}
Japanese flying squidOP
I've every route protected with checking user inside the session and event than checking session user in my DB, so it's already well protected I guess, right?
if only these people should have access, then yes