Skip to content

Instantly share code, notes, and snippets.

@darknoon
Created November 5, 2019 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darknoon/dd42d10ad523393dc0f91b1a5edad3a7 to your computer and use it in GitHub Desktop.
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
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