Reputation: 65
I am making an app in NextJS 13, I am using API routes and I want to protect them to prevent them from calling functions outside of what the app allows. In my app I use Auth0 but I do not require any protection to be used with Auth because within the app people without being registered can call functions.
So in my .env I added a random key, which protects all my API routes.
This is what it looks like when I call fetch:
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)
})
This is 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')
//
I this a good way to protect my API Routes?
Basically what I want to achieve is to protect my API from hackers.
Upvotes: 0
Views: 2355
Reputation:
For most projects, a setup with environment variables works perfectly, so I'd say you're good. Here's some additional steps you might want to take:
I'm not a security expert by any means, and there are hundreds of methods to secure your app. For most small projects, just a simple setup will be fine.
Many hosting providers (for example Vercel) also provide their own protection against DDoS attacks and other hacks, so you probably don't need to worry to much unless you're building everything from the ground up.
Upvotes: 0