The current version of "next.js" (version 13.1.6) is experiencing issues with undefined environment variables

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);
}

Answer №1

The issue at hand is not related to "undefined next.js environment variables." By prefixing the env variable with NEXT_PUBLIC, you can access it in both experimental and regular client-side directories. The error actually pertains to TypeScript, requiring you to cast it using as string.

const db = mongoose.connect(process.env.NEXT_PUBLIC_MONGODB_URI as string);

If you run

console.log("dada", process.env.NEXT_PUBLIC_MONGODB_URI)
in an app directory file, the log should appear in the terminal. Likewise, in a client-side directory file, the log should show up in the browser console.

Answer №2

If you need to retrieve the environment variable in a client component, make sure to prepend it with NEXT_PUBLIC_. This means that all variables should start with NEXT_PUBLIC_

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on assigning a value to an object array within an Angular application

I need help figuring out how to update a value in an object array. The current object array is structured like this: objArr = [ { "id": "123", "name": "abc" }, { "id": "null", "name ...

Ways to simulate objects in jest

I'm facing an issue while trying to mock a function of an object using Jest and Typescript. Below is a concise version of my code: // myModule.ts export const Foo = { doSomething: () => { // ... does something console.log('original ...

Seeking assistance with using JavaScript to filter posts from Contentful for a Next.js website

Currently, I am integrating a Next.js blog with Contentful and employing queries to display posts on the homepage. While I can easily use .filter() to feature certain posts based on a boolean value, I am struggling to figure out how to fetch posts that mat ...

Steps for setting up a nested route in Angular 2

I am currently working on a project that includes an admin page (check the file structure below). I am trying to set up a child route named 'createuser' for the admin page (localhost:4200/admin/createuser). Despite my attempts, I encountered an e ...

Navigate to a different page using Angular with a simple click

How can I implement a redirect from clicking on the "Firms" word to another component page in Angular? I have tried using routerLink="/", [routerLink]="['/']". I have imported Routes in the app.module. I have also attempted this approach: import ...

Attempting to create a function that removes the first and last characters from a string, however encountering issues with the code in TypeScript

Currently, I am delving into the world of TypeScript and facing a challenge. The task at hand involves creating a function that returns a string without its first and last character. Can anyone offer assistance with this problem? Below is the code along wi ...

Setting up Webhooks for Previews on Vercel: A Step-by-Step Guide

Currently, my Next.js app is deployed using Vercel. The backend code in this app is designed to listen for events from third-party services through webhooks, such as the user creation event from Clerk. In order to make this work, I must set up the webhook ...

Implementing ETag in Angular 2

Implementing the odata standard which utilizes ETag has presented a challenge for me, particularly with PATCH requests. Each PATCH request requires sending the ETag in the header as If-None-Match. A HTTP status of 200 indicates that the change was successf ...

What is the best method for integrating Bootstrap 5's Sass capabilities into a NextJS project?

Currently, I am in the process of working on a NextJS project that involves integrating Bootstrap 5. While I have past experience with Sass and NextJS, I seem to be encountering some difficulties when attempting to leverage Sass features within Bootstrap. ...

What is the best way to restrict a mapped type in typescript to only allow string keys?

In the Typescript documentation, I learned about creating a mapped type to restrict keys to those of a specific type: type OptionsFlags<Type> = { [K in keyof Type]: boolean; }; If I want to use a generic type that only accepts strings as values: t ...

Encountering an "Unexpected token" error when importing a JSON file in TypeScript even though the JSON is valid

I recently read an article on Hacker Noon about importing JSON into TypeScript, and decided to give it a try in my code. Here's the import line I used: import data from './assets/fonts/helvetiker_bold.typeface.json'; To test if the import ...

Issue with setting a background image to a div in Next.js: not functioning as expected

I haven't used Next.js before and I'm having trouble setting a background image for a specific div. I have a folder named public in the root directory where I've placed the file art-thing.jpg. My styles.css is also in the root directory, whi ...

What is the process of specifying mapped types for function return types in TypeScript version 4.5.4?

Previously, in typescript 4.4.4, this code compiled successfully: /** * type to get only those properties that are functions */ type FunctionProperties<T> = { [P in keyof T]: T[P] extends (...args: any) => any ? P : never; }[keyof T]; type Re ...

Choosing a personalized component using document selector

Currently, I am working on an application using Stenciljs and have created a custom element like this: <custom-alert alertType="warning" alertId="warningMessage" hide>Be warned</custom-alert> The challenge arises when attem ...

Executing a function to erase the stored value in local storage during an Angular unit test

Looking to verify whether the localStorage gets cleared when I execute my function. Component ngOnInit() { // Logging out when reaching login screen for login purposes this.authService.logout(); } authService logout() { // Removing logged i ...

Consistent navigation within a NextJs application

I'm currently developing a Next.js application and I face the challenge of fetching navigation content from my Prismic API server-side. I want to retrieve the data once and pass it to my Header component to ensure a persistent navigation menu across a ...

Angular - Showing validation messages post successful execution of two functions

I have encountered an issue with my form submission process involving two functions. When both functions succeed, I want to display a successful validation message. However, currently the success message is displayed even if the second function fails. How ...

Develop an object's attribute using form in the Angular 5 framework

I am looking to create an object for a location that includes two parameters. While I can easily create an array of strings using FormGroup, I am unsure of how to create an object with two parameters nested inside it. Below is the code snippet I currently ...

Error encountered: TypeError - The function formData.set is not supported. Unable to resolve this issue

Whenever I try to update the blog, an error occurs after reloading the browser. This error gets resolved when I refresh the browser before updating the blog. I have used formData.set in handleToggle and handleTagsToggle and it works fine there. However, ...

Utilizing a third-party npm package within an Angular 2 project

I have been trying to integrate the file-system npm library into my Angular 2 project by following these steps closely: https://medium.com/@s_eschweiler/using-external-libraries-with-angular-2-87e06db8e5d1#.1dx1fkiew Despite completing the process, I am e ...