Hosting a static website with node.js and express is extremely easy but also extremely useful. This lesson aims to provide you with the skill to set up a website to host your own project portfolio, business webpage, etc..
This lesson will assume you have already set up a linux environment that is connected to the internet that is likely always on (so your website will be always up). I use an old desktop PC and have it running at home but it is also extremely common to use a free tier AWS server.
First, you should have node.js installed. If you do not, you can install it by running the following:
# Download and install nvm:
curl -o- <https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.2/install.sh> | bash
# in lieu of restarting the shell
\\. "$HOME/.nvm/nvm.sh"
# Download and install Node.js:
nvm install 22
# Verify the Node.js version:
node -v # Should print "v22.14.0".
nvm current # Should print "v22.14.0".
# Verify npm version:
npm -v # Should print "10.9.2".
Next, open the directory where your you will store your website. I just have a folder off my home directory. In this folder will be the code to host your website (”index.js”, you can make this file by just running “touch index.js”) and another folder holding your static files, like the following:
--home
|
--website
index.js
|
--static_files
Next while in the website directory, you will need to run “npm install express.” You will notice this creates a “node_modules” folder and some “package…” files. These are the files for the package you just installed.
After this, you can copy the following code into the “index.js” file.
'use strict';
const express = require('express');
const path = require('path');
const app = express();
// Serve static files from the 'static_files' directory
app.use(express.static(path.join(__dirname, './static_files')));
// Start the server
const PORT = process.env.PORT || 1234;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
You may choose any port you want but if you choose port 80 you will have to run this program using “sudo.” It is better practice to use a different port like 1234 and forward that port to 80 in your router.
To run this to just test your website, you can do “npm start index.js.” If you want your website to stay permanently online, you have to run it a little different. For this, you should run the following:
#install pm2
sudo npm install pm2 -g
#start your website
pm2 start index.js
Now, your website should be running. You can check this by navigating to localhost on whatever port you selected. You are now done! After port forwarding and setting up a domain with a provider (I use cloudflare), your website will be easily accessible to anyone.