I’m using NextJS 14 App Router, and I have multiple Route Handlers for my APIs, but I was surprised to know that my friend was able to send requests to my Route Handlers using Postman from his PC.
I thought that by default they were protected because the headers in NextJS are following a same-origin policy.
But apparently, CORS (Cross-Origin Resource Sharing) and SOP (Same-Origin Policy) are server-side configurations that clients decide to enforce or not. And Postman does not enforce them.
So, Is there a way to prevent my Route Handlers from being accessed from outside my website?
This is my code.
// Client component || Form.tsx
async function sendText(text: string) {
const translateResponse = await fetch("/api/translate-text", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
text: text,
}),
});
const translatedData = await translateResponse.json();
}
// api/translate-text/route.ts
export async function POST(request: Request) {
const { text} = await request.json();
const res = await fetch(
`https://api-source.com`,
{
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
"Key": process.envAPI_KEY || "",
"Host": process.env.API_HOST || "",
},
body: new URLSearchParams({
from: "auto",
to: "en",
text: text,
}),
}
);
const translatedText = await res.json();
return NextResponse.json(translatedText, {
status: 201,
});
}