How to redirect to generated URL with ExpressJS?
Last Updated :
08 Jan, 2025
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.
Redirection is a common feature when building dynamic web applications.
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:
- ExpressJS
- EJS
- 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: "[email protected]",
password: "Raktim"
},
{
name: "Arpita Banerjee",
email: "[email protected]",
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:

Similar Reads
How to Get the Full URL in ExpressJS ?
When building web applications with Express.js, a popular framework for Node.js, there are many scenarios where you may need to retrieve the full URL of a request. This is especially useful for tasks like logging requests, generating absolute URLs for redirect responses, or creating links in respons
6 min read
How to get multiple requests with ExpressJS ?
Express.js is the most powerful framework of the node.js. Express.js is a routing and Middleware framework for handling the different routing of the webpage, and it works between the request and response cycle. Express.js use different kinds of middleware functions in order to complete the different
2 min read
How to handle redirects in Express JS?
Express JS uses redirects to send users from one URL to another. This can be done for various reasons, such as handling outdated URLs or guiding users through a process. In ExpressJS, you define routes and use them to direct users to the desired URL. It's a way to keep your application organized and
2 min read
How to get full URL in Express.js ?
Express is a small framework that sits on top of Node.jsâs web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your applicationâs functionality with middleware and routing. It adds helpful utilities to Node.jsâs HTTP object and it facilitates th
2 min read
How to test GET Method of express with Postman ?
The GET method is mainly used on the client side to send a request to a specified server to get certain data or resources. By using this GET method we can only access data but can't change it, we are not allowed to edit or completely change the data. It is widely one of the most used methods. In thi
2 min read
How to handle URL parameters in Express ?
In this article, we will discuss how to handle URL parameters in Express. URL parameters are a way to send any data embedded within the URL sent to the server. In general, it is done in two different ways. Table of Content Using queriesUsing Route parameterSteps to Create Express Application:Let's i
3 min read
How to Read the Current full URL with React?
In React applications, it is often necessary to read the current full URL for various purposes, such as routing, conditional rendering, or logging. There are two common approaches to achieve this: using the window.location object and using the useLocation hook from react-router-dom. Prerequisites:NP
3 min read
How to use get parameter in Express.js ?
Express Js is a web application framework on top of Node.js web server functionality that reduces the complexity of creating a web server. Express provides routing services i.e., how an application endpoint responds based on the requested route and the HTTP request method (GET, POST, PUT, DELETE, UP
2 min read
How to get url after "#" in Express Middleware Request ?
In Express, the fragment identifier (the part of the URL after the # symbol) is not directly accessible on the server side because it is not sent to the server as part of the HTTP request. The fragment identifier is typically used for client-side navigation and is processed on the client side only.
3 min read
What is Express Generator ?
Express Generator is a Node.js Framework like ExpressJS which is used to create express Applications easily and quickly. It acts as a tool for generating express applications. In this article, we will discuss the Express Generator. Express GeneratorExpress Generator is a command-line tool for quickl
3 min read