Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: simplify redirect url pattern #31

Closed
wants to merge 7 commits into from

Conversation

zhongliang02
Copy link
Contributor

Context

Currently, there's a common pattern across multiple codebases for handling redirect URLs:

const validator = new UrlValidator({
  baseOrigin: new URL(baseUrl).origin,
  whitelist: {
    protocols: ['http', 'https'],
    hosts: [new URL(baseUrl).host],
  }
})

export const callbackUrlSchema = z
  .string()
  .optional()
  .default(RECORDINGS)
  .transform((url, ctx) => {
    try {
      return validator.parse(url)
    } catch (error) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: (error as Error).message,
      })
      return z.NEVER
    }
  })
  .catch(new URL(RECORDINGS, baseUrl))

...

await router.push(callbackUrlSchema.parse(router.query[CALLBACK_URL_KEY]))

...

Changes

This PR introduces three key improvements to our URL validation and redirection process:

  1. New RelUrlValidator Class
    Simplifies the creation of UrlValidator with sensible defaults
    Usage: new RelUrlValidator(origin: string | URL)
  2. Enhanced UrlValidator.parse(..., fallbackUrl: string | URL)
    Adds a fallbackUrl parameter
    Eliminates the need to use callbackUrlSchema
  3. parsePathname method
    Introduces UrlValidator.parsePathname(...) that can be directly assigned to window.location.pathname

Example usage

const validator = new RelUrlValidator(baseUrl)
window.location.pathname = validator.parsePathname(router.query['redirect'], '/home'))

@zhongliang02 zhongliang02 deleted the feat/simplify-redirect-url-pattern branch November 19, 2024 07:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant