|
| 1 | +--- |
| 2 | +title: Rewrites | Guides |
| 3 | +description: Learn how to use rewrites in Qwik City. |
| 4 | +contributors: |
| 5 | + - omerman |
| 6 | +updated_at: '2025-05-04T19:43:33Z' |
| 7 | +created_at: '2025-05-04T23:45:13Z' |
| 8 | +--- |
| 9 | + |
| 10 | +# Rewrites |
| 11 | + |
| 12 | +Sometimes you want to redirect a user from the current page to another page, |
| 13 | +but you want to keep the current URL in the browser history. |
| 14 | + |
| 15 | +Let's say a user tries to access an article which is indexed by its name, |
| 16 | +e.g `/articles/qwik-is-very-quick`. |
| 17 | +but in our code, we access it by its id, on our directory structure. |
| 18 | + |
| 19 | +``` |
| 20 | +src/routes/articles/ |
| 21 | +├── [id] |
| 22 | +├─── index.tsx |
| 23 | +``` |
| 24 | + |
| 25 | + |
| 26 | +```tsx title="src/routes/ [email protected]" |
| 27 | +import type { RequestHandler } from "@builder.io/qwik-city"; |
| 28 | + |
| 29 | +export const onRequest: RequestHandler = async ({ url, rewrite }) => { |
| 30 | + const pattern = /^\/articles\/(.*)$/; |
| 31 | + // Detects /articles/<article-name>, returns null if url does not match the pattern. |
| 32 | + const match = url.pathname.match(pattern); |
| 33 | + if (match) { |
| 34 | + const articleName = match[1]; |
| 35 | + const { id } = await db.getArticleByName(articleName); |
| 36 | + throw rewrite(`/articles/${id}`); |
| 37 | + } |
| 38 | +}; |
| 39 | +``` |
| 40 | + |
| 41 | +The `rewrite()` function, which was destructured in the RequestHandler function arguments, takes a pathname string or a URL object. |
| 42 | + |
| 43 | +```tsx |
| 44 | +throw rewrite(`/articles/777/`); |
| 45 | +throw rewrite(new URL(`/articles/777/`, url)); |
| 46 | +``` |
| 47 | + |
| 48 | +Note: If you provide a relative path, Qwik City will rewrite the URL and apply search params from the original URL. |
0 commit comments