Search code examples
reactjsfetchnext.js

Why is fetching data in next.js with hardcoded api-key working but not with environment variable?


I followed the documentation of Next.js, so I created a file called .env.local and stored my API key inside.

When console.logging that key it gets shown in the server-console and not in the browser console. So far I understand this.

Problem: I want to fetch some data from the given URL. How can I get this done, without giving my API_KEY to the browser?

I think that topic is quite confusing for beginners (as me) and I an many other (so I think) would be overjoyed if anyone could get the confusion out of that.

Here is my code: (If I hardcode my API_KEY inside the URL it works fine)

import Haversine from '../components/Haversine'
import LangLat from '../components/LangLat'
import axios from 'axios'
import { useEffect } from 'react'

const key = process.env.API_KEY

const index = () => {
  console.log(key)

  const getLangLat = async () => {
    try {
      const response = await axios.get(
        `https://geocode.search.hereapi.com/v1/geocode?q=wimpfener str 40 backnang&apiKey=${key}`
      )
      console.log(response.data)
    } catch (err) {
      console.error(err.message)
    }
  }
  useEffect(() => {
    getLangLat()
  })
  return (
    <div>
      <Haversine />
      <LangLat />
    </div>
  )
}

export default index

Solution

  • You need to add NEXT_PUBLIC_ to the beginning of your environmental variable so you have access to it on the client side.

    So inside of your .env.local change

    API_KEY to NEXT_PUBLIC_API_KEY and do the same inside of your code.

    https://nextjs.org/docs/basic-features/environment-variables#loading-environment-variables