Created
November 5, 2019 21:46
-
-
Save darknoon/dd42d10ad523393dc0f91b1a5edad3a7 to your computer and use it in GitHub Desktop.
A simple way to get the right host to query your API in serverless next.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getHost = (context: NextPageContext): { host: string; proto: string } => { | |
const { req } = context; | |
if (req !== undefined) { | |
const { | |
"x-forwarded-host": host, | |
"x-forwarded-proto": proto | |
} = req.headers; | |
if ( | |
typeof host === "string" && | |
typeof proto === "string" && | |
(proto === "http" || proto === "https") | |
) { | |
// Proto doesn't have the colon on server | |
return { host, proto: proto + ":" }; | |
} | |
} else if (window && window.location) { | |
// Parse url to determine our current host | |
const { href } = window.location; | |
const { host, protocol: proto } = new URL(href); | |
return { host, proto }; | |
} | |
throw new Error("Could not determine host to fetch API."); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment