乐闻世界logo
搜索文章和话题

How to get page url or hostname in nextjs project?

3个答案

1
2
3

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.

jsx
export 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:

jsx
import { 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:

jsx
const 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.

jsx
import 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:

jsx
const MyComponent = () => { const router = useRouter(); const { id } = router.query; // Retrieve dynamic routing parameters // ... };

In getServerSideProps:

jsx
export 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.

2024年6月29日 12:07 回复

When accessing the URL, always include a window check to ensure the code runs only in the browser and not during SSG.

javascript
if (typeof window !== 'undefined') { const hostname = window.location.hostname; }

Update: If you have specified basePath in next.config.js:

javascript
module.exports = { basePath: 'https://www.example.com/docs', };

Then, using useRouter, you can access the base path:

javascript
import { useRouter } from 'next/router' function Component() { const router = useRouter(); console.log({ basePath: router.basePath}); // { basePath: 'https://www.example.com/docs' } ... }

However, if you have a relative base path, you can use the first method.

2024年6月29日 12:07 回复

If you need the hostname within server-side getInitialProps, you can still retrieve it from req.

javascript
Home.getInitialProps = async(context) => { const { req, query, res, asPath, pathname } = context; if (req) { let host = req.headers.host // This will return the host, e.g., localhost:3000 } }
2024年6月29日 12:07 回复

你的答案