Skip to content
This repository was archived by the owner on Jan 11, 2023. It is now read-only.
This repository was archived by the owner on Jan 11, 2023. It is now read-only.

Allow process.env.PORT to be defined via .env file #1254

@martinburger

Description

@martinburger

I would like to use dotenv to configure the port number the app listens on via a .env file.

I minimal implementation of that approach follows these steps:

  1. Start new project using npx degit "sveltejs/sapper-template#rollup" sapper-dotenv-port.
  2. Install dotenv via npm install dotenv.
  3. Create .env file with content PORT=5000.
  4. Change file src/server.js as follows:
--- a/src/server.js
+++ b/src/server.js
@@ -6,6 +6,9 @@ import * as sapper from '@sapper/server';
 const { PORT, NODE_ENV } = process.env;
 const dev = NODE_ENV === 'development';

+const result = require('dotenv').config({ debug: true });
+console.log('dotenv result:', result);
+
 polka() // You can also use Express
        .use(
                compression({ threshold: 0 }),

I would expect that the Sapper app listens on port 5000. However, it listens on default port 3000 instead. The console output shows the reason:

npm run dev

> TODO@0.0.1 dev /[...]/sapper-dotenv-port
> sapper dev

✔ server (952ms)
✔ client (959ms)
> Listening on http://localhost:3000
[dotenv][DEBUG] did not match key and value when parsing line 2:
[dotenv][DEBUG] "PORT" is already defined in `process.env` and will not be overwritten
dotenv result: { parsed: { PORT: '5000' } }
✔ service worker (28ms)

As far as I understand the cause of process.env.PORT being already defined, this is due to the following two lines in the Sapper code base:

  1. PORT: this.port at src/api/dev.ts#L287
this.proc = child_process.fork(`${dest}/server/server.js`, [], {
  cwd: process.cwd(),
  env: Object.assign({
    PORT: this.port
  }, process.env),
  stdio: ['ipc'],
  execArgv
});
  1. process.env.PORT = process.env.PORT || ${opts.port || 3000}; at src/cli.ts#L179
fs.writeFileSync(launcher, `
  // generated by sapper build at ${new Date().toISOString()}
  process.env.NODE_ENV = process.env.NODE_ENV || 'production';
  process.env.PORT = process.env.PORT || ${opts.port || 3000};
  console.log('Starting server on port ' + process.env.PORT);
  require('./server/server.js');
`.replace(/^\t+/gm, '').trim());

Thus, the definition of process.env.PORT is hard coded. That way, it is not possible to redefine its value using dotenv.

It would be great if I could define that port number in my .env file.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions