Best way to handle /:lang prefix routes without catch-all behavior? #4639
Unanswered
kevinsimper
asked this question in
Q&A
Replies: 1 comment
-
|
Here are a few patterns to handle language prefix routes more elegantly: Option 1: Use regex to restrict the lang parameter // Only match specific language codes
app.get("/:lang{(en|da|de|fr)}", (c) => {
// frontpage
})
app.get("/:lang{(en|da|de|fr)}/features", (c) => {
// features page
})Option 2: Create a language validation middleware const SUPPORTED_LANGS = ["en", "da", "de", "fr"];
const validateLang = async (c, next) => {
const lang = c.req.param("lang");
if (!SUPPORTED_LANGS.includes(lang)) {
return c.notFound();
}
return next();
};
// Apply to all lang routes
app.use("/:lang/*", validateLang);
app.use("/:lang", validateLang);
app.get("/:lang", (c) => {
// frontpage
});
app.get("/:lang/features", (c) => {
// features page
});Option 3: Use route groups with basePath const langApp = new Hono();
langApp.get("/", (c) => {
// frontpage
});
langApp.get("/features", (c) => {
// features page
});
// Mount for each language
app.route("/en", langApp);
app.route("/da", langApp);Option 4: Define static routes first (order matters) // Static routes first
app.get("/api/*", apiHandler);
app.get("/assets/*", staticHandler);
// Then lang routes
app.get("/:lang", langHandler);I'd recommend Option 1 (regex) for simplicity, or Option 2 (middleware) for more flexibility. If this solves your problem, please mark it as the answer! ✅ |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm building a multilingual site with routes like:
The problem is /:lang matches everything - including /notarealpage
Currently I'm working around this with manual checks:
This works but is verbose and easy to forget when adding new routes.
Is there a recommended pattern for language prefix routing?
Beta Was this translation helpful? Give feedback.
All reactions