Published on

How to get Request Host Domain in Next.js getServerSideProps

Authors

Here's a little snippet on how to get current request host domain in Next.js's getServerSideProps

export async function getServerSideProps(context) {
  const host = context.req.headers.host;
  console.log({ host });
  return {
    props: {host}, // will be passed to the page component as props
  }
}

Context

  • getServerSideProps is used when we need to get some props from the server side.
  • It runs ONLY on the server so you can perform operations like talk to database or perform some operation and then return props to the frontend
  • Then the frontend can use the props in the client side.
  • It has access to all the request related information like host, path, cookies, etc. And this is sort of similar to that of Express approach.
  • If you host it on Vercel, then it'll run in serverless environment.

Happy server-side props!