How to serve static html files from express server
Serving static files from an Express server is straightforward. Express provides a built-in middleware function called express.static
to serve static files such as HTML, CSS, JavaScript, images, etc. Here's how to set it up:
-
Install Express: First, make sure you have Express installed in your project. If not, install it using npm:
npm install express
-
Create an Express server: Set up a basic Express server in a file, for example,
src/index.ts
. -
Serve static files: Use the
express.static
middleware to serve static files from a directory.
Here is a complete example:
Directory Structure
my-express-app/
├── public/
│ ├── images/
│ │ └── logo.png
│ ├── js/
│ │ └── script.js
│ └── css/
│ └── style.css
├── src/
│ └── index.ts
├── package.json
├── tsconfig.json
└── ...
Code Example
// src/index.ts
import express from 'express';
import path from 'path';
const app = express();
const port = 3000;
// Middleware to serve static files
app.use(express.static(path.join(__dirname, '../public')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../public/index.html'));
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Steps
-
Create Static Files: Place your static files (HTML, CSS, JavaScript, images, etc.) in the
public
directory. -
Update
package.json
: Ensure yourpackage.json
has the necessary scripts and dependencies.{ "name": "my-express-app", "version": "1.0.0", "main": "dist/index.js", "scripts": { "build": "tsc", "start": "node dist/index.js", "dev": "ts-node-dev --respawn --transpile-only src/index.ts" }, "dependencies": { "express": "^4.17.1" }, "devDependencies": { "ts-node-dev": "^1.1.8", "typescript": "^4.3.5", "@types/express": "^4.17.13", "@types/node": "^14.14.41" } }
-
Compile TypeScript: Compile your TypeScript code to JavaScript.
npx tsc
-
Run the Server: Start your Express server.
npm start
-
Access Static Files: Open your browser and navigate to
http://localhost:3000/
. You should see yourindex.html
file served, and you can access other static files such as CSS, JavaScript, and images.