Microservices in NodeJS

Microservices architecture in NodeJS is a group of loosely-coupled services that works independently of each other. Failure in one service does not affect the other services in the system. Consider each service as a separate server or system.

For example, you have a social networking website. So you can create one microservice that handles all functions of users, one microservice for managing posts, one microservice for comments etc.

Today, we are going to create such microservices in Node JS. First, we are going to create 2 microservices. One for handling users and one for posts. Then we will create a gateway that will route the API requests to the relevant service.

  • Directory structure:
    • users
      • server.js
    • posts
      • server.js
    • gateway
      • server.js

Create users microservice

First, we are going to create a microservice for users. Create a folder named users and inside it create a file named server.js. After that, open command prompt or terminal in this users folder and run the following commands one-by-one:

> npm init
> npm install -g nodemon
> npm install express
> nodemon server.js

Following will be the code of your server.js file inside users folder.

const express = require("express")
const app = express()

app.get("/getData", function (request, result) {
	result.send("Get data from users.")
})

app.listen(3001, function () {
	console.log("User service is running.")
})

It simply creates a service running at port 3001. This will be your separate server for handling users requests.

Create posts microservice

Now we will create a microservice for handling posts requests. Create a folder named posts and inside it create a file named server.js. After that, open command prompt or terminal in this posts folder and run the following commands one-by-one:

> npm init
> npm install express
> nodemon server.js

The commands are same as we did in users folder. Open the server.js file inside posts folder and write the following code in it.

const express = require("express")
const app = express()

app.get("/getData", function (request, result) {
	result.send("Get data from posts.")
})

app.listen(3002, function () {
	console.log("Post service is running.")
})

It is almost similar to the user’s server.js file. Only the port number is different. It is running on port 3002.

So you have 2 different services that runs independently. If user server fails, the posts server will keep on running independently. Now we need to have a gateway in between them, that will route the users API requests to user’s server and posts API requests to post’s server.

Note that each miroservice should run on a different server or process. Because the whole point of creating microservices is to create loosely-coupled services.

Create a gateway

All the API requests will be sent to the gateway server. The gateway server will then redirect the request to the relevant service.

Create a folder named gateway. Create a file named server.js inside it and open command prompt in it. Then run the following commands in this folder one-by-one:

> npm init
> npm install fast-gateway
> nodemon server.js

We will be using fast-gateway NPM module. Following will be the code of server.js file inside gateway folder.

const gateway = require("fast-gateway")

const server = gateway({
	routes: [
		{
			prefix: "/users",
			target: "http://localhost:3001"
		},
		{
			prefix: "/posts",
			target: "http://localhost:3002"
		}
	]
})

server.get("/serverApi", function (request, result) {
	result.send("Server API is called.")
})

server.start(3000).then(function () {
	console.log("Server is started running.")
})

The gateway server will be running on port 3000. Run the following URL in your web browser:

http://localhost:3000/users/getData

You will see the message “Get data from users.” So the gateway will automatically route all the requests prefixed with “/users” to the user microservice. Same goes for posts. Run the following URL in web browser:

http://localhost:3000/posts/getData

Now you will see the message “Get data from posts.” That’s how you can create microservices in NodeJS.

Add emoji between text – jQuery

In this tutorial, we will teach you, how you can add emoji between text using jQuery. Emoji picker is a library that allows you to select a wide variety of emojis. It is a Javascript library that returns the emoji character. You can append the emoji in your input fields as well.

This library is very useful specially if you are developing a chat app. For example, user can share emojis in messages.

But it has one problem: what happens when user has typed a message, now he wants to add the emoji in between the message ? The library does not provide such functionality by default.

So that we are going to do, is to get the current cursor position on the input field and set the emoji in-between the text.

Requirements:

  1. jQuery
  2. Emoji picker
  3. twemoji

After downloading all the above files, create 2 folders “css” and “js”. Place the CSS files in “css” folder and Javascript files in “js” folder.

After that, you need to include all these files in your code:

<link rel="stylesheet" href="css/emojis.css" />

<script src="js/jquery.js"></script>
<script src="js/DisMojiPicker.js"></script>
<script src="js/twemoji.min.js"></script>

Then, create an input field where you will enter the text and give it a unique ID.

<textarea id="textInput"></textarea>

Create a container where the emoji picker will be displayed. Give it a unique ID as well.

<div id="emojis"></div>

In your Javascript, initialize the emoji picker.

<script>
	$("#emojis").disMojiPicker()
	twemoji.parse(document.body)
