Write the absolute best, and most robust redirect utility that is cross-compatible…
- User
Write the absolute best, and most robust
redirectutility that is cross-compatible between JavaScript server runtimes with built-in Typescript support. These runtimes include Cloudflare Workers, Deno, and Bun. The utility handles every edge case gracefully. It can redirect to both internal and external locations. Relative redirects first normalize the path and are then used as the value for the a Location header. Redirects to external URLs should use the staticResponse.redirectmethod. The utility is able to check if its input a a full URL or a relative path. If it is an URL it ensures that it is both valid and secure (https), and if it is a path, it normalizes it, making sure that it starts with a single forward slash. It should also allow for a second parameter that is either of type number or the ResponseInit interface. By default it is a value of 302. - Assistant
Here is a robust
redirectutility function written in TypeScript that is cross-compatible between Cloudflare Workers, Deno, and Bun. This function handles every edge case gracefully, ensuring that both internal and external redirects are processed correctly. It normalizes relative paths, validates external URLs to ensure they are secure (use HTTPS), and allows for an optional second parameter that can be a status code or aResponseInitobject./** * Redirects to the given location, handling both internal and external URLs. * Relative paths are normalized and used as the Location header. * External URLs must be valid and use the HTTPS protocol. * @param location - The URL or path to redirect to. * @param init - An optional status code or ResponseInit object. Defaults to 302. * @returns A Response object representing the redirect. */ function redirect(location: string, init?: number | ResponseInit): Response { let status = 302; let headers: HeadersInit = {}; // Determine the status code and extract headers if provided if (typeof init === 'number') { status = init; } else if (init !== undefined) { if (init.status !== undefined) { status = init.status; } if (init.headers !== undefined) { headers = init.headers; } } let isAbsoluteURL = false; let url: URL | null = null; // Check if the location is a valid absolute URL try { url = new URL(location); isAbsoluteURL = true; } catch (err) { // Not a valid absolute URL isAbsoluteURL = false; } if (isAbsoluteURL) { // Ensure the URL uses the HTTPS protocol if (url.protocol !== 'https:') { throw new Error('Redirect URL must use the HTTPS protocol'); } // Use the static Response.redirect method for external URLs return Response.redirect(location, status); } else { // Normalize the relative path const normalizedPath = normalizePath(location); // Set the Location header headers['Location'] = normalizedPath; // Return a new Response with the specified status and headers return new Response(null, { status: status, headers: headers, }); } } /** * Normalizes a relative path to ensure it starts with a single forward slash. * Resolves any '.' or '..' segments in the path. * @param path - The relative path to normalize. * @returns The normalized path. */ function normalizePath(path: string): string { // Remove leading and trailing whitespace path = path.trim(); // Use a dummy base URL to leverage URL path normalization const baseURL = 'http://localhost'; const url = new URL(path, baseURL); // Return the normalized pathname return url.pathname; }Explanation:
-
Type Checking and Status Initialization:
- The function accepts a
locationstring and an optionalinitparameter, which can be anumber(status code) or aResponseInitobject. - It initializes the
statuscode to302by default and extracts any headers provided in theinitparameter.
- The function accepts a
-
URL Validation:
- It attempts to create a new
URLobject with the providedlocation.- If successful, it means the
locationis an absolute URL. - If it is an absolute URL, it checks that the protocol is
https:. If not, it throws an error to ensure security. - For valid and secure URLs, it uses
Response.redirect()to create the redirect response.
- If successful, it means the
- It attempts to create a new
-
Relative Path Handling:
- If the
locationis not an absolute URL, it treats it as a relative path. - The
normalizePathfunction uses theURLconstructor with a dummy base URL to normalize the path. This resolves any.or..segments and ensures the path starts with a single/. - It sets the
Locationheader to the normalized path and returns a newResponsewith the specified status and headers.
- If the
-
Cross-Compatibility:
- The code uses standard web APIs (
URL,Response,HeadersInit) that are available in Cloudflare Workers, Deno, and Bun. - By avoiding environment-specific features, it ensures cross-compatibility between these runtimes.
- The code uses standard web APIs (
Usage Example:
// Redirect to an internal path const response1 = redirect('/about'); // Redirect to an internal path with custom status code const response2 = redirect('contact', 301); // Redirect to an external URL const response3 = redirect('https://example.com'); // Redirect to an external URL with custom status and headers const response4 = redirect('https://secure.example.com', { status: 303, headers: { 'X-Custom-Header': 'value', }, });Edge Case Handling:
- Invalid URLs:
- The function gracefully handles invalid URLs by catching exceptions when creating a
URLinstance.
- The function gracefully handles invalid URLs by catching exceptions when creating a
- Insecure URLs:
- It enforces the use of
httpsfor external redirects to ensure security.
- It enforces the use of
- Path Normalization:
- It resolves relative paths correctly, handling cases where the path might include multiple slashes, dots, or parent directory references.
Notes:
- This utility function is designed to be robust and handle various edge cases as per the specifications.
- It ensures security by enforcing the use of HTTPS for external redirects.
- By normalizing paths and using standard APIs, it maintains compatibility across different JavaScript server runtimes with TypeScript support.
-