Fetching the current URL of a webpage is a very common requirement whether for building navigation links, user analysis or implementing dynamic routing. In this guide, we will discuss how to get the current URL in the Next js app, even if it has hash, query params or dynamic parameters in the URL.
We will explore various methods including the use of a router or without a router to get the current URL and much more is coming up!
[lwptoc]
How to get the Current URL in Next.js?
There are various ways to obtain the current URL in the Next js application. We will walk through each of them with examples and other useful details:
1. Using useRouter
from next/router
2. Using window.location
Object
3. Using getServerSideProps
 or getInitialProps
1. Using useRouter
from next/router
One of the most common methods to get the current URLÂ is by using the useRouter
hook:
In your component, import the useRouter
hook from next/router
:
import { useRouter } from 'next/router';
Then, we need to use the useRouter
hook to access the current URL as shown below:
function CurrentURL() {
const router = useRouter();
const currentURL = router.asPath;
return (
<div>
<p>Current URL: {currentURL}</p>
</div>
);
}
export default CurrentURL;
This method is recommended when we are building an application that relies on client-side routing.
2. Using window.location
Object
We can also access the current URL by using the window.location
object. This method is less common but it can be helpful in a few situations
Create a new component or add this code to an existing one:
function CurrentURL() {
const currentURL = typeof window !== 'undefined' ? window.location.href : '';
return (
<div>
<p>Current URL: {currentURL}</p>
</div>
);
}
export default CurrentURL;
We can use this method where useRouter
is not available for example utility functions or non-component files.
3. Using getServerSideProps
 or getInitialProps
To get the current URL on the server side in Next js, we can use the getServerSideProps
 or getInitialProps
where we can access the req object which contains the full URL.
Create a new page pages/currentUrl.js
// pages/currentUrl.js
import { useRouter } from 'next/router';
function CurrentUrlPage({ currentURL }) {
return (
<div>
<p>Current URL: {currentURL}</p>
</div>
);
}
export async function getServerSideProps({ req }) {
const currentURL = req.url;
return {
props: {
currentURL,
},
};
}
export default CurrentUrlPage;
Here we have import the useRouter
hook from next/router
for use in the component. The CurrentUrlPage
component will display the current URL passed as a prop.Â
The getServerSideProps
function is an async function to receive a context object with the req
property that will represent the incoming HTTP request. Where we can extract the current URL using req.url
and return it as a prop to the component.
Thereafter run the application by hitting npm run dev
, then by visiting the following URL, you will see the current page URL:
http://localhost:3000/currentUrl
How to Get full URL including query parameters?
Here is how you can get the full URL using the router object’s query property to get the query parameter object:
// pages/index.js
import { useRouter } from 'next/router'
function Page() {
const router = useRouter()
const fullUrl = `${router.pathname}?${JSON.stringify(router.query)}`
return <p>Full URL: {fullUrl}</p>
}
// Full URL: /index?{"foo":"bar","baz":"xyz"}
How to get URL parameters in getInitialProps in Next.js?
You can get the router object with the query parameters passed to getInitialProps:
// pages/index.js
export const getInitialProps = ({ query }) => {
return { query }
}
function Page({ query }) {
return <p>Query: {JSON.stringify(query)}</p>
}
// Query: {"foo":"bar","baz":"xyz"}
Get the current URL in getServerSideProps in Next.js
You can import the request object and get the URL from req.url:
export const getServerSideProps = async ({ req }) => {
return {
props: {
url: req.url
}
}
}
function Page({ url }) {
return <p>URL: {url}</p>
}
// URL: /current-page?foo=bar
Get the current URL including hash
Use router.asPath to get the URL with hash:
const router = useRouter()
const url = router.asPath
// url = /current-page#section-2
Get the preview URL when using preview mode
The preview data contains the preview URL:
export const getStaticProps = async ({ previewData }) => {
return {
props: {
previewUrl: previewData?.previewUrl
}
}
}
// previewUrl = /api/preview?secret=...&slug=...
Difference between pathname
and asPath
in Next.js for getting the URL
The pathname
get the path section of the URL only whereas asPath
get the full URL including query parameters and hash. For example the pathname
would give ‘/blog/post-1‘ and asPath
would give ‘/blog/post-1?published=false#comments‘
Conclusion
We have discussed how to easily fetch the current URL in the NExt js application on the Client or Server side using various methods. based on the requirements and functionality of your application you can easily choose between the various techniques. Hope this was helpful.
Leave a Reply