How to set up an Express.js server

· Category: Node.js

Short answer

Install Express with npm, require it in your entry file, create an app instance, define routes, and call app.listen() to start the server.

Steps

  1. Run npm install express in your project directory.
  2. Create an index.js file and import Express: const express = require('express');.
  3. Initialize the app: const app = express();.
  4. Define a route: app.get('/', (req, res) => res.send('Hello'));.
  5. Start the server: app.listen(3000, () => console.log('Server started'));.

Tips

  • Use app.use(express.json()) to automatically parse JSON request bodies.
  • Enable environment-based port selection with const PORT = process.env.PORT || 3000;.

Common issues

  • Forgetting to send a response causes the client to timeout. Always end the request-response cycle.
  • Middleware order matters; place error-handling middleware last in your application.