'How to get origin or domain name in Next.js [duplicate]
I can get the relative pathname using useRouter().asPath
which gives something like /my-awesome-post
but how to get the origin?
Similar to what window.location.origin
gives like https://www.google.com
.
Next.js Router docs doesn't mention anything about how to get origin.
I can't use window.location.origin
(next.js gives an error that window is not defined) so what is my alternative?
I want to get the origin inside a component which is not calling getStaticProps
or getServerSideProps
.
Solution 1:[1]
If you are on client-side:
window.location.origin
if you are on the server
That means you are either in serverside functions or api functions. In both cases you have access to
req
object. In node.js we could get the originreq.get('host')
But in next.js we do not have get
property on req
. so I use this npm package: next-absolute-url
import absoluteUrl from 'next-absolute-url'
const { origin } = absoluteUrl(req);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yilmaz |