![]() |
In Next.js, we can get current url domain with the help of built-in methods like window and document location. In this article, we’ll explore different approaches and best practices for obtaining the current URL domain in Next.js applications. The approaches to get the URL of the current domain in next.js are given below: Table of Content Why Accessing the Current URL Domain is Important ?Obtaining the current URL domain is useful for various purposes in web development, such as:
Steps to Create the Next.js ApplicationStep 1: Set up React Project using the Command: npx create-next-app url-domain Step 2: Navigate to the Project folder using: cd url-domain Project Structure: The updated dependencies in package.json file will look like: "dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.1"
} Approach 1: Using window.locationTo get the current URL domain in Next.js using Syntax: window.location.origin Example: The below example uses window.location to Get The Current URL Domain in NextJS.
Step to run the application: Now run the application with the below command: npm run dev Output: Approach 2: Using document.locationIn this approach, we are using the useState hook in a Next.js page component (HomePage) to manage states for the current URL’s hostname, protocol, port, and the full URL itself (currHostName, currProtocol, currPort, and currURL). By invoking document.location and window.location properties within the handleGetURLDetails function, we dynamically fetch and display the corresponding URL details when the “Get URL Details” button is clicked. Syntax: document.location.href Example: The below example uses document.location to Get The Current URL Domain in NextJS.
Step to run the application: Now run the application with the below command: npm run dev Output: |
Reffered: https://www.geeksforgeeks.org
ReactJS |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 7 |