</script>

If you refresh the page now, you will start seeing the emoji picker. Now we need to make it to set the emoji in input field.

// callback function that will be called when an emoji is clicked from emoji picker
$("#emojis").picker(function (emoji) {
	// get the current cursor position on textarea field
	const cursorPosition = $("#textInput").prop("selectionStart")

	// get the current value of texarea field
	const value = $("#textInput").val()

	// check if cursor is at the end of the text
	if (cursorPosition == value.length) {
		// append the emoji at the end
		$("#textInput").val(value + emoji)
	} else {
		// if cursor is in between the text
		// then prepend the emoji before next character
		$("#textInput").val(value.replace(value[cursorPosition], emoji + value[cursorPosition]))
	}
})

We created a single page chat application in MEVN stack where we implemented this emoji picker. You can check that project here.

[wpdm_package id=’2918′]

Custom middleware in Node JS

Middleware in Node JS is called before the request is handled by the router function. They stand between the router and the request. Middlewares are great when it comes to processing and validating request values before they reach the route.

Make sure you have downloaded and installed Node JS in your system first. You can download Node JS from here.

We are going to create a simple middleware that will add a new field “email” with the request.

# open terminal at desktop
# following command will create a folder
> mkdir nodejs-middleware

# open the folder in command prompt
> cd nodejs-middleware

# create a file named "server.js" in that folder
# following command will initialize the project
> npm init

# install express module
> npm install express

# start the server
> node server.js

Now in our server.js file, we will first start the server.

// server.js

// include express module
const express = require("express")

// create instance of express module
const app = express()

// get the port number if already set, or 3000 otherwise
const port = process.env.PORT || 3000

// start the server at specified port
app.listen(port)

// test in browser
// http://localhost:3000

Make sure to restart the server using “node server.js” command. Now we will create our custom middleware.

// create a custom middleware
const myMiddleware = function (request, result, next) {
	// add "email" field with the request object
  	request.email = "support@adnan-tech.com"
  
  	// continue with the request
	next()
}

The following code will add the middleware to all the requests.

// attach middleware to all requests
app.use(myMiddleware)

The following code will add the middleware to specific requests only.

// attach middleware to specific request
app.get("/", myMiddleware, function (request, result) {
	// display "email" value on browser
  	result.send(request.email)
})

Restart the server and check in your browser: http://localhost:3000

External middleware in Node JS

You can create your middleware in a separate file as well in your Node JS server. Create a file named “external-middleware.js” at the root of your project and write the following code in it:

module.exports = function (request, result, next) {
	request.email = "adnan@gmail.com"
	next()
}

Then in your “server.js” file, use the middleware like the following:

const externalMiddleware = require("./external-middleware")
app.use(externalMiddleware)

To test this middleware, remove or comment out the previous middleware and refresh your browser again. Check out our android application’s tutorial we created on Node JS.

Call function when user stops writing input field – Javascript

In this article, we are going to show you a technique that helps you call a function when the user stops writing in an input field, using Javascript. Suppose you have an input field for search and you want to show search suggestions to the user as he types. So typically you do the following:

<!-- input field -->
<input id="input" oninput="onInput()" />

<script>

	// function to be called whenever input field text value is changed
	function onInput() {
		// get the input field DOM in a separate variable
		const self = event.target

		// write your logic here to get suggestions
		console.log(self.value)
	}
</script>

The problem with this method is, if you are calling an AJAX request inside onInput() function, then it will call an HTTP request on each input change. So if the user types 5 characters in 1 second, it calls 5 AJAX requests in 1 second. But you should only call the AJAX request once.

So we will be using a technique called debounce. Change your onInput() function to the following:

// timer object
let timer;

// function to be called whenever input field text value is changed
function onInput() {
	// get the input field DOM in a separate variable
	const self = event.target
	
	// if user types another key before 500 milliseconds,
	// then remove the timer, so the function will not gets called
	clearTimeout(timer)

	// this will create a timer every time input field has a value
	timer = setTimeout(function () {
		// write your own logic when user stops typing
		console.log(self.value)
	}, 500)
}

You can see that we have created a global variable timer. Comments have been added with each line for an explanation. Now your AJAX request will only be called when the user stops writing.

You can also check our auto-search suggestion tutorial for a real-world example.

Pagination on arrays – MongoDB

In this tutorial, we will teach you, how you can do pagination on arrays of documents in MongoDB.

