Santiago Padilla
Santiago Padilla

Reputation: 65

NextJS API Route Protected with API Key

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

Answers (1)

user21392777
user21392777

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:

  • Set up backend logic protecting against DDoS attacks (where hackers send a flood of traffic to the API, so that it's overwhelmed).
  • Check to make sure code isn't inserted into the API key using some form of sanitization, to prevent malicious code from being run on the server.

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

Related Questions