'No environment variables with Next.js TypeScript Custom server

I am currently building a next.js app for a course at uni. I want to run a script when the development server starts that performs some API calls to update the database with new events for the webpage to display. I only want to run this script when the development server starts.

I therefore created a custom server since I thought that would give me the opportunity to call the function in the server file like below:

import next from 'next';
import { NextServer, RequestHandler } from 'next/dist/server/next';
import syncGasque from './lib/gasquesync';

const port = 3000;
const dev = process.env.NODE_ENV !== 'production';
const app : NextServer = next({ dev });
const handle : RequestHandler = app.getRequestHandler();

app.prepare().then(() => {
    const server = express();

    server.all('*', (req : Request, res : Response ) => handle(req, res));

    server.listen(port, () => {
        console.log("Server started at http://localhost:" + port+"/");
    });

    console.log(process.env.NODE_ENV); // Prints dev
    console.log(process.env.MONGODB_URI); // Prints the uri
    console.log(process.env.MONGODB_DB); // Prints the db name
    
    syncGasque();
});

I want to run "syncGasque" which is a script that establishes a connection to the database to perform some insertions and updates (mongodb), and naturally it needs the env variables for the db. The code works when I don't call the function: the server starts and the frontend displays information from the database. When i do include the function like above it does not work and gives me this error message:

/Users/simpen/dev/chalmers/dat257-hasse-andersson/client/lib/mongodb.ts:8
  throw new Error('Please add your Mongo URI to .env.local')
        ^
Error: Please add your Mongo URI to .env.local
    at Object.<anonymous> (/Users/simpen/dev/chalmers/dat257-hasse-andersson/client/lib/mongodb.ts:8:9)
    at Module._compile (node:internal/modules/cjs/loader:1095:14)
    at Module.m._compile (/Users/simpen/dev/chalmers/dat257-hasse-andersson/client/node_modules/ts-node/src/index.ts:1455:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1147:10)
    at Object.require.extensions.<computed> [as .ts] (/Users/simpen/dev/chalmers/dat257-hasse-andersson/client/node_modules/ts-node/src/index.ts:1458:12)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/Users/simpen/dev/chalmers/dat257-hasse-andersson/client/lib/db.service.ts:2:1)

Here is the scripts from my package.json file. I am using dev.

"scripts": {
    "dev": "NODE_ENV=development ts-node server.ts",
    "lint": "next lint",
    "build": "next build"
}

This is the mongodb.ts file:


declare global {
  var _mongoClientPromise: Promise<MongoClient>
}

if (!process.env.MONGODB_URI) {
  throw new Error('Please add your Mongo URI to .env.local')
}

const uri: string = process.env.MONGODB_URI
const options = {}

let client: MongoClient
let clientPromise: Promise<MongoClient>


if (process.env.NODE_ENV === 'development') {
  // In development mode, use a global variable so that the value
  // is preserved across module reloads caused by HMR (Hot Module Replacement).
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options)
    global._mongoClientPromise = client.connect()
  }
  clientPromise = global._mongoClientPromise
} else {
  // In production mode, it's best to not use a global variable.
  client = new MongoClient(uri, options)
  clientPromise = client.connect()
}

// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise

Any ideas as to why this is happening?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source