Help needed re : usage of environment variable / snippet injection

Hi there,

A very basic question from a newbie….

I have created a basic front end only news reader application with vanilla JS, no frameworks, which fetches news from a third party API and display them on the front end.

Site name is:

https://clabs-newsreader.netlify.app/

I would not want to share the api key, so I have hidden the api key in a config.js file, and then placed it into a script in the HTML, and then created a variable on index.js to use on the call to the API :

//config.js

const config = {

API_KEY: “***********”

}

HTML

<script src="config.js"></script>

<script src="index.js"></script>

JS

const apikey = config.API_KEY

const topHeadlines = https://content.guardianapis.com/search?api-key=${apikey}&show-fields=thumbnail;

The app works fine locally, however does not when deployed to netlify. Console error is :

index.js:8 Uncaught ReferenceError: config is not defined

I have tried:

  1. setting the apikey as environment variable through netlify UI - does not work

2.added a snippet injection trough netlify UI ( )- does not work either

Am i missing something?

Thanks in advance

Your config.js script returns 404, thus the error.

If there is a link to your config file in your HTML, your API key is not hidden, it’s just moved. Anyone looking for it will be able to find it.

@hrishikesh @gregraven Thanks both!!

I understand config script gives 404 as it is included into a .gitignore

I guess I was just looking for a way to try and hid the apikey, mainly because I am trying to put a portfolio in place & was trying to show that I am also thinking about security of my application…

Any advice for what I am trying to achieve?

Many thanks again!

You’ll have to make use of a Netlify Function to be able to hide your API key. If you use an environment variable in your JS build, it will still show up on your site.

Here’s a simple Netlify function get-headlines.js to get you going:

exports.handler = async (event, context) => {
  const headlines = `https://content.guardianapis.com/search?api-key=${process.env.API_KEY}&show-fields=thumbnail;`
  return {
    statusCode: 200,
    body: headlines
  };
};

You’ll have to set an environment variable called API_KEY for it to work.

You then fetch it kinda like this (untested)

const response = await fetch('/.netlify/functions/get-headlines, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  }
}).then((res) => res.json());

console.log(response.body);

For obvious reasons I wouldn’t copy and paste this to use in production. I recommend you read up on Netlify Functions in the docs and browse through the playground a bit

2 Likes

Hi, @0750kosse. We also have a support guide here about how to use Functions to keep your API keys safe:

1 Like