Open In App

Create an Express.js Application

Last Updated : 03 Oct, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Building an Express.js application is the foundation of server-side development in Node.js.

Step 1: Install Node.js

Firstly, install Node.js on your system. Follow this article for a step-by-step Node.js installation.

Step 2: Create a Project Directory

Open your terminal/command prompt and create a new folder for your project:

mkdir my-express-app
cd my-express-app

Step 3: Initialize npm

Initialize a new Node.js project using npm:

npm init  or npm init -y
Screenshot-2024-06-06-155750

Step 4: Install Express

Install Express.js as a dependency:

npm install express

Something like this will be shown on successful installation. 

Screenshot-2024-06-06-155921

Step 5: Create the Server File

Create an app.js (or server.js) file. This will serve as the main entry point for your application.

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
    "express": "^4.19.2",
    "mongoose": "^8.4.0"
  }

Approach

  • Use require('express') to import the Express module.
  • Call express() to create an Express application instance.
  • Define the port for the application, typically 3000.
  • Set up a basic GET route with app.get('/', (req, res) => res.send('Hello World!')).
  • Use app.listen method to listen to your desired PORT and to start the server.

Example: Implementation to setup the express application.

Node
const express = require('express');

const app = express();
const PORT = 3000;

app.listen(PORT, (error) =>{
    if(!error)
        console.log("Server is Successfully Running, 
                   and App is listening on port "+ PORT);
    else 
        console.log("Error occurred, server can't start", error);
    }
);

Step to Run Application: Run the application using the following command from the root directory of the project

node app.js

Output: You will see something like this on the terminal.

Screenshot-2024-06-06-160044

In this example:

  • The server has been created and run successfully.
  • If the server does not start, check the error message carefully and resolve the issue.
  • After a successful run, opening http://localhost:3000 in the browser will display “Cannot GET /”.
  • This happens because no routes have been configured in the application yet.

Step 6: Setting Up Routes

Routes are server endpoints that respond to client requests. You can think of a route as a function that runs when someone accesses a specific path. Express supports routes for various HTTP methods like GET, POST, PUT, and more.

Syntax:

app.anyMethod(path, function) 

Setting GET request route on the root URL:

  • Use app.get() to configure the route with the path '/' and a callback function.
  • The callback function receives req (request) and res (response) objects provided by Express.
  • req is the incoming request object containing client data, and res is the response object used to send data back to the client.
  • Use res.status() to set the HTTP status code before sending the response.
  • Use res.send() to send the response back to the client. You can send a string, object, array, or buffer. Other response methods include res.json() for JSON objects and res.sendFile() files.

Example: Implementation to set up a basic request route on the root URL.

Node
//app.js

const express = require('express');

const app = express();
const PORT = 3000;

app.get('/', (req, res)=>{
    res.status(200);
    res.send("Welcome to root URL of Server");
});

app.listen(PORT, (error) =>{
    if(!error)
        console.log("Server is Successfully Running,
                    and App is listening on port "+ PORT);
    else 
        console.log("Error occurred, server can't start", error);
    }
);


Step to run the application: Save the code, restart the server, and open localhost:<port>. A GET request to / will return the plain text response, which you can also inspect in Chrome DevTools under the Network tab.

Output:

Setting up one more get request route on the '/hello' path. 

  • Most of the things are the same as in the previous example.
  • The set() function is used to set the HTTP header's content type as HTML. When the browser receives this response it will be interpreted as HTML instead of plain text.
  • Also in this example, we are not explicitly setting status, it is now concatenated with the statement of sending the response. This is another way to send status along with a response.

Example: Implementation to setup the one more route.

Node
//app.js

const express = require('express');
const app = express();
const PORT = 3000;

app.get('/hello', (req, res)=>{
    res.set('Content-Type', 'text/html');
    res.status(200).send("<h1>Hello GFG Learner!</h1>");
});

app.listen(PORT, (error) =>{
    if(!error)
        console.log("Server is Successfully Running, and App is
                      listening on port "+ PORT);
    else 
        console.log("Error occurred, server can't start", error);
    }
);


Step to run the application: Save this code, restart the server, and open the localhost on the given port. Now access the '/hello' route from the browser, The h1 text inside HTML will be shown as a response.

Output:

Step 7: Sending Data to the Server

Sometimes we need to send data to the server (e.g., login details). This is done using the request object with methods like POST. Since browsers can only send GET requests via the address bar, tools like Postman or a frontend form are needed to send data.

Setting route to be accessed by users to send data with post requests.

  • Use express.json() middleware to parse incoming JSON data.
  • Apply middleware with app.use().
  • Create a POST route on '/'.
  • Extract the name property from req.body using ES6 syntax: const { name } = req.body.
  • Send a response confirming the data was received.
  • Use ${} to include variables in the response string.

Example: Implementation to Setup route to be accessed by users to send data with post requests.

Node
// app.js

const express = require('express');
const app = express();
const PORT = 3000;

app.use(express.json());
app.post('/', (req, res)=>{
    const {name} = req.body;
    
    res.send(`Welcome ${name}`);
})

app.listen(PORT, (error) =>{
    if(!error)
        console.log("Server is Successfully Running, and 
                    App is listening on port "+ PORT);
    else 
        console.log("Error occurred, server can't start", error);
    }
);


Step to run the application: We test the route using Postman (or any tool like Axios, fetch, or cURL). Sending JSON data in the request body returns a response from the server, confirming the data was received successfully.

Output: 

Step 8: Sending Files from Server

To send files from the server, we can either serve static files using middleware or send a single file via a route. For example, serve all files in a Static Files folder and send image.jpg through a separate route.

Example 1: Serving entire directory using middleware   

In Express, we use the middleware express.static() function, which takes two arguments. The first argument is the absolute root path of the directory containing the files we want to serve. We can easily serve static files by using app.use() and providing the express.static() middleware.

Syntax:

app.use(path, express.static(root, [options]));  

Example: Implementation to show the use of middleware in Express.

app.js
// app.js

const express = require('express');
const app = express();
const PORT = 3000;

const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'Static Files')))


app.listen(PORT, (error) =>{
    if(!error)
        console.log("Server is Successfully Running, 
                   and App is listening on port "+ PORT);
    else 
        console.log("Error occurred, server can't start", error);
    }
);

Step to run the application: This will be the returned response when we request some static file from the directory that we are serving as static. Here you can see we have received an HTML file as a response for '/static/random.html'. The same things happen when we request for '/static/1.jpg'.

Output:

In this example:

  • Import the built-in path module.
  • Use path.join(__dirname, ...) to create an absolute path to the directory.
  • Mount express.static() middleware on the /static route.
  • Provide the joined path to the middleware so it can serve files from that directory.

Example 2: Sending a single file on a route with the sendFile() function.

This function accepts an absolute URL of the file and whenever the route path is being accessed the server provides the file as an HTTP response. This process can be thought of as a single endpoint of the express.static(). It can be useful when we have to do some kind of processing before sending the file.

Syntax:

res.sendFile(fileUrl)

Example: Implementation to show Sending a single file on a route with the sendFile() function.

app.js
// app.js

const express = require('express');
const path = require('path');

const app = express();
const PORT = 3000;

app.get('/file', (req, res)=>{
    res.sendFile(path.join(__dirname,'image.jpg'));
});

app.listen(PORT, (error) =>{
    if(!error)
        console.log("Server is Successfully Running, and App is listening on port "+ PORT);
    else 
        console.log("Error occurred, server can't start", error);
    }
);

Output: After running the server, When we request the route '/file' the server sends the image.jpg file as a response.

In this example:

  • We are creating a get request route on the '/file' path
  • After that we create the absolute path by joining the path of the current __dirname and the name of the file we want to send and then passing it to sendFile().
  • The route sends the image.jpg file to the user as an HTTP response.

Explore