Serve React Build or Next Export using Express Js as Static Server

Serve React Build or Next Export using Express Js as Static Server

Written : 2023-01-13 Last Update : 2023-01-13

Intro

A Simple code snippet to server static builds from views directory, from an express server. This can be used to serve react js and next js apps.

Put your static content in a directory named static.

You can use this to serve builds of react JS , flutter etc.

npm init --yes
npm i express
const express = require("express"); 
 
const app = express();
 
app.use("/", express.static(__dirname + "/static"));
 
app.get('/', (req, res) => { 
    res.sendFile('views/index.html', {root: __dirname })
});
 
app.get('*', (req, res) => {
    res.sendFile('views/404.html', {root: __dirname })
});
 
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => console.log(`Started At ${PORT}`));