If you have a very large database, fetching all the documents in one query might be very slow. But we have a solution: Pagination. It allows you to fetch a few records in one query and the next few in another query. For example, if you have 1000 users, the first query will fetch users from 0 to 100, the second query will fetch users from 101 to 200, and so on.

Problem

Pagination comes with a problem; when data is stored in arrays. In Mongo DB, the data is stored in JSON format. You might be saving data in arrays. For example, take the following document:

db.collection("users").insertOne({
	name: "Adnan",
	workouts: [{
		name: "Push ups",
		sets: 10,
		reps: 30
	}, {
		name: "Pull ups",
		sets: 7,
		reps: 10
	}, {
		name: "Crunches",
		sets: 5,
		reps: 50
	}, {
		name: "Deadlifts",
		sets: 3,
		reps: 15
	}, {
		name: "Shoulder press",
		sets: 8,
		reps: 8
	}]
})

Here, one document has an array of “workouts” and it might have a lot more data in it. For example, the user we created above has 5 “workouts” array elements, but you want to show 2 workouts on each query. If you run the regular query to fetch the users document, then it will return all the 5 workouts:

// not a solution

// return the whole object
const data = await db.collection("users").find({
	name: "Adnan"
}).toArray()
console.log(data[0])

But it will return the whole object with all 5 “workouts” elements, which is not the desired outcome.

So how will you paginate on that ?

Solution

This is where the Mongo DB $slice operator comes in. It works the same as the Javascript slice() function. It cuts the array from provided start and end values. So we will use the following query to get the users document but with a few workouts:

// solution

// return the first 2 workouts
const data = await db.collection("users").find({
	name: "Adnan"
}, {
	projection: {
		workouts: {
			$slice: [0, 2]
		}
	}
}).toArray()
console.log(data[0])

Slice start value works on indexes, so 0 means the first element of the array, and the end means the number of elements to fetch. So it will fetch 2 array elements starting at index 0.

The second parameter to the find() function tells the projection, which means which keys you want to fetch. You have to write all your key names inside the “projection” object. Now if you want to fetch the next 2 records, you can simply do the following:

// return the workouts from 2 to 4 
const data = await db.collection("users").find({
	name: "Adnan"
}, {
	projection: {
		workouts: {
			$slice: [2, 2]
		}
	}
}).toArray()
console.log(data[0])

The “start” is set to 2, which means the array starts from index 2 which will be the 3rd element of the array. Because the first and second are already fetched in the previous query. The “end” is again set to 2 so we are again fetching the 2 records from the array.

That’s how you can keep going on and implementing pagination on your document’s arrays in MongoDB. If you face any problem in following this, kindly do let me know.

[wpdm_package id=’2045′]

2 ways to disable chrome autocomplete on input fields

Google Chrome by default autocomplete the input field. The HTML autocomplete attribute no longer works on chrome. We present to you 2 methods you can use to disable the autocomplete feature for input fields in chrome and other browsers.

  1. Set input DOM value
  2. Use textarea (recommended)

1. Set input DOM value

When the page loads, wait for half second, then set the input value to empty.

<input type="text" name="username" id="disable-autocomplete" />

<script>
	window.addEventListener("load", function () {
		setTimeout(function () {
			document.getElementById("disable-autocomplete").value = ""
		}, 500)
	})
</script>

We are using wait for 0.5 seconds to let the chrome autocomplete set the value. Then we will override that value to empty.

2. Use textarea (recommended)

We can also use a textarea tag instead of the input field, which will look exactly like a standard input field.

<textarea name="username" rows="1"
	style="resize: none;
		min-height: fit-content;
		font-family: sans-serif;
		font-size: 14px;"

	oninput="this.value = this.value.replace(/\n/g, '')"></textarea>

resize: none; will remove the resize icon to the bottom right of textarea.

Some CSS frameworks like bootstrap give minimum height to a textarea field. You can override that value by setting min-height: fit-content; style.

To set the font the same for input fields, we are setting the font family to “sans-serif”, and size to “14px”. If you are using any framework like Bootstrap, you need to give the “inherit” property to “font-family”, “font-size”, and “font-weight”. This will take the font from its parent element.

rows=”1″ attribute is necessary as it will only make the textarea look like 1 row.

Finally, we are adding an attribute oninput that will be an event listener. This will be called whenever the element gets the user input. We are using a regular expression to convert all the new line characters to empty. This means we are disabling the enter key press. Otherwise, a new line would be started whenever the user presses enter key in the textarea.

Textarea as password

