How to Set Up a Node.js Express App: A Step-by-Step Guide
Node.js and Express are a powerful combination for building fast, scalable, and lightweight web applications. Whether you're creating a simple API or a full-fledged web server, Express makes it straightforward to handle routes, middleware, and requests. In this guide, we’ll walk through setting up a Node.js Express app from scratch.
1. Prerequisites
Before you start, make sure you have the following installed:
- Node.js (v14+ recommended) – Download Node.js
- npm (comes with Node.js) or yarn for package management
- A code editor, like VS Code
You can check your Node.js and npm versions by running:
node -v
npm -v
2. Create Your Project Folder
Start by creating a folder for your project:
mkdir my-express-app
cd my-express-appInitialize a new Node.js project:
npm init -yThis creates a package.json file, which will keep track of your dependencies and scripts.
3. Install Express
Next, install Express as a dependency:
npm install expressOptionally, install nodemon as a development dependency to automatically restart your server when files change:
npm install --save-dev nodemonUpdate package.json to add a start script for nodemon:
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
}
4. Create Your Entry File
Create an index.js file (or app.js) in your project root:
touch index.jsOpen it in your editor and add the basic Express server code:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware to parse JSON
app.use(express.json());
// Basic route
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
5. Run Your Server
Start your server:
npm run devOpen your browser and navigate to http://localhost:3000. You should see:
Hello, Express!Congratulations! Your Express server is running.
6. Add More Routes
Express makes routing simple. Create additional routes:
app.get('/about', (req, res) => {
res.send('About Page');
});
app.post('/contact', (req, res) => {
const { name, message } = req.body;
res.send(`Thanks ${name}, your message has been received!`);
});Test the POST route using tools like Postman or curl:
curl -X POST http://localhost:3000/contact -H "Content-Type: application/json" -d '{"name":"Alice","message":"Hello!"}'
7. Add Middleware
Middleware allows you to handle requests before they reach your routes. For example, a simple logger:
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});You can also use third-party middleware:
npm install morganconst morgan = require('morgan');
app.use(morgan('dev'));
8. Serve Static Files
Express can serve static files like HTML, CSS, or images:
app.use(express.static('public'));Place your files in a public folder. Now you can visit them directly in your browser.
9. Organize Your Project
As your app grows, structure your project:
my-express-app/
│
├── public/ # Static files
├── routes/ # Route modules
├── middleware/ # Custom middleware
├── index.js # Entry point
└── package.jsonExample of a route module in routes/users.js:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Users list');
});
module.exports = router;Then in index.js:
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
10. Next Steps
Once your basic app is up and running, you can explore:
- Connecting a database (MongoDB, PostgreSQL, MySQL)
- Using a template engine (EJS, Pug, Handlebars)
- Building a REST API with CRUD operations
- Deploying your app (Heroku, Vercel, DigitalOcean)
Conclusion
Setting up a Node.js Express app is quick and flexible. With just a few steps, you can have a fully functional server running locally. From there, Express gives you the freedom to scale your app, add features, and structure your project in a maintainable way.