Setting Up a Basic Express Server

🚀 Introduction

After installing Express.js, the next step is to create a basic web server. An Express server listens for incoming HTTP requests, processes them through routes and middleware, and sends appropriate responses back to the client. With just a few lines of code, you can build a functional web server using Node.js and Express.js.

Information

Every Express application starts by importing the Express module, creating an application instance, defining routes, and starting the server using the listen() method.

📋 Prerequisites

  • Node.js installed on your system.
  • Express.js installed using npm install express.
  • A project initialized with package.json.
  • A code editor such as Visual Studio Code.

🛠 Steps to Create an Express Server

📁 Project Structure

express-app
node_modules/
package.json
package-lock.json
index.js

📝 Creating the Express Server

index.js

const express = require('express');

// Create an Express application
const app = express();

// Define the port number
const PORT = 3000;

// Define a route
app.get('/', (req, res) => {
  res.send('Welcome to Express.js!');
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running at http://localhost:${PORT}`);
});

â–ļī¸ Running the Server

Start the Server

node index.js

Once the server starts successfully, open your browser and navigate to http://localhost:3000. You should see the message "Welcome to Express.js!".

Success

If the server starts without errors, your first Express server is running successfully.

🔍 Understanding the Code

CodePurpose
require('express')Imports the Express framework.
express()Creates a new Express application instance.
app.get()Registers a route for HTTP GET requests.
reqRepresents the incoming HTTP request.
resRepresents the HTTP response sent to the client.
app.listen()Starts the server and listens for incoming requests.

đŸ›Ŗ Adding Multiple Routes

Multiple Routes Example

app.get('/', (req, res) => {
  res.send('Home Page');
});

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

app.get('/contact', (req, res) => {
  res.send('Contact Page');
});

Each route is associated with a specific URL path. When a client requests that path using the appropriate HTTP method, Express executes the corresponding route handler.

🔄 Express Request Lifecycle

Client
HTTP Request
HTTP Response
Express Server
Route Matching
Route Handler

âš™ī¸ Using a Custom Port

Using Environment Variables

const PORT = process.env.PORT || 3000;

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

Best Practice

Using process.env.PORT makes your application easier to deploy on cloud platforms where the port number is assigned automatically.

📌 Common Server Methods

MethodDescription
app.get()Handles HTTP GET requests.
app.post()Handles HTTP POST requests.
app.put()Handles HTTP PUT requests.
app.delete()Handles HTTP DELETE requests.
app.listen()Starts the Express server.

💡 Best Practices

  • Keep the server entry file simple and organized.
  • Use meaningful route names.
  • Store the port number in an environment variable whenever possible.
  • Separate routes, controllers, and middleware into different folders as the project grows.
  • Handle server errors gracefully in production applications.

📚 Learn More

Explore the official documentation for more details:
â€ĸ Express.js Official Documentation
â€ĸ Node.js Documentation

📝 Summary

Summary

Setting up a basic Express server involves importing Express, creating an application instance, defining routes, and starting the server with app.listen(). This simple structure serves as the foundation for developing scalable web applications and RESTful APIs using Express.js.