I'm developing an app in NextJS 13 that utilizes API routes, and I aim to secure them against any unauthorized access from external functions. While my app integrates Auth0, there is no strict requirement for protection since unregistered individuals can access the functions. To safeguard the API routes, I've included a unique key in my .env file.
When making a fetch call, this is how it looks:
const req = await fetch(`${process.env.BASE_URL}/api/${path}`, {
method: method,
headers: {
'Content-Type': 'application/json',
'authorization': process.env.API_KEY!,
},
body: JSON.stringify(body)
})
Here's an example of one of my API Routes:
export async function DELETE(req: NextRequest) {
try {
// Validate API KEY
const headersInstance = headers()
const authorization = headersInstance.get('authorization')
if (!authorization || authorization !== process.env.API_KEY) throw new Error('Invalid API_KEY')
//
Do you think this approach effectively protects my API Routes?
Essentially, my goal is to fortify my API against potential hackers.