In Nuxt.js, retrieving the website's hostname during server-side rendering can be achieved through the Nuxt context object context. The context object contains many useful properties, such as req (request object) and env (environment variables), which can help us retrieve the current hostname on the server side.
Example Steps
- Using
asyncDataorfetchMethods in Pages or Components
Both methods provide a parameter context, through which you can access the server-side request object.
javascriptasync asyncData({ req }) { let host; if (req) { host = req.headers.host; // Retrieve the hostname (including port number) } return { host }; }
- Using in Middleware
If you need to retrieve the hostname within global or specific page middleware for conditional logic processing, you can also use the context object.
javascriptexport default function ({ req, redirect }) { const host = req.headers.host; // For example, redirect to different paths based on the hostname if (host === 'example.com') { redirect('/special-path'); } }
Important Notes
-
Ensure
reqObject is Used Only on the Server Side Thereqobject is only available on the server side. Therefore, you need to useif (process.server)to ensure the code executes only on the server side, avoiding errors during client-side rendering. -
Format of the Hostname The hostname retrieved from
req.headers.hosttypically includes the port number (if present), such aslocalhost:3000. If you only need the domain name, you may need to process the string appropriately.
Using these methods, you can adjust the server-side rendered content based on different hostnames, which is very useful for SEO optimization or providing specific content based on the domain.