-1

I am trying to read .env in next.js inside the next.config.js

this is how it looks

require("dotenv").config({ path: require("find-config")(".env") })

console.log(process.env.API_URL)

module.exports = {
  reactStrictMode: true,
  sassOptions: {
    includePaths: [path.join(__dirname, 'styles')],
  },
  baseURL: process.env.API_URL,
}

and this prints the value from .env on the server console.

And now If i use this baseUrl in the component like this

import config from "../../next.config";

const axiosInstance = axios.create({ baseURL: config.baseURL }); 

then even code does not compile

Module not found: Can't resolve 'fs'

Import trace for requested module:
./next.config.js

what can be the issue?

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
  • is your `axiosInstance` being used by a `getServerSideProps` render, api route or client side render? The filesystem is not present on client side. – Trevor V Nov 27 '21 at 03:53

1 Answers1

1

Looks like you are trying to access your axios instance in a client side component. The filesystem in not available client side. Take a look at NextJS Public Environment Variables. If you prefix a NEXT_PUBLIC_ in an environment variable you can access it on a client side component like this.

.env file
NEXT_PUBLIC_API_BASE_URL = 'https://myapi...'
const axiosInstance = axios.create({ baseURL: process.env.NEXT_PUBLIC_API_BASE_URL }); 
Trevor V
  • 1,958
  • 13
  • 33