How to Get the Current URL with JavaScript

October 26, 2025

javascript

The window.location object provides access to the current page URL and its components.

Get the Full URL

Use window.location.href to get the complete URL including protocol, domain, path, and query parameters.

js
1.const currentURL = window.location.href;
2.console.log(currentURL);
3.// "https://example.com/path/page?id=123"

Get Specific URL Components

The window.location object has properties for accessing different parts of the URL.

js
1.// Get hostname
2.const hostname = window.location.hostname;
3.// "example.com"
4.
5.// Get pathname
6.const pathname = window.location.pathname;
7.// "/path/page"
8.
9.// Get protocol
10.const protocol = window.location.protocol;
11.// "https:"
12.
13.// Get port
14.const port = window.location.port;
15.// "8080" or "" if default
16.
17.// Get query string
18.const search = window.location.search;
19.// "?id=123"
20.
21.// Get hash/fragment
22.const hash = window.location.hash;
23.// "#section"

Get the Base URL

Combine protocol and hostname to get the base URL without the path.

js
1.const baseURL = window.location.protocol + "//" + window.location.hostname;
2.// "https://example.com"
3.
4.// Include port if present
5.const baseURLWithPort = window.location.origin;
6.// "https://example.com:8080"

Access Query Parameters

Use URLSearchParams to parse query parameters from the URL.

js
1.// URL: https://example.com/page?id=123&name=test
2.
3.const params = new URLSearchParams(window.location.search);
4.
5.const id = params.get('id');
6.// "123"
7.
8.const name = params.get('name');
9.// "test"

Usage in React

In React components, access the URL in useEffect or event handlers to avoid SSR issues.

js
1.import { useEffect, useState } from 'react';
2.
3.function MyComponent() {
4. const [currentURL, setCurrentURL] = useState('');
5.
6. useEffect(() => {
7. setCurrentURL(window.location.href);
8. }, []);
9.
10. return <div>Current URL: {currentURL}</div>;
11.}

Found this helpful? Follow for more tips and tutorials