Skip to content

Instantly share code, notes, and snippets.

@darknoon

darknoon/getHost.ts

Created Nov 5, 2019
Embed
What would you like to do?
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