This repository was archived by the owner on Jan 11, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 419
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
Copy link
Copy link
Closed
Description
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:
- Start new project using
npx degit "sveltejs/sapper-template#rollup" sapper-dotenv-port
. - Install dotenv via
npm install dotenv
. - Create
.env
file with contentPORT=5000
. - 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:
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
});
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
Labels
No labels