Fastify with Heroku
Asked Answered
D

3

5

I am having a simple Fastify server hosted with Heroku. But, it seems not working ! But, it seemed all right during the development! The error I get is: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch. Full error I am getting:

enter image description here

Here is the code I am using:
server.js:

const fastify = require("fastify")();
const path = require("path");

fastify.register(require("fastify-static"), {
  root: path.join(__dirname, "/"),
});

fastify.get("/", function (req, reply) {
  reply.sendFile("index.html");
});

fastify.listen(process.env.PORT || 5000, (err) => {
  if (err) throw err;
  console.log(`server listening on ${fastify.server.address().port}`);
});

package.json:

{
"name": "test1",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "engines": {
    "node": "15.11.x"
  },
  "scripts": {
    "start": "node server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "fastify": "^3.14.0",
    "fastify-static": "^4.0.1"
  }
}

Sometimes, the site even doesn't load!
Any help is greatly appreciated !
Thanks !

Dereism answered 22/3, 2021 at 9:34 Comment(0)
H
17

That's an issue with the library. For other libraries (express, django, etc..) specifying the address is not necessary.

See https://github.com/fastify/fastify/issues/709

Change:

.listen(process.env.PORT) 

to:

.listen(process.env.PORT, '0.0.0.0')
Higgler answered 22/3, 2021 at 10:24 Comment(1)
I had to change it to the new syntax so .listen({port: process.env.PORT || 3000, host: '0.0.0.0'})Lateen
H
2

When I use both nodemon as local server and Heroku for production the following works for me:

await fastify.listen(process.env.PORT, process.env.HOST || '0.0.0.0');

and in package.json

"dev": "PORT=${PORT:=3000} HOST=${HOST:=localhost} nodemon"
Humidistat answered 27/1, 2022 at 21:27 Comment(0)
R
0

In 2024 with the current syntax, it would be:

   app.listen({ port: Number(process.env.PORT || 5000), host: '0.0.0.0' }, (err, address) => {
      if (err) {
        console.error(err);
        throw err;
      }
      console.log(`Fastify server is running on ${address}`);
    });
Rondarondeau answered 17/6 at 19:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.