Cannot Get/ when express app is deployed on heroku


my dir structure


above is my director structure

app.use(express.static(__dirname + "/public/"));
// app.use(express.static("/public/"));

const path = require("path");

app.get("/", (req, res, next) => {
    // res.sendFile(path.join(__dirname, + "public", 'index.html'));
    res.sendFile(__dirname , "index.html");

    //res.send('Testing one two');

const port = process.env.PORT || '5005';
app.listen(port, () => console.log("Server running on port 5005"));

when I run the above code, it works well on my local machine but won’t work when it is deployed to Heroku,
I tried just passing a string like this and it worked, but when I want to render a static file like the HTML file it wont work on heroku, any help? i think the problem is my directory structure

app.get("/", (req, res, next) => {
        res.send('Testing one two');


If I recall correctly, express.static middleware is separate from res.sendFile. In other words, even if you set express.static to public, it will not do anything to res.sendFile, as it takes the first parameter as a path.

In my humble opinion, it would be better if you were to use an absolute path, like the following snippet below.

const path = require('path');

/** Code here... **/

app.get("/", (req, res, next) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));


  • path.join is an utility to join path segments into one path. It is cross-platform compatible.
  • __dirname will get the current directory that the script is running from.

Further reading: Express methods.

Answered By – Nicholas

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published