Skip to content
brought to you byVoidZero

Rewrites ​

Use the Hono context to rewrite a request or read its original URL.

c.rewrite(destination) ​

Serve the response from another route while keeping the original URL in the browser. For example, c.rewrite("/search") keeps the incoming query, while c.rewrite("/search?q=void") replaces it with ?q=void.

Use a path starting with /. RewriteDestination suggests known routes in your editor and accepts strings for paths you build at runtime.

Pass a RouteDestination object to check the route pattern and its parameters:

ts
return c.rewrite({
  pathname: '/users/[id]',
  params: { id: 42 },
  query: { tab: 'activity' },
});

With routing.typedRoutes, a string destination must be a RouteUrl: a URL that matches one of your routes. Cast a path built at runtime, such as c.rewrite(`/${locale}${path}` as RouteUrl).

With routing.typedRoutes, c.redirect() checks strings like a link: route URLs, same-page queries and hashes, and http://, https://, mailto:, or tel: URLs. It also accepts a URL or typed destination object.

For a string TypeScript can't check, such as a payment provider's checkout URL, use as Href:

ts
import { routeUrl, type Href } from 'void/routes';

declare const checkoutUrl: string;

return c.redirect(routeUrl('/users/[id]', { params: { id: 42 } }));
return c.redirect({ pathname: '/users/[id]', params: { id: 42 } });
return c.redirect('https://example.com/login');
return c.redirect(checkoutUrl as Href);

A cast skips the type check; Void doesn't validate redirect destinations at runtime. For request values such as ?redirectTo=, check the origin before redirecting:

ts
const requested = new URL(c.req.query('redirectTo') ?? '/', c.req.url);
return c.redirect(requested.origin === new URL(c.req.url).origin ? requested : '/');

c.redirect() sends the location you provide without adding the request query. From /sign-in?redirectTo=/notes, c.redirect('/notes') goes to /notes. Configured routing.redirects merge query parameters instead.

A named action keeps its own query parameters. For example, POST /users/42?delete&tab=profile with c.redirect('/users/42') redirects to /users/42?tab=profile. The action key is removed when the redirect changes the method to GET.

Redirects that preserve the method keep the action key: 307 and 308, or 301 and 302 after PUT, PATCH, or DELETE. Parameters added from the current page's query aren't carried into the redirect.

ts
import { defineHandler } from 'void';

export const GET = defineHandler((c) => {
  const locale = c.req.header('accept-language')?.startsWith('de') ? 'de' : 'en';
  return c.rewrite(`/${locale}${new URL(c.req.url).pathname}`);
});

Signature:

ts
interface CloudContext {
  // RouteUrl instead of RewriteDestination with routing.typedRoutes
  rewrite(destination: RewriteDestination | RouteDestination): Promise<Response>;
}

Caveats:

  • destination must start with a single / and point at an internal path. External URLs, protocol-relative destinations (//host/...), and anything non-path-absolute throw immediately — use fetch() for cross-origin calls.
  • Destinations whose final path segment ends in a known static-asset extension (e.g. /hero.png, /app.css, /data.json) throw VoidAssetRewriteError (exported from "void") before the re-dispatch. Runtime rewrites cannot reach assets — use a static routing.rewrites rule or a _redirects 200! entry. .html routes are allowed. See Rewrites.
  • Middleware re-runs on every rewrite hop. Guard side-effects with c.isRewritten().
  • Client-side SPA navigation via Link does not trigger server rewrites; only full HTTP requests do.
  • Purge the destination path to clear rewritten ISR entries.

c.originalUrl() / c.isRewritten() ​

Context methods for inspecting rewrite state. c.originalUrl() returns the pre-rewrite URL as a URL object, or null on the first, non-rewritten hop. c.isRewritten() returns true on any re-dispatched context and false on the original. Use them for both static and middleware rewrites.

ts
import { defineMiddleware } from 'void';

export default defineMiddleware(async (c, next) => {
  if (!c.isRewritten()) {
    // Only log the user-visible request, not internal rewrite hops.
    console.log(`${c.req.method} ${c.req.path}`);
  }
  await next();
});

Signature:

ts
interface CloudContext {
  originalUrl(): URL | null;
  isRewritten(): boolean;
}

RewriteDestination ​

ts
import type { RewriteDestination } from 'void/routes';

Suggests known route patterns in your editor while also accepting dynamic strings. Used as:

  • The parameter type of c.rewrite(), unless routing.typedRoutes is on.
  • The type of destination entries in routing.rewrites and routing.fallbacks in void.config.ts.