1. 11
    Generate a Custom API Key to Secure an API Route in Next.js
    1m 10s

Generate a Custom API Key to Secure an API Route in Next.js

Jon Meyers
InstructorJon Meyers
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

Currently, our API route can be used by anyone navigating to its endpoint. To ensure that this function can only be executed by our application, we need to create a special secret value.

In this video, we generate a special key to secure our API route. This value must be provided as a query parameter on the request to our endpoint, or an error response will be sent back.

To confirm this is working correctly, we use the Thunder Client extension. When the API_ROUTE_SECRET is not provided we receive a 401 response. When the correct value is attached our serverless function executes, creating a stripe customer and updating our profile table in Supabase.

Instructor: [0:00] Currently, our API route is entirely open to the public. Someone could just sit here, sending this request to this URL over and over and over again and creating a whole bunch of customers in Stripe. Let's generate our own API key to ensure that the person making a request to this API route is indeed us and not just some stranger.

[0:15] I'm going to quit my development server and then run this snippet from the Auth0 docs to create a random string using the crypto library. Now, I'm going to copy this value and create a new environment variable, and I'm going to call this API_ROUTE_SECRET. We can start our development server again.

[0:33] Now, back in our serverless function, before we do any processing, we can check whether the user has passed us a query parameter for that API_ROUTE_SECRET. If it's not equal to our process.env.API_ROUTE_SECRET, then we want to return a response saying the status is 401 and say that this person is not authorized to call the API.

[0:54] Now, if we try to send this request again, we get a 401, saying that we are not authorized to call this API. If we attach a query parameter for API_ROUTE_SECRET and set it to our value, we can send this request again, and it successfully creates our Stripe customer for us.