Created
December 6, 2023 09:52
-
-
Save nmattia/f703954e48f973b93cfeb778ce726f56 to your computer and use it in GitHub Desktop.
Netlify Edge Function for token-based website access (using cookie)
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
// On first access looks up a search param: `?token=...` | |
// If the token is valid, saves it in cookies so that | |
// subsequent requests don't need the search param. | |
import type { Config, Context } from "@netlify/edge-functions"; | |
// Ideally look up from the environment | |
const EXPECTED_TOKEN = "very-secret"; | |
const TOKEN_COOKIE_NAME = "my-token"; | |
const TOKEN_HEADER_NAME = "x-my-token"; | |
const TOKEN_PARAM_NAME = "token"; | |
const findCookie = ( | |
headers: Headers, | |
cookieName: string, | |
): string | undefined => { | |
const cookies = headers.get("cookie"); | |
if (cookies === null) { | |
return undefined; | |
} | |
for (const pair of cookies.split(";").filter(Boolean)) { | |
const [key, val] = pair.trim().split("="); | |
if (key === TOKEN_COOKIE_NAME && val !== undefined) { | |
return val; | |
} | |
} | |
}; | |
export default async (request: Request, context: Context) => { | |
const tokenCookie = findCookie(request.headers, TOKEN_COOKIE_NAME); | |
if (tokenCookie === EXPECTED_TOKEN) { | |
return context.next(); | |
} | |
const url: URL = new URL(request.url); | |
const tokenParam = url.searchParams.get(TOKEN_PARAM_NAME); | |
if (tokenParam !== EXPECTED_TOKEN) { | |
return new Response("Unauthorized", { status: 403 }); | |
} | |
const response = await context.next(); | |
response.headers.set("set-cookie", `${TOKEN_COOKIE_NAME}=${tokenParam}`); | |
return response; | |
}; | |
export const config: Config = { | |
path: "/*", | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment