Hide your API Keys with Netlify Functions
Tags: react, tutorial, webdev
Published: 2019-08-16 10:00:46

---
title: Hide your API Keys with Netlify Functions
published: true
description: A tutorial on how to handle form submissions and how to hide your API keys by using the free Netlify functions.
tags: react, tutorial, webdev
---

In March I published a tutorial on [how to handle form submissions in Gatsby and using Airtable](https://dev.to/fabiorosado/handle-form-submission-in-gatsby-with-airtable-5bg2) as your backend. I was pretty convinced that by hiding your API keys with `process.env` they would be hidden away from view.

The tutorials and the blog posts that I read, all said that your keys would be hidden if you just used `process.env`. In a way that is true and if you inspect the code on your browser the keys will be hidden.

Then [Fran Caballero](https://twitter.com/fjcero) commented on my blog, saying that the keys would be shown in the network tab after you made the request. This happens because Airtable expects you to pass your API Key as a parameter in the header of your request.

As a reminder, the code from the tutorial looks like this:

```js
 handleSubmit = e => {
 const fields = {"fields": {"Name": this.state.name, "Notes": this.state.notes}}
 fetch("<https://api.airtable.com/v0/><account id>/<table name>", {
 method: "POST",
 headers: {"Authorization": `Bearer ${process.env.AIRTABLE_API}`,
 "Content-Type": "application/json"},
 body: JSON.stringify(fields)
 })
 .then(() => alert("Form Sent!"))
 .catch(error => alert(error))
 
 e.preventDefault();
 }
```

As you can see, the API key is being passed in the headers and when a request is made the headers are exposed through the network tab. That means, everyone can see the API Key.

I needed a solution to keep the API keys hidden.

## Netlify functions to the rescue!

Most of my sites are being served by Netlify and Netlify functions looked like the solution for this problem.

Netlify functions are nothing more, nothing less than functions run on the server. So the API keys should remain hidden from prying eyes.

A great thing about Netlify functions is that you can use 125k calls and 100minutes for free in a month per site. 

Setting up functions for your Netlify site is pretty easy. All you need to do is create a folder, in the root of your project, inside this folder, you will put your functions. Then tell Netlify where to find this folder.

I like to put all the things related to Netlify inside a folder called `.netlify`. Inside that `.netlify` folder I just created another folder called `functions`.

Now all I needed to do was to tell Netlify where my functions were. To do this, all you need to do is login into your Netlify account, choose the site that will be using the functions and then press the functions tab. In this tab, you just need to write the path of your folder.

In my case, I just wrote `.netlify/functions`. Then you can push new changes or redeploy your site and Netlify will find the folder automatically - you will get an email saying that you are now using functions on your site.

## Netlify functions rules

Netlify functions let you deploy AWS functions without the need to have an AWS account. At the moment you can write your functions using Javascript or Go.

Your javascript function will need to export a handler and should look like this:

```js
 exports.handler = function(event, context, callback) {
 // your server-side functionality
 }
```

When you call a function the handler will get an event object that will look similar to this:

```json
 {
 "path": "Path parameter",
 "httpMethod": "Incoming request's method name"
 "headers": {Incoming request headers}
 "queryStringParameters": {query string parameters }
 "body": "A JSON string of the request payload."
 "isBase64Encoded": "A boolean flag to indicate if the applicable request payload is Base64-encode"
 }
```

So when you call your netlify function, the headers, method and path that you add will be available to you by writing `event.path`, `event.headers` and `event.method`.

Finally, the callback will be what your Netlify function will return when you run it. This is where you handle success/failure and any response that you might need.

## Creating a server-side function for airtable

I'm going to use the example above on how to handle form submissions and send them to airtable.

First, create a file inside your netlify functions folder called `airtable.js`.

Now you need mix the handler format and the fetch request shown above. The function will look like this:

```js
exports.handler = async (event, context, callback) => {
  const pass = (body) => {callback(null, {statusCode: 200, body: JSON.stringify(body)})}

  try {
    let response = await fetch("https://api.airtable.com/v0/<account id>/<table name>", 
  {
   method: event.httpMethod,
   headers: {
     "Authorization": `Bearer ${process.env.AIRTABLE_API}`, 
     "Content-Type": "application/json"
  },
   body: event.body
  })
   let data = await response.json()
   await pass(data)
 } catch(err) {
     let error = {
       statusCode: err.statusCode || 500,
       body: JSON.stringify({error: err.message})
 }
  await pass(error)
 }
}
```

Notice that I am using `process.env` to get the Airtable API Key. Netlify will get the key automatically from the environmental variables since they are living server-side. 

## Connecting your form to the Netlify function

Now that we have our function, all that is left to do is to connect our form to the netlify function. Netlify makes it pretty easy for us to do this, all you need to do is use the path of your function on the fetch request.

Let's say that our form is located on the component called `Notes` and its full path is `your-awesome-site/src/components/Notes.js` we need to change our form to this:

```js
handleSubmit = e => {
  const fields = {
    "fields": {
      "Name": this.state.name, 
      "Notes": this.state.notes
      }
     }
    fetch("../../.netlify/functions/airtable", {
    method: "POST",
    body: JSON.stringify(fields)
    })
    .then(() => alert("Form Sent!"))
    .catch(error => alert(error))
 
    e.preventDefault();
 }
```

Notice that we are fetching the Netlify function airtable from the root folder. Also, we took the headers param from the request since we are using it on the server-side function. 

So this fetch request will just call the netlify function and pass the form fields into the server-side function and that server-side function is the one calling the Airtable API.

This is all you need to do to hide your API keys and use Netlify functions. If you want to log things from your Netlify function you can use `console.log` and this log will be available within your function screen inside your Netlify account - from the functions tab.