I have come across a similar question in the past, however, none of the solutions provided were able to resolve my issue.
Currently, I am attempting to utilize environment variables in Next.js with TypeScript, but I keep encountering this error:
An argument of type "string | undefined" cannot be assigned to the parameter of type "string". Type 'undefined' cannot be assigned to type 'string.
The environment variable I am trying to use is named: NEXT_PUBLIC_MONGODB_URI
and it is located in the root directory within the .env
file of my project.
I am referencing it in a file called db.ts which resides in /my-project/utils/db.ts like so:
import mongoose, { ConnectionStates } from 'mongoose';
interface IConnection {
isConnected: ConnectionStates | null;
}
const connection: IConnection = {
isConnected: null
};
async function connect() {
if (connection.isConnected !== null) {
console.log('already connected');
return;
}
if (mongoose.connections.length > 0) {
connection.isConnected = mongoose.connections[0].readyState;
if (connection.isConnected === 1) {
console.log('use previous connection');
return;
}
await mongoose.disconnect();
}
const db = mongoose.connect(process.env.NEXT_PUBLIC_MONGODB_URI);
}