Hide Sensitive Information from the Consumers of Next.js API

Share this video with your friends

Social Share Links

Send Tweet

We'll learn how to use Next.js API Routes to hide sensitive information from the clients. In this case, we're calling the JSON Placeholder API with a "secret" value in the headers. All that sensitive information is hidden from the clients since they don't call, or even know, that we're calling the JSON Placeholder API under the hood.

Instructor: [0:00] All right. Let's start by creating a secret proxy API route. We're going to create a handler function that has two arguments, the request and the response. We're going to export that handler function as the default export for this file.

[0:24] What this route is going to do, is that we are going to get a secret todo item from this function that we're going to create in a second that is called getSuperSecretData. We're going to return it to the client as a JSON.

[0:43] We're going to call this todo. This is going to be the secret todo. The idea behind the getSuperSecretData function is that we're going to call another endpoint with sensitive data. Here, we are going to call the JSONPlaceholder API. Here, we're going to send sensitive information in our headers. Let's create an Authorization header. This is going to be superSecretValue.

[1:20] Now, we're going to return whatever that JSONPlaceholder API has, and we just return their result. Let's call this secret proxy endpoint. We're going to print out the request information. As you can see, we don't have any Authorization header here. We're getting the JSONPlaceholder data through our secret proxy handler here.

[1:50] To recap, we can use API routes to hide sensitive information from the consumers of our API. In this case, getSuperSecretData is sending a request to JSONPlaceholder, and it is also setting an Authorization header with a superSecretValue that no one should know. Because all this is executed in Node, there is no way that the consumers know about it.