If you want to have your <textarea> tag to be treated as password input field, you can do it the following way:

<textarea name="password" rows="1"
    style="resize: none;
        min-height: fit-content;
        font-family: sans-serif;
        font-size: 14px;"
    id="maskedPassword"></textarea>
    
<input type="hidden" id="hiddenPassword" />

Then in Javascript, you need to do the following:

const maskedPassword = document.getElementById('maskedPassword')
const hiddenPassword = document.getElementById('hiddenPassword')

maskedPassword.addEventListener('input', function (event) {
    const input = event.target.value
    
    // Prevent adding asterisks to the hidden input value
    if (input.length > hiddenPassword.value.length) {
        const newChar = input[input.length - 1]
        hiddenPassword.value += newChar
    } else {
        hiddenPassword.value = hiddenPassword.value.slice(0, input.length)
    }

    maskedPassword.value = '*'.repeat(input.length)
})

Explanation:

  • <textarea>: First we create a <textarea> tag where user will enter his password. Whatever user enters here will be replaced with asterisk “*”.
  • <input />: Then created a hidden input field where the actual password value will be stored.
  • In Javascript, we get DOM of both <textarea> and hidden <input> field.
  • Attach an input event listener to the <textarea> that will be called whenever user type anything in it. This will also be called if user copy/paste something in it.
  • Line 5: Getting the value of <textarea>.
  • Line 8: Make sure the length of <textarea> should be 1 character greater than the hidden <input> field.
  • Line [9-10]: Get the last character of textarea and append it in hidden input field.
  • Line 12: If textarea value is less than hidden input field, meaning user has pressed backspace or remove some characters, then replace the hidden input field value to where it was before (last entered value).
  • Line 15: Replace every character in textarea with asterisk “*”.

Disable copy, cut and paste

As this is a password field, so you must not allow users to copy, cut or paste from that input field. You can disable copy, cut and paste features on password field.

// Disable copying, cutting, and pasting
maskedPassword.addEventListener("copy", function (event) {
    event.preventDefault()
    // alert("Copy is disabled!")
})

maskedPassword.addEventListener("cut", function (event) {
    event.preventDefault()
    // alert("Cut is disabled!")
})

maskedPassword.addEventListener("paste", function (event) {
    event.preventDefault()
    // alert("Paste is disabled!")
})

That’s how you can disable autocomplete for input fields in Google Chrome along with disabling copy, cut and paste feature.

Disable autocomplete on textarea

If you are using <textarea>, you will notice that it also has an autocomplete feature. To disable the autocomplete feature on textarea, you need to do 2 things:

  • Set readonly attribtue as soon as textarea gets focused.
  • Remove readonly attribute just after 10 milliseconds.
<textarea name="address" id="address"></textarea>

<script>
    document.getElementById("address").addEventListener("focus", function() {
        const self = this;
        this.setAttribute("readonly", true);
        setTimeout(function () {
            self.removeAttribute("readonly");
        }, 10);
    });
</script>

If you set readonly attribute on textarea tag, the autocomplete feature does not work. But that means that user is also not able to type anything in textarea field. So you remove the readonly attribute right after 10 milliseconds that will not be noticeable by users.

If you face any problem in following this, kindly do let me know. Check out our tutorial to disable mouse scroll on input number fields.

Practical difference between async await and callback

In one of our tutorial, we learned how to create a function in async await and how to create a function that uses callback.

Video tutorial:

Asynchronous

Let’s say you want to send an email to a user. Following is a Node JS code that sends an email using a callback:

const transport = nodemailer.createTransport({
	host: "",
	port: 465,
	secure: true,
	auth: {
		user: "",
		pass: ""
	}
})

transport.sendMail({
	from: "support@adnan-tech.com",
	to: "",
	subject: "Test",
	text: "Hello",
	html: "Hello"
}, function (error, info) {
	console.log("Mail sent: " + (new Date()))
})

console.log("I am called: " + (new Date()))

In your terminal, you will see that the “I am called:” message will be displayed instantly. But the “Mail sent:” message will be shown after a few seconds, once the mail is sent. It means that all lines of your code are executed at once, irrespective of the fact that the sendMail function will take some. The code is executed without waiting for any function to complete. This is asynchronous programming.

Synchronous

This can be converted into a synchronous function. Following is the synchronous version of the above code:

// the function must be async if await is used inside it

