Protecting your API keys with Next JS

This is the story of Max.

Max thought his API keys were safe because he put them inside an .env file.

Max didn’t know his keys were visible in the network tab.

?

Max is actually me, Max is actually everyone.

Especially when we are jus…


This content originally appeared on DEV Community and was authored by Ivan Maximiliano Saldano

This is the story of Max.

Max thought his API keys were safe because he put them inside an .env file.

Max didn't know his keys were visible in the network tab.

Screenshot from 2021-02-12 15-25-47.jpg
?

Max is actually me, Max is actually everyone.

Especially when we are just learning and start playing with public APIs that require a private key.

There is not a good (or any) way to protect your keys in the frontend.
One good alternative is to create a proxy in your own server, since backend code is not exposed to the browser. But many people using these APIs are beginners that don't know much about backend yet.

Well, Next JS comes to save the with its integrated and ready to use API Routes. Which is basically a Node JS environment that you can use to create API endpoints, a server ready to go.

Let's take a look.

Initial setup

First let's create a next js app.

In the terminal run

npx create-next-app next-api-key
# or
yarn create next-app next-api-key
Enter fullscreen mode Exit fullscreen mode

Then move to the app folder

cd next-api-key
Enter fullscreen mode Exit fullscreen mode

A different .env file

Once inside the project we can create a .env.local file. This looks the same as your normal .env files if you are familiar with them. The difference is that the variables inside .env.local are only available in the Node JS environment of Next. This means the browser doesn't have access to them.

So where can we use these variables?

Inside pages, there is another folder called api, any file inside here will be treated as an API endpoint.

It works more or less like this.

On the server side we have pages/api/hello.js

export default (req, res) => {
  res.status(200).json({ name: 'John Doe' })
}
Enter fullscreen mode Exit fullscreen mode

On the client side we can call.

const fetchHello = async (page) => {
  const res = await fetch(`/api/hello`); // notice the naming
  const data = await res.json();
// data = { name: "John Doe" }
  return data;
};
Enter fullscreen mode Exit fullscreen mode

Protecting the keys

So now that we know how that works, let's add a key in the .env.local file.

Let's pretend I have a key that I need to send in the url of my request.

Let's add the key inside .env.local

SECRET_KEY=someSecretKeyThatNoOneShouldSee
Enter fullscreen mode Exit fullscreen mode

And instead of using our key on the client side, we use it inside hello.js.

This variable won't work on the client anyways, read more here

// pages/api/hello.js
import axios from "axios";

export default async (req, res) => {
  const URL = `https://api.i.require.keys/?&api_key=${process.env.SECRET_KEY}`;
  const response = await axios.get(URL);
  res.status(200).json({ data: response.data })
}
Enter fullscreen mode Exit fullscreen mode

You will need to install axios, node-fetch or a similar library to manage the fetching, since fetch API is not available in Node.

Nothing really changes on the client side, but let's use axios since we already installed it for the server.

const fetchHello = (page) => axios.get('/api/hello')
Enter fullscreen mode Exit fullscreen mode

And that's about it, our key is nowhere to be seen in the network tab.

That wasn't too hard right?

Please like and share if you found this helpful.

Until next time!


This content originally appeared on DEV Community and was authored by Ivan Maximiliano Saldano


Print Share Comment Cite Upload Translate Updates
APA

Ivan Maximiliano Saldano | Sciencx (2021-02-12T13:36:49+00:00) Protecting your API keys with Next JS. Retrieved from https://www.scien.cx/2021/02/12/protecting-your-api-keys-with-next-js/

MLA
" » Protecting your API keys with Next JS." Ivan Maximiliano Saldano | Sciencx - Friday February 12, 2021, https://www.scien.cx/2021/02/12/protecting-your-api-keys-with-next-js/
HARVARD
Ivan Maximiliano Saldano | Sciencx Friday February 12, 2021 » Protecting your API keys with Next JS., viewed ,<https://www.scien.cx/2021/02/12/protecting-your-api-keys-with-next-js/>
VANCOUVER
Ivan Maximiliano Saldano | Sciencx - » Protecting your API keys with Next JS. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/02/12/protecting-your-api-keys-with-next-js/
CHICAGO
" » Protecting your API keys with Next JS." Ivan Maximiliano Saldano | Sciencx - Accessed . https://www.scien.cx/2021/02/12/protecting-your-api-keys-with-next-js/
IEEE
" » Protecting your API keys with Next JS." Ivan Maximiliano Saldano | Sciencx [Online]. Available: https://www.scien.cx/2021/02/12/protecting-your-api-keys-with-next-js/. [Accessed: ]
rf:citation
» Protecting your API keys with Next JS | Ivan Maximiliano Saldano | Sciencx | https://www.scien.cx/2021/02/12/protecting-your-api-keys-with-next-js/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.