IBIL Global

Blog

Hybrid Rendering in NextJS

HOW YOU CAN PROTECT YOUR API KEY IN PRODUCTION ON JAMSTACK APPLICATIONS ?

Front-end developers must communicate with either private or public APIs, whose authentication process necessitates the usage of a secret key or API key. The necessity to preserve or secure the key(s) arises because they are valuable. The “go-to” option, which is typically used by developers, is to create an environment variable that saves the key, but there is a catch. The environment variable does not shield the key(s) from users who are familiar with their browser’s dev-tools. Therefore, while writing our API requests, we must utilise our keys server-side.

We will be covering more of this approach by using a NextJS framework

You can read more about Next.js here

Installing the NextJS framework:

npx create-next-app [name-of-your-app]

Next.js will be used in this post to bootstrap our project. The create-react-app library will still function despite this. You are free to utilise whatever one you find most useful. We utilise Next.js because of all the benefits it offers.

To retrieve data from the API, we’ll use the built-in “Fetch API” library in JavaScript. The style topic won’t be covered in

|–pages

|   |– api

|   |   |– MyserverSideCall.js

|   |– _app.js

|   |– index.js

|__ .env.local

In order to secure our API key, we are writing the API call at the server-side, and Next.js already makes this work simple for us. We can make API calls using Next.js’s API routes without worrying that our API keys will be exposed

export default async function

MyServerSideCall(req, res) {
const {
query: { firstName, lastName },
} = req;
const baseUrl = `https://example.com/v1/search?lastName=${lastName}&firstName=${firstName}
&apiKey=${process.env.KEY}`;
const response = await fetch (baseUrl);
res.status(200).json({
data: response.data,
});
}

We defined an asynchronous method named serverSideCall in the code above. It accepts two arguments: req, which is the full form of “request,” and res, which is the complete form of “response.”  

Req.query is one of the attributes, or “middlewares,” as the Next.js documentation refers to them, that may be accessed while we’re using our API.

As you can see from the sample above, we destructured the query property, therefore we should be able to provide those variables to the query properties of the API endpoint as values immediately.

The Above API will be invoked from the client side using axios like before, but here we will only call our proxy apis inside MyServerSideCall which inturn calls the real API with requires an API key

const response = await axios.get(baseUrl);
res.status(200).json({
data: response.data,
});