Calling the api server side #12419
-
I've built an API using Next.js' API functionality. It's great when I need to call it client side as I can just call However when calling it on the server, in getInitialProps for example, I need to use an absolute url or it won't work. My current solution is something like this:
This gets really verbose, is there a better solution I'm missing? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
The easiest solution is to read the URL from env vars. Alternatively, with access to the const url = `${protocol}://${req.headers.host}` Be aware that this makes you vulnerabe to the Host Header Attack, check if your host is protected against it (Vercel isn't vulnerable). |
Beta Was this translation helpful? Give feedback.
-
For anyone looking for https://github.com/zeit/next.js/blob/canary/examples/amp-first/pages/index.js#L242 |
Beta Was this translation helpful? Give feedback.
-
I use an environment variable per deployment. |
Beta Was this translation helpful? Give feedback.
The easiest solution is to read the URL from env vars. Alternatively, with access to the
req
object, you can get the client URL in the server withBe aware that this makes you vulnerabe to the Host Header Attack, check if your host is protected against it (Vercel isn't vulnerable).