3

How can I access the domain name and full path in a server component in Next.js 13 using the app directory? In previous versions of Next.js (such as version 12), I could do this using context in the getServerSideProps function, but this is no longer supported in the app directory.

I have a small SaaS app where different domains can point to the same Next.js code, and by passing the domain and pathname, I can get data from the API for that particular account, same like WordPress multisite I think.

Is there a better way to do this in Next.js 13 with the app directory? Please help.

Sohail
  • 2,058
  • 7
  • 33
  • 57

1 Answers1

7

You can do something like this :

import { headers } from 'next/headers';

export default function Home() {
  const headersList = headers();
  
  headersList.get('host'); // to get domain
  headersList.get('next-url'); // to get url

  return <div>....</div>
}
Mathis
  • 3
  • 1
  • 3
Sohail
  • 2,058
  • 7
  • 33
  • 57
  • 2
    please note that [Using it in a layout or page will opt a route into dynamic rendering at request time](https://nextjs.org/docs/app/api-reference/functions/headers#:~:text=Using%20it%20in%20a%20layout%20or%20page%20will%20opt%20a%20route%20into%20dynamic%20rendering%20at%20request%20time) – Gangula May 27 '23 at 08:49
  • Very much helpful. Thank you. – Mehadi Hassan Jun 06 '23 at 04:17
  • This was really helpful. I was looking for some way to get the current URL in layout.tsx so that I can generate the dynamic metadata in next.js 13. – Zain Ul Abdin Jun 26 '23 at 16:03