Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my API key visible when using next.js with environment variables?

I followed next.js documentation and added a custom api key on now server.

The problem is that when i run now dev and go to the sources tab, I can see my api key there.

enter image description here

The api key is saved in .env.build file, here is my code:

index.js

import { useState, useEffect } from 'react';
const axios = require('axios');

import Nav from '../src/components/Nav';
import Head from '../src/components/Head';
import Movies from '../src/components/movies';

const key = process.env.API_KEY;

const index = () => {
  const [currentMovies, setCurrentMovies] = useState([]);

  const getTopMovies = async url => {
    const fetchData = await axios.get(url).then(response => {
      const [...data] = response.data.results;
      setCurrentMovies({ data: data });
    });
  };

  useEffect(() => {
    getTopMovies(
      `https://api.themoviedb.org/3/discover/movie?primary_release_date.gte=2019-12-12&primary_release_date.lte=2020-02-22&api_key=${key}`
    );
  }, []);

  if (currentMovies.data === undefined) {
    console.log('Loading...');
  } else {
    console.log(currentMovies.data);
  }

next.config.js

module.exports = {
  env: {
    API_KEY: process.env.API_KEY
  }
};

now.config.json

{
  "build": {
    "env": {
      "API_KEY": "@api-key-moviedb"
    }
  }
}
like image 569
m00 Avatar asked Dec 18 '22 13:12

m00


1 Answers

NextJS implements environment variables with DefinePlugin from Webpack. All the variables used with process.env are replaced with variables in .env in compile time. From the docs:

Next.js will replace process.env.customKey with 'my-value' at build time.

Unlike on the server side, NextJS is still a client side framework for running JavaScript in the browser and as it stands there are no ways of hiding these keys from the browser.

If you have to hide the key, then you would have to add a server (or a serverless function).

You can add an API endpoint and call it from the frontend, which would connect to 3rd party service and return the fetched data.

One of the ways to do that is to add .env and load it to Node process with dotenv.

.env

API_KEY=@api-key-moviedb

next.config.js

require('dotenv').config();

module.exports = {
  /* config options here */
};

Usage

process.env.API_KEY

This way your API key won't be exposed.

Next.js with dotenv example

API routes in Next.js

like image 101
Agney Avatar answered Dec 31 '22 01:12

Agney