Ask your question and get a summary of the document by referencing this page and the AI provider of your choice
The content of this page was translated using an AI.
See the last version of the original content in EnglishIf you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.
GitHub link to the documentationCopy doc Markdown to clipboard
useRewriteURL Hook
The useRewriteURL hook for Next.js is a client-side hook that automatically manages localised URL rewrites. It ensures that the browser's address bar always reflects the "pretty" localised path defined in your intlayer.config.ts, even if the user manually types a canonical path with a locale prefix.
This hook operates silently by using window.history.replaceState, avoiding redundant Next.js router navigations or page reloads.
Usage
Simply call the hook in a Client Component that is part of your layout.
How it works
- Path Monitoring: The hook listens for changes to the user's
locale. - Rewrite Detection: It checks the current
window.location.pathnameagainst the rewrite rules in your configuration. - URL Correction: If a prettier localised alias is found for the current path, the hook triggers a
window.history.replaceStateto update the address bar while keeping the user on the same internal page.
Why use it in Next.js?
While the intlayerMiddleware handles server-side rewrites and initial redirects, the useRewriteURL hook ensures that the browser's URL remains consistent with your preferred SEO structure even after client-side transitions.
- Clean URLs: Enforces the use of localised segments like
/fr/essaisinstead of/fr/tests. - Performance: Updates the address bar without triggering a full router cycle or re-fetching data.
- SEO Alignment: Prevents duplicate content issues by ensuring only one URL version is visible to the user and search engine bots.