albert.walickihire me
← all solutions
javascript

How to get the current URL in JavaScript?

Get the current page URL with window.location.href, read its parts and query parameters, and get the URL safely in Next.js and other SSR frameworks.

Use window.location.href. It returns the full URL of the current page as a string. The window. part is optional, so location.href works too.

const url = window.location.href;
// 'https://shop.example.com:8080/shoes?color=red&size=42#reviews'

The parts of the URL

location also gives you each part separately. For the URL above:

location.origin;   // 'https://shop.example.com:8080'
location.protocol; // 'https:'
location.host;     // 'shop.example.com:8080'
location.hostname; // 'shop.example.com'
location.port;     // '8080'
location.pathname; // '/shoes'
location.search;   // '?color=red&size=42'
location.hash;     // '#reviews'

A few details that trip people up:

  • protocol includes the colon, search includes the ?, and hash includes the #. Use location.hash.slice(1) to get just reviews.
  • port is an empty string when the URL uses the default port (443 for HTTPS, 80 for HTTP).
  • host includes the port, hostname doesn't.

Query parameters

Don't split the search string by hand. URLSearchParams parses it and decodes the values for you:

// ?q=red+shoes&page=2
const params = new URLSearchParams(location.search);

params.get('q');    // 'red shoes'
params.get('page'); // '2', always a string
params.get('sort'); // null when it's missing
params.has('page'); // true

For a parameter that appears more than once, like ?tag=a&tag=b, get() returns only the first value and getAll('tag') returns ['a', 'b'].

If you want to change parameters and build a new URL, start from a URL object, which has the same parts as location plus a searchParams property:

// ?q=red+shoes&page=2
const url = new URL(location.href);
url.searchParams.set('page', '3');
url.search; // '?q=red+shoes&page=3'

To put that new URL in the address bar, see how to change the URL without reloading the page.

Next.js and other server-rendered apps

In frameworks that render on the server, component code runs on the server first, where there's no window, and window.location throws ReferenceError: window is not defined.

Code inside event handlers only runs in the browser, so reading location there is fine. To render the URL, read it in useEffect, which only runs in the browser:

'use client';

import { useEffect, useState } from 'react';

export function ShareLink() {
  const [url, setUrl] = useState('');

  useEffect(() => {
    setUrl(window.location.href);
  }, []);

  return <input readOnly value={url} aria-label="Page link" />;
}

Usually it's better to ask the router, which also re-renders your component when the URL changes. In the Next.js App Router, use the hooks from next/navigation in a client component:

'use client';

import { usePathname, useSearchParams } from 'next/navigation';

export function Filters() {
  const pathname = usePathname(); // '/products/shoes'
  const searchParams = useSearchParams();
  const color = searchParams.get('color'); // 'red'

  // ...
}

Neither hook gives you the domain or the hash. For the domain, keep your site URL in an environment variable. Also, on statically rendered pages Next.js may ask you to wrap a component that uses useSearchParams() in a <Suspense> boundary.

In the Pages Router, use useRouter() from next/router:

import { useRouter } from 'next/router';

export default function ProductPage() {
  const { asPath, pathname, query } = useRouter();
  // asPath: '/products/shoes?color=red', as in the address bar
  // pathname: '/products/[slug]', the route file
  // query: { slug: 'shoes', color: 'red' }

  // ...
}

Other routers have their own versions: useLocation() in React Router and useRoute() in Vue Router.

more solutions
work with me

Got something that needs building?

Frontend builds, full-stack features in Django, design-system work. Available for work.

See my workGet in touch