Skip to content

Improve DX of redirect() for server-side redirects (type, doc comment, and error message) #4788

@jasongitmail

Description

@jasongitmail

Which project does this relate to?

Router

Describe the bug

For server-side redirects using throw redirect() from import { redirect } from "@tanstack/react-router";

Expectated behavior

Given that throw redirect({to: "..."}) to property accepts a string type, I'd expect any URL to work, including external URLs.

Actual behavior

Turns out it does not accept an external URL and gives a runtime error message that isn't clear:

 {
  message: `Server side redirects must use absolute paths via the 'href' or 'to' options. Received: {"to":"https://...","statusCode":307}`,
  statusCode: 500
}

After I discovered the href property, it redirects to an external URL as expected.

Suggestions to improve DX

  1. Add doc comment for to property describing it's intended for internal links only and guiding to use href for external urls.
Image

The href property has this and it's very helpful for discoverability of the other property.

Image
  1. Consider a stricter type for the to property.

When providing a literal string value, a type error will show if given an external URL. But no type error is shown when the value is a variable that has a of string.
Image

Does to have a fallback type of string, by chance? If so, could this be changed to a template literal type instead like /${string}?

This would make it more clear that an internal path is expected (by enforcing it to start /) and would provide typescript error/warning, instead of only a runtime error, when a fully qualified external URL is used here. (Only protocol-relative URLs could slip through, but this is still an improvement.)

  1. Consider rewording the runtime error message:

Current:

 {
  message: `The redirect() method's "to" property accepts an internal path only. Use the "href" property to provide an external URL. Received: {"to":"https://...","statusCode":307}`,
  statusCode: 500
}

Platform

  • Router Version: 1.129.5
  • Runtime: Cloudflare Workerd

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions