Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

How to redirect to generated URL with ExpressJS?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In this article I’m showing you how to redirect users using ExpressJS. First of all, when you want to redirect the user? Here are some real scenario.

Example, when user successfully login you can redirect him to the dashboard. Another instance, when user request for reset password, generally we generate an URL with user’s old password’s hash and send to user’s email. Here, I’m showing you How redirect user to dashboard after successfully login.


Client: Make a GET request on URL ‘/’ for login page.
Server: Render login page
Client: Next, user fill the form data and make a POST request on URL ‘/login’.
Server: If user data matched then redirect to ‘/dashboaard/[ USER EMAIL ]’.
Client: User make GET request  on ‘/dashboaard/[ USER EMAIL ]’.
Server: Render dashboard page.

Project Structure: Final project directory structure will look like this.

|-> node_modules
|-> views
  |-> login.ejs
  |-> dashboard.ejs
|-> package.json
|-> package-lock.json
|-> server.js

Step 1: Create empty npm project folder and name it Project.

mkdir Project
cd Project 
npm init -y

Step 2: Install require dependency.

Require dependency:

  1. ExpressJS
  2. EJS
  3. body-parser
npm i express ejs body-parser

Step 3: Client files, the default behavior of EJS is that it looks into the ‘views’ folder for the templates to render. So, let’s make a ‘views’ folder in our main node project folder and make two files named “login.ejs”  and “dashboard.ejs” .

login.js is responsible for user login request and if login success user will redirect to dashboard.ejs.


<!DOCTYPE html>
    <style type="text/css">
            margin: 0% auto;
            color: green;
            margin: 10px;
            display: block;
            padding: 5px 10px;
            margin: 10px;
            display: block;
            padding: 5px 10px;
            cursor: pointer;
            background-color: green;
            border: none;
            color: white;
            font-weight: bold;            
            margin: 10% auto;
            padding: 20px;
            width: 20%;
            border: 1px solid green;
        <input type="email" id="userEmail">
        <input type="password" id="userPassword">
        <button onClick = "login(event)"> Login </button>
        const login = e =>{
            const email = document.getElementById('userEmail').value;
            const password = document.getElementById('userPassword').value;
            const option = {
                    "Content-Type": "application/json"
                method: "POST",
                body: JSON.stringify({
                    email: email,
                    password: password
                redirect: "follow"
            // fetching data
            fetch(`<%= url %>`, option)
                .then(res => res.redirected && ( location.href = res.url ))
                .catch(err => alert('Something happen wrong!'));


<!DOCTYPE html>
    <h1>Welcome <%= email %></h1>

Step 4: Create a file name server.js on your root folder. This file is has some middleware and it response on user request. Generally user login information is fetched from database but for our case it is fair to fetch it from a damy database. 

Here, login handler route is redirect to ‘/dashboaard/[ USER EMAIL ]’ if user data matched else response with HTTP Client  Error Code 401.  


const express = require('express');
const path = require('path');    
const bodyParser = require('body-parser'); 
const ejs = require('ejs');
const app = express();
const PORT = 3000;
app.set('view engine', 'ejs');
//login page route
app.get('/', (req,res)=>{
    res.render(path.join(__dirname, 'views/login.ejs'), {url: '/login'});
// login handler route'/login', (req,res)=>{
    const {email, password} = req.body;
    findUser(email, password) ?
        // if user is registered
        // generate a dynamic url
        // redirect to user
        res.redirect(301, `/dashboard/${email}`) :
// dashboard route
app.get('/dashboard/:email', (req, res)=>{
    const {email} = req.params;
    res.render(path.join(__dirname, 'views/dashboard.ejs'), {email: email})
// damy user db
const users = [
        name: "Raktim Banerjee",
        email: "",
        password: "Raktim"
        name: "Arpita Banerjee",
        email: "",
        password :"Arpita"
// find user 
const findUser = (email, password)=> users.some(user => === email && user.password === password 
// Start the server
app.listen(PORT, err =>{
    err ? 
    console.log("Error in server setup") :
    console.log("Server listening on Port", PORT)

Step 5: Start server.

node server.js


My Personal Notes arrow_drop_up
Last Updated : 08 Apr, 2021
Like Article
Save Article
Similar Reads
Related Tutorials