I am trying to build a docker image, but next build keeps trying to read and even execute the code that uses the CONNECTION_STRING environment variable at build time.
I tried:
- Placing it into another variable:
const connectionString = process.env.CONNECTION_STRING; - Throwing an error when the environment variable is not present:
if (!connectionString) {
throw new Error('Please add your Mongo connection string to .env.local');
} - Making a function that reads the variable:
const getEnvironmentVariable = (name: string): string => {
const value = process.env[name];
if (!value) {
throw new Error(Missing environment variable: ${name});
}
return value;
};
and a few other tricks, none of which helped. I am dumbstruck that even when I managed to get past the "environment variable missing", I got an error instantiating the MongoClient:
new MongoClient(connectionString!, options)
Another thing to note is, that, when I deleted all of my app/api/<some_route>/route.ts files, which were using the mongo client, then the error went away, while I'm still using the client in NextAuth:
import mongoClient from '@/connectors/mongodb';
`...
callbacks: {
async signIn({ user }) {
const client = await mongoClient;
const dbUser = await client
.db()
.collection<{ role: string }>('users')
.findOne({ email: user.email });
if (!dbUser) return false;
return true;
},
},
...
Note that my NextAuth is set up in the pages folder, not the app folder.
So now I am absolutely stumped as to why the build insists so much on inlining what quite obviously to me should not be inlined as is documented as though it will not be inlined here:
https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables
and is not used at all on the client side.
Help? 