简体   繁体   中英

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.

在此处输入图片说明

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"
    }
  }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM