51

I am working on a single page web app using Node + Express and Handlebars for templating. Everything currently works well from index.html, which is served from a pretty standard server.js file:

var express = require('express');

var server = express();
server.use(express.static(__dirname + '/public'));

var port = 10001;
server.listen(port, function() {
    console.log('server listening on port ' + port);
});

This works perfectly when loading from http://localhost:10001/. My issue is that I'm using push states in the app, so the browser may show a URL like http://localhost:10001/foo/bar and then if I refresh the page, I get the error Cannot GET /foo/bar since there is no route for this.

So my question, and pardon my incredible noobishness when it comes to Node, can I make it so all requests route to index.html? The JavaScript in my app can handle showing the right content based on URL params on page load. I don't want to define custom routes as the number would be large, and the paths for them can change dynamically.

Sam Dutton
  • 14,775
  • 6
  • 54
  • 64
JPollock
  • 3,218
  • 4
  • 26
  • 36

5 Answers5

59
const express = require('express')
const server = express()

/* route requests for static files to appropriate directory */
server.use('/public', express.static(__dirname + '/static-files-dir'))

/* other routes defined before catch-all */
server.get('/some-route', (req, res) => {
  res.send('ok')
})

/* final catch-all route to index.html defined last */
server.get('/*', (req, res) => {
  res.sendFile(__dirname + '/index.html');
})

const port = 8000;
server.listen(port, function() {
  console.log('server listening on port ' + port)
})
cdock
  • 850
  • 9
  • 15
  • 5
    It is good to **note** that the catch-all route should be after the static middleware and other get routes, as pointed out in other answers. – Akseli Palén Oct 06 '16 at 18:19
  • what is the use for public in => "server.use('/public', express.static(__dirname + '/public'));" . Can that be used in later steps to alias "__dirname + '/public' " , while serving individual files with specified route name ? – IKriKan Aug 14 '18 at 10:54
11

This pattern will serve static assets before hitting the catch-all route that serves up your front-end application. To register any additional routes, just add them above the catch-all route.

var express = require('express');
var server = express();

// middleware
server.use(express.static(__dirname + '/public'));

// routes
server.use('*', function (req, res) {
  // serve file
});

var port = 10001;
server.listen(port, function() {
  console.log('server listening on port ' + port);
});
Nick Tomlin
  • 28,402
  • 11
  • 61
  • 90
8

This short thing works well:

import express from "express";

const app = express(),
      staticServe = express.static(`${ __dirname }/public`);

app.use("/", staticServe);
app.use("*", staticServe);

Just make sure that all URLs from your HTML/JS files are absolute now, as all resources that do not exist will return index.html file.

Express v 4.15.2

ZitRo
  • 1,163
  • 15
  • 24
7
var app = express();

var options = {
  dotfiles: 'ignore',
  etag: true,
  extensions: ['htm', 'html'],
  index: 'index.html',
  lastModified: true,
  maxAge: '1d',
  setHeaders: function (res, path, stat) {
    res.set('x-timestamp', Date.now());
    res.header('Cache-Control', 'public, max-age=1d');
  }
};

app.use(compression());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());

app.use('/', express.static(__dirname + '/public', options));
app.use('*', express.static(__dirname + '/public', options));
poke
  • 369,085
  • 72
  • 557
  • 602
Deepak
  • 141
  • 1
  • 2
3
var express = require('express');

var server = express();
server.use(express.static(__dirname + '/public'));

server.get('*', function(req, res){
  res.sendFile('index.html');
});

var port = 10001;
server.listen(port, function() {
    console.log('server listening on port ' + port);
});
vodolaz095
  • 6,680
  • 4
  • 27
  • 42
  • This works, with the edit I made, except it also acts on the URL for my CSS file, so it serves index.html instead of the CSS file. Is there a way to only apply this by mime type (ie, only on html). – JPollock Oct 14 '14 at 02:16
  • @JPollock register middleware for public files before your catch-all route. That way requests to css/js will be picked up before your index route. – Nick Tomlin Oct 29 '14 at 18:39