Skip to content
Related Articles

Related Articles

How to redirect to generated URL with ExpressJS?
  • Last Updated : 08 Apr, 2021

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.

Overview:

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.



Project
|
|-> 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.

login.ejs




<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        body{
            margin: 0% auto;
        }
        h1{
            color: green;
        }
        input{
            margin: 10px;
            display: block;
            padding: 5px 10px;
        }
        button{
            margin: 10px;
            display: block;
            padding: 5px 10px;
            cursor: pointer;
            background-color: green;
            border: none;
            color: white;
            font-weight: bold;            
        }
        form{
            margin: 10% auto;
            padding: 20px;
            width: 20%;
            border: 1px solid green;
        }
    </style>
</head>
<body>
    <form>
        <center><h1>GeeksForGeeks</h1></center>
  
        <label>Email</label>
        <input type="email" id="userEmail">
  
        <label>Password</label>
        <input type="password" id="userPassword">
  
        <button onClick = "login(event)"> Login </button>
    </form>
  
    <script>
        const login = e =>{
            e.preventDefault();
  
            const email = document.getElementById('userEmail').value;
            const password = document.getElementById('userPassword').value;
  
            const option = {
                headers:{
                    "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!'));
        }
    </script>
</body>
</html>

dashboard.ejs




<!DOCTYPE html>
<html>
<head>
    <title>Dashboard</title>
</head>
<body>
    <h1>Welcome <%= email %></h1>
</body>
</html>

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.  

server.js




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');
app.use(bodyParser.json());
  
//login page route
app.get('/', (req,res)=>{
    res.render(path.join(__dirname, 'views/login.ejs'), {url: '/login'});
})
  
// login handler route
app.post('/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}`) :
        res.status(401).end();
  
});
  
// 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: "raktim@email.com",
        password: "Raktim"
    },
    {
        name: "Arpita Banerjee",
        email: "arpita@email.com",
        password :"Arpita"
    }
];
  
// find user 
const findUser = (email, password)=> users.some(user => 
      user.email === 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

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :