Loading

Quipoin Menu

Learn • Practice • Grow

express-js / Your First Express Server
tutorial

Your First Express Server

Now that you've seen the Hello World example, let's dive deeper into understanding your first Express server. We'll explore `app.listen()`, folder structure, and how to organize your code better.

Understanding app.listen()

The `app.listen()` method binds and listens for connections on the specified host and port. It's the method that actually starts your server.
app.listen(port, [host], [backlog], [callback]);

ParameterDescription
portThe port number to listen on (e.g., 3000, 5000, 8080).
hostOptional – the host address (default: '0.0.0.0').
backlogOptional – max length of pending connections.
callbackFunction called when server starts successfully.

Best Practice: Using Environment Variables

Instead of hardcoding the port, use environment variables – this makes your app more flexible for deployment.
const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Basic Express Folder Structure

For a simple Express app, here's a recommended folder structure:
my-express-app/
├── node_modules/ # Dependencies (created by npm)
├── public/ # Static files (CSS, images, client-side JS)
│ ├── css/
│ ├── js/
│ └── images/
├── views/ # Template files (if using template engine)
│ └── index.ejs
├── routes/ # Route handlers
│ ├── index.js
│ └── users.js
├── middleware/ # Custom middleware
│ └── logger.js
├── models/ # Database models
│ └── user.js
├── controllers/ # Business logic
│ └── userController.js
├── app.js # Main application file
├── package.json # Project metadata and dependencies
└── package-lock.json # Locked dependency versions

Simple Organized Example

Let's refactor our Hello World into a more organized structure:

app.js
const express = require('express');
const indexRouter = require('./routes/index');

const app = express();
const PORT = process.env.PORT || 3000;

<!-- Use routes -->
app.use('/', indexRouter);

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

routes/index.js
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  res.send('Hello World from organized app!');
});

router.get('/about', (req, res) => {
  res.send('About page');
});

module.exports = router;

Two Minute Drill

  • `app.listen()` starts your Express server on a specified port.
  • Use `process.env.PORT` for flexible deployment (works on hosting platforms).
  • Organize your code with folders: `routes/`, `middleware/`, `models/`, `controllers/`.
  • Separate route handlers into different files using `express.Router()`.
  • A well-organized structure makes your app scalable and maintainable.

Need more clarification?

Drop us an email at career@quipoinfotech.com