app.get("/sendMail", async function (request, result) {

	// send an email using a callback
	const transport = nodemailer.createTransport({
		host: "",
		port: 465,
		secure: true,
		auth: {
			user: "",
			pass: ""
		}
	})

	const info = await transport.sendMail({
		from: "support@adnan-tech.com",
		to: "",
		subject: "Test",
		text: "Hello",
		html: "Hello"
	})

	console.log("Mail sent: " + (new Date()))

	console.log("I am called: " + (new Date()))

	result.send("")
})

If you run the code now, you will have to wait for the sendMail function to finish before you see your log messages. This is synchronous programming.

Now you have understood the difference, let’s discuss where you should use async await and where you should use a callback.

When to use async await

You should use the async await pattern when the next line of your code is dependent on the previous lines. For example, “you have to insert the record in the database only if the mail is sent successfully”. In this case, you must use async await so that your code will wait for the mail to be sent successfully, then it will insert it in the database.

When to use callback

A callback will be helpful when your code sections are independent of each other. For example, “send an email to the user and insert the record in the database.” In this case, your insertion query should not have to wait for the mail to be sent. The mail should be handled in a callback.

A guide to MEVN

MEVN stands for Mongo DB, Express JS, Vue JS, and Node JS. It is a technology stack used by developers to create full-fledged web applications. Most of the applications created in the MEVN stack are single-page applications. But it is up to you if you want to single page or multi-page web application.

Table of content

  1. What is MEVN ?
  2. Why MEVN ?
    • Same language for frontend and backend
    • Easy deployment
    • Seamless user experience
    • APIs for mobile apps
    • Mongo DB is scaled horizontally
    • Short learning curve
    • Better support for sockets
  3. Future of MEVN
  4. Projects developed in MEVN
  5. Where to learn MEVN ?
    • Official documentation
    • YouTube
    • Blogs
  6. Issues you will face in the development

Let’s get started.

1. What is MEVN ?

MEVN is a technology stack used to develop full-fledged web applications. You can easily create scalable web applications either single-page or multi-page applications. It is a new yet quickly evolving technology stack that has been adopted by a lot of developers already. Learning this will not only make you a frontend developer but a backend developer as well. Thus increasing your demand and reputation in the community.

Hiring a developer in this stack is easy for companies as well. Hiring individual developers for the backend and frontend is costly, especially for startups. So they end up looking for someone who knows both the backend and frontend.

2. Why MEVN ?

If you learn this technology stack, your demand is automatically increased since companies would love to have a developer that can handle both frontend and backend tasks. Even if you didn’t get a job as a full-stack developer, you can still get a job as either a frontend or backend developer since you can work in both.

Same language for frontend and backend

In this stack, the primary language is Javascript. Node JS is a Javascript runtime environment, Vue JS is a Javascript frontend framework and Express JS is a framework of Node JS for creating APIs. Mongo DB syntax is also very similar to Javascript. So you do not need to learn Javascript for the frontend and PHP or Python for the backend. One language i.e. Javascript is used for both sides (frontend and backend).

Easy deployment

Vue JS builds are minified code of HTML, CSS, and Javascript. So they can easily be deployed on most servers. You do not need to worry if your hosting supports PHP, Java, Python, or any other language. If your hosting supports HTML (which almost every hosting does) then you are good to go.

Node JS can also be easily deployed on Virtual Private Servers (VPS) or dedicated servers. You can check our detailed guide on how to deploy Node JS on VPS or dedicated servers.

Mongo DB can also be deployed on VPS or dedicated servers. But it can also be deployed on Mongo DB’s official site. You can check our tutorial for Mongo DB deployment.

Seamless user experience

Most of the apps created in this stack are single-page applications. They provide a better user experience since there is no page reload on any link. Only the required section of the page changes dynamically. Some of the websites that are single-paged are Gmail, Facebook, and Twitter.

APIs for mobile apps

Most of the rendering is done on the client side. This means you have to create APIs for each request. This helps you in the future when you want to develop mobile apps for your website. Android and iOS apps can easily communicate with APIs developed in Node JS.

Mongo DB is scaled horizontally

Horizontal scaling is performed by adding more nodes to the servers. Horizontal scaling is best for a non-relational database like Mongo DB since all the data is stored in a single document.

Moreover, if you have to add one more attribute to a single entity, you can easily add it to that document only. Unless in MySQL, where either you have to create a column that will result in assigning the value to all rows. Or you have to create a separate table and join them in each query which will slow down your application.

In Mongo DB, all data required for an entity is stored in a single document. No relationships are made. So data can be saved on different servers without being dependent on each other.

Short learning curve

