In Next.js projects, you can obtain the current page's URL or host in multiple ways. Here are some common methods:
On the Server Side (in getServerSideProps or API Routes)
In Next.js server-side code, such as in getServerSideProps or API routes, you can directly retrieve the host and full URL from the request object.
jsxexport async function getServerSideProps(context) { const { req } = context; const host = req.headers.host; // Get host const protocol = req.headers['x-forwarded-proto'] || 'http'; // Note: When deployed on Vercel or other cloud services, using the 'x-forwarded-proto' header to determine the protocol may be more accurate. const fullUrl = `${protocol}://${host}${req.url}`; // Get full URL return { props: {}, // Pass required data as props to the page }; }
Note: req.url only contains the path and query string of the URL, not the protocol or hostname.
On the Client Side (using useRouter or window object)
On the client side, you can use Next.js's useRouter hook or the browser's window object to obtain the current page's URL.
Using the useRouter hook:
jsximport { useRouter } from 'next/router'; const MyComponent = () => { const router = useRouter(); const currentPath = router.asPath; // Get the path and query string of the route // On the client side, you can use the window object to get the full URL const fullUrl = window.location.href; return ( // ... ); }; export default MyComponent;
Using the window.location object directly:
jsxconst MyComponent = () => { // Ensure the window object is used only after the component loads in the browser React.useEffect(() => { const fullUrl = window.location.href; // Use fullUrl }, []); return ( // ... ); }; export default MyComponent;
Ensure that when using the window object, the code is wrapped in the useEffect hook or any logic that ensures client-side execution to avoid reference errors during build.
Using Next.js's Head Component to Dynamically Set Meta Information
If you want to use the URL or host in the <head> tag of your page, you can use Next.js's Head component to dynamically add meta information during server-side rendering.
jsximport Head from 'next/head'; import { useRouter } from 'next/router'; const MyPage = () => { const router = useRouter(); const currentPath = router.asPath; return ( <> <Head> <link rel="canonical" href={`https://yourdomain.com${currentPath}`} /> </Head> {/* Page content */} </> ); }; export default MyPage;
In this example, the <link rel="canonical"> tag is set to the full URL of the current page, assuming you know your domain. If the domain is unknown or changes, you may need to pass it as a configuration parameter or retrieve it from server-side code.
Retrieving Dynamic Routing Parameters
If your page path includes dynamic routing parameters, such as [id].js, you can use the useRouter hook or the context object in getServerSideProps to retrieve these parameters.
Using the useRouter hook:
jsxconst MyComponent = () => { const router = useRouter(); const { id } = router.query; // Retrieve dynamic routing parameters // ... };
In getServerSideProps:
jsxexport async function getServerSideProps(context) { const { params } = context; const { id } = params; // Retrieve dynamic routing parameters // ... }
With these parameters, you can construct related URLs or use them in your page.
In summary, obtaining the current page's URL or host can be done in different ways depending on the runtime context (server-side or client-side) and your specific requirements.