0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-01-06 22:10:10 -05:00
astro/.changeset/little-hornets-give.md
Emanuele Stoppa 440681e7b7
feat(i18n): manual routing (#10193)
* feat(i18n): manual routing

* one more function

* different typing

* tests

* fix merge

* throw error for missing middleware

* rename function

* fix conflicts

* lock file update

* fix options, error thrown and added tests

* rebase

* add tests

* docs

* lock file black magic

* increase timeout?

* fix regression

* merge conflict

* add changeset

* chore: apply suggestions

* apply suggestion

* Update .changeset/little-hornets-give.md

Co-authored-by: Erika <3019731+Princesseuh@users.noreply.github.com>

* chore: address feedback

* fix regression of last commit

* update name

* add comments

* fix regression

* remove unused code

* Apply suggestions from code review

Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>

* chore: update reference

* Update packages/astro/src/@types/astro.ts

Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>

* chore: improve types

* fix regression in tests

* apply Sarah's suggestion

---------

Co-authored-by: Erika <3019731+Princesseuh@users.noreply.github.com>
Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
2024-04-10 15:38:17 +01:00

48 lines
1.4 KiB
Markdown

---
"astro": minor
---
Adds a new i18n routing option `manual` to allow you to write your own i18n middleware:
```js
import { defineConfig } from "astro/config"
// astro.config.mjs
export default defineConfig({
i18n: {
locales: ["en", "fr"],
defaultLocale: "fr",
routing: "manual"
}
})
```
Adding `routing: "manual"` to your i18n config disables Astro's own i18n middleware and provides you with helper functions to write your own: `redirectToDefaultLocale`, `notFound`, and `redirectToFallback`:
```js
// middleware.js
import { redirectToDefaultLocale } from "astro:i18n";
export const onRequest = defineMiddleware(async (context, next) => {
if (context.url.startsWith("/about")) {
return next()
} else {
return redirectToDefaultLocale(context, 302);
}
})
```
Also adds a `middleware` function that manually creates Astro's i18n middleware. This allows you to extend Astro's i18n routing instead of completely replacing it. Run `middleware` in combination with your own middleware, using the `sequence` utility to determine the order:
```js title="src/middleware.js"
import {defineMiddleware, sequence} from "astro:middleware";
import { middleware } from "astro:i18n"; // Astro's own i18n routing config
export const userMiddleware = defineMiddleware();
export const onRequest = sequence(
userMiddleware,
middleware({
redirectToDefaultLocale: false,
prefixDefaultLocale: true
})
)
```