If you know Javascript, you already know Vue JS. Unlike in React where you have to use JSX syntax, in Vue JS you can use legacy HTML and CSS code and use Javascript with it. If you know the basics of Javascript, spend a few hours on Vue JS official documentation and you will become a Vue JS developer.

Better support for sockets

Sockets are used for real-time communication. Like on Facebook, you do not have to refresh the page to check new notifications. Whenever a new notification is received, it automatically displays an alert. If you develop your web application in the MEVN stack, you will be able to add real-time features like alerts, notifications, chat messages, real-time collaborations, etc.

3. Future of MEVN

MEVN proving itself a bright future. A lot of developers are moving to this stack. It is in the race with MEAN and MERN stacks. It has solved a lot of issues that developers faced in web development. For example, during infinite scroll, the web page hangs due to too much data. Vue JS solved this by using the useVirtualList component. Node JS has solved real-time communication problems via sockets. And Mongo DB has solved the scalability problems and also the problems that came with tightly-coupled databases.

4. Projects developed in MEVN

To show you how easy it is to develop websites in this technology stack, we developed some projects in it. We have developed a chat app, a customer support ticketing system, and more.

5. Where to learn MEVN

You can learn this technology stack from many sources.

Official documentation

To stay updated with the latest versions and features, check out the official documentation of Vue JS. Node JS can also be learned from their official documentation. Mongo DB also came with outstanding documentation.

YouTube

Check this playlist to find a lot of tutorials on the MEVN stack.

Blogs

We have created many text-based tutorials on this stack.

6. Issues you will face in the development

You need to spend a lot of time to make the application up and running. The first version of your product might take more time and effort because you need to set up the APIs and basic functionality. However, we have created a boilerplate for authentication that will save you 100% time on rewriting the authentication code.

How to pick random document from Mongo DB

We need to use the aggregate function to pick a random document from Mongo DB. Its usage is simple. It accepts an array of objects. You need to pass $sample object in one array object and tell the number of random documents you want to fetch in the size object. Suppose you have the following data in your users collection.

db.users.insertOne({ name: "Adnan", language: "Java" })
db.users.insertOne({ name: "Tech", language: "Node JS" })
db.users.insertOne({ name: "Developer", language: "Java" })
db.users.insertOne({ name: "Programmer", language: "C++" })

Then the Mongo DB query to return 1 random document would be:

db.users.aggregate([
	{
		$sample: {
			size: 1
		}
	}
])

This will return 1 random document from your users collection. If you want to apply some query to it, you can do it by passing another array element and this time using the $match operator.

db.users.aggregate([
	{
		$match: {
			language: "Java"
		}
	},
	
	{
		$sample: {
			size: 1
		}
	}
])

This will return 1 random document from users collection whose language is “Java”. Make sure the $match operator is the first element of the array, otherwise it will return empty records sometimes.

Video tutorial

You can learn more about Mongo DB aggregate function from their official documentation. Check out our tutorials on Mongo DB.

Add or update URL query parameter in Javascript

Create the following function in Javascript to add or update URL query parameter.

function addOrUpdateURLParam (key, value) {
    const searchParams = new URLSearchParams(window.location.search)
    searchParams.set(key, value)
    const newRelativePathQuery = window.location.pathname + "?" + searchParams.toString()
    history.pushState(null, "", newRelativePathQuery)
}

Now, whenever you want to add or update the URL, simply call the function in the following way:

addOrUpdateURLParam("name", "adnan-tech.com")

The first parameter will be the key of the parameter, and the second will be the value.

window.location.search: will return all the query parameters starting from “?”.

URLSearchParams: This will create an instance of URLSearchParams that will be used to manipulate URL query parameters.

searchParams.set(key, value): This will set the key value provided in arguments, but will not display yet in the URL.

window.location.pathname: It returns the relative path starting from “/your_website”. It DOES NOT include the query parameters starting from “?”.

searchParams.toString(): Will convert all the key-value pairs to a string. If there will multiple parameters set, then they will be separated by the “&” sign.

history.pushState: Will actually display the query parameters in the URL.

The first parameter to the “history.pushState” function is the “state”. It can be a push, pop, or null. The second parameter is not used anymore but not removed either, passing an empty string is safe. The third parameter is the new URL, here we are passing our new string variable to set the new URL with query parameters. More information can be found here.

Video tutorial:

Following this tutorial, I hope you will be able to add or update query parameter in your website’s URL using Javascript. If it helps, check out our tutorials on Javascript.