{"_id":"@alt-digital/next-translate-routes","_rev":"6-78f1fb60939e701f0bb74d249b2c354e","name":"@alt-digital/next-translate-routes","dist-tags":{"latest":"1.0.3"},"versions":{"1.0.0":{"name":"@alt-digital/next-translate-routes","version":"1.0.0","keywords":["next","next.js","routes","router","routing","react","intl","i18n","dynamic"],"author":{"name":"cvolant"},"license":"MIT","_id":"@alt-digital/next-translate-routes@1.0.0","maintainers":[{"name":"axxxx0n","email":"arian@altdev.hr"},{"name":"draxx","email":"mauro@altdev.hr"}],"homepage":"https://github.com/hozana/next-translate-routes#readme","bugs":{"url":"https://github.com/hozana/next-translate-routes/issues"},"dist":{"shasum":"23f037a662dbd189b70f91deafdc83bc6a254a1a","tarball":"https://registry.npmjs.org/@alt-digital/next-translate-routes/-/next-translate-routes-1.0.0.tgz","fileCount":124,"integrity":"sha512-tkuJlKhkDrklhw7Bdm3DI+hQVpWCkXQFpEFrKizAs4AVgayITTXTIIjya59LGGz7bIs6wN2y6+DaagvpSC/ccw==","signatures":[{"sig":"MEYCIQDl7MfcM7BaYmAu2UUfdwQy6vZYLwFO1rwKkg7R5t3gzgIhAP0XSTkl4J+dC6cMukV+ol/QOgM3abXaLAyx7Ljl3KjT","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":267652},"main":"index.js","types":"./index.d.ts","gitHead":"3cba72eb7c6acf5dfc7cda41b186432b44bf3101","scripts":{"link":"sudo npm link ../colours-of-istria/node_modules/react ../colours-of-istria/node_modules/react-dom ../colours-of-istria/node_modules/next","lint":"yon eslint --ignore-path .gitignore .","test":"jest","build":"npm run build:clear && tsc","start":"yon install && yon build && cd ./example && yon install && yon build && yon start","format":"yon prettier -c --write .","release":"npx release-it","prerelease":"yon lint && yon build","build:clear":"rimraf 'plugin' 'react' 'shared' './*.d.ts' './*.js.map' './*.js'"},"_npmUser":{"name":"axxxx0n","email":"arian@altdev.hr"},"deprecated":"Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.","repository":{"url":"git+https://github.com/hozana/next-translate-routes.git","type":"git"},"_npmVersion":"10.9.2","description":"Flexible and translated routes for Next.js without custom server","directories":{},"_nodeVersion":"22.14.0","dependencies":{"url":"^0.11.0","yamljs":"^0.3.0","querystring":"^0.2.1","path-to-regexp":"^6.2.0"},"publishConfig":{"registry":"https://registry.npmjs.org"},"_hasShrinkwrap":false,"packageManager":"yarn@3.6.4","devDependencies":{"jest":"^27.4.5","next":"^14.0.4","react":"^18.2.0","eslint":"^7.29.0","rimraf":"^3.0.2","ts-jest":"^27.0.3","webpack":"^5.65.0","prettier":"^2.3.2","react-dom":"^18.2.0","babel-jest":"^27.4.5","typescript":"4.9.5","@babel/core":"^7.8.0","@types/jest":"^27.0.0","yarn-or-npm":"^3.0.1","@types/react":"^18.2.0","@types/yamljs":"^0.2.31","@types/react-dom":"^18.2.0","eslint-plugin-react":"^7.24.0","@testing-library/react":"^13.3.0","eslint-config-prettier":"^8.3.0","eslint-plugin-prettier":"^3.4.0","@typescript-eslint/parser":"^4.28.0","eslint-plugin-react-hooks":"^4.2.0","@typescript-eslint/eslint-plugin":"^4.28.0","@ianvs/prettier-plugin-sort-imports":"^3.4.2"},"peerDependencies":{"next":">=14.0.0","react":">=18.0.0"},"_npmOperationalInternal":{"tmp":"tmp/next-translate-routes_1.0.0_1762252698900_0.4916153426340204","host":"s3://npm-registry-packages-npm-production"}},"1.0.1":{"name":"@alt-digital/next-translate-routes","version":"1.0.1","keywords":["next","next.js","routes","router","routing","react","intl","i18n","dynamic"],"author":{"name":"cvolant"},"license":"MIT","_id":"@alt-digital/next-translate-routes@1.0.1","maintainers":[{"name":"axxxx0n","email":"arian@altdev.hr"},{"name":"draxx","email":"mauro@altdev.hr"}],"homepage":"https://github.com/hozana/next-translate-routes#readme","bugs":{"url":"https://github.com/hozana/next-translate-routes/issues"},"dist":{"shasum":"9c9848a5d888ee78e2c7c9eacb2f807c380682a9","tarball":"https://registry.npmjs.org/@alt-digital/next-translate-routes/-/next-translate-routes-1.0.1.tgz","fileCount":124,"integrity":"sha512-MQAxRhL4nYhCz5L09icGsb2mxDwvZJ6jbOxyh/7fSv5KnpB0FVmQB4+OuY6mbl35WZNY3Zh2U09akQdBqTGvfg==","signatures":[{"sig":"MEYCIQCUvmguyNmew4ONi9Ts9gOoDsdaBfZflO4U4/jlk9ItDAIhANfAZHEjE3WGMW3SLw6zg3SYi4/1cmac4Km38LOnMAdh","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":267586},"main":"index.js","types":"./index.d.ts","gitHead":"2d8cf5c1604368f57aff3b1f904b17ffc006e1ff","scripts":{"link":"sudo npm link ../colours-of-istria/node_modules/react ../colours-of-istria/node_modules/react-dom ../colours-of-istria/node_modules/next","lint":"yon eslint --ignore-path .gitignore .","test":"jest","build":"npm run build:clear && tsc","start":"yon install && yon build && cd ./example && yon install && yon build && yon start","format":"yon prettier -c --write .","release":"npx release-it","prerelease":"yon lint && yon build","build:clear":"rimraf 'plugin' 'react' 'shared' './*.d.ts' './*.js.map' './*.js'"},"_npmUser":{"name":"axxxx0n","email":"arian@altdev.hr"},"deprecated":"Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.","repository":{"url":"git+https://github.com/hozana/next-translate-routes.git","type":"git"},"_npmVersion":"10.9.2","description":"Flexible and translated routes for Next.js without custom server","directories":{},"_nodeVersion":"22.14.0","dependencies":{"url":"^0.11.0","yamljs":"^0.3.0","querystring":"^0.2.1","path-to-regexp":"^6.2.0"},"publishConfig":{"registry":"https://registry.npmjs.org"},"_hasShrinkwrap":false,"packageManager":"yarn@3.6.4","devDependencies":{"jest":"^27.4.5","next":"^14.0.4","react":"^18.2.0","eslint":"^7.29.0","rimraf":"^3.0.2","ts-jest":"^27.0.3","webpack":"^5.65.0","prettier":"^2.3.2","react-dom":"^18.2.0","babel-jest":"^27.4.5","typescript":"4.9.5","@babel/core":"^7.8.0","@types/jest":"^27.0.0","yarn-or-npm":"^3.0.1","@types/react":"^18.2.0","@types/yamljs":"^0.2.31","@types/react-dom":"^18.2.0","eslint-plugin-react":"^7.24.0","@testing-library/react":"^13.3.0","eslint-config-prettier":"^8.3.0","eslint-plugin-prettier":"^3.4.0","@typescript-eslint/parser":"^4.28.0","eslint-plugin-react-hooks":"^4.2.0","@typescript-eslint/eslint-plugin":"^4.28.0","@ianvs/prettier-plugin-sort-imports":"^3.4.2"},"peerDependencies":{"next":">=14.0.0","react":">=18.0.0"},"_npmOperationalInternal":{"tmp":"tmp/next-translate-routes_1.0.1_1762253426393_0.8136302460331031","host":"s3://npm-registry-packages-npm-production"}},"1.0.2":{"name":"@alt-digital/next-translate-routes","version":"1.0.2","keywords":["next","next.js","routes","router","routing","react","intl","i18n","dynamic"],"author":{"name":"cvolant"},"license":"MIT","_id":"@alt-digital/next-translate-routes@1.0.2","maintainers":[{"name":"axxxx0n","email":"arian@altdev.hr"},{"name":"draxx","email":"mauro@altdev.hr"}],"homepage":"https://github.com/hozana/next-translate-routes#readme","bugs":{"url":"https://github.com/hozana/next-translate-routes/issues"},"dist":{"shasum":"041dc06baa8fa4897d225116fbe459e831fa4dd7","tarball":"https://registry.npmjs.org/@alt-digital/next-translate-routes/-/next-translate-routes-1.0.2.tgz","fileCount":124,"integrity":"sha512-KV39ZYVJLsxCtvzoS8TO0WS5adsw2aGhvs7ngRtHqmSQoaR/F3Hdx5MDZFvNwKKyAd9dwYT7vtUm05Jm4fA5HA==","signatures":[{"sig":"MEUCIB/l2MH701un53UTVZBjZWJKF2Imobq00teSlm+nOat1AiEApRmbEKwcsIdh5HebxthWnqsiWCUmBI0/P6z5pLkKCg0=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":267272},"main":"index.js","types":"./index.d.ts","gitHead":"6e190fab29cb7b5a89086d7100d80a2dc58943af","scripts":{"link":"sudo npm link ../colours-of-istria/node_modules/react ../colours-of-istria/node_modules/react-dom ../colours-of-istria/node_modules/next","lint":"yon eslint --ignore-path .gitignore .","test":"jest","build":"npm run build:clear && tsc","start":"yon install && yon build && cd ./example && yon install && yon build && yon start","format":"yon prettier -c --write .","release":"npx release-it","prerelease":"yon lint && yon build","build:clear":"rimraf 'plugin' 'react' 'shared' './*.d.ts' './*.js.map' './*.js'"},"_npmUser":{"name":"axxxx0n","email":"arian@altdev.hr"},"deprecated":"Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.","repository":{"url":"git+https://github.com/hozana/next-translate-routes.git","type":"git"},"_npmVersion":"10.9.2","description":"Flexible and translated routes for Next.js without custom server","directories":{},"_nodeVersion":"22.14.0","dependencies":{"url":"^0.11.0","yamljs":"^0.3.0","querystring":"^0.2.1","path-to-regexp":"^6.2.0"},"publishConfig":{"registry":"https://registry.npmjs.org"},"_hasShrinkwrap":false,"packageManager":"yarn@3.6.4","devDependencies":{"jest":"^27.4.5","next":"^14.0.4","react":"^18.2.0","eslint":"^7.29.0","rimraf":"^3.0.2","ts-jest":"^27.0.3","webpack":"^5.65.0","prettier":"^2.3.2","react-dom":"^18.2.0","babel-jest":"^27.4.5","typescript":"4.9.5","@babel/core":"^7.8.0","@types/jest":"^27.0.0","yarn-or-npm":"^3.0.1","@types/react":"^18.2.0","@types/yamljs":"^0.2.31","@types/react-dom":"^18.2.0","eslint-plugin-react":"^7.24.0","@testing-library/react":"^13.3.0","eslint-config-prettier":"^8.3.0","eslint-plugin-prettier":"^3.4.0","@typescript-eslint/parser":"^4.28.0","eslint-plugin-react-hooks":"^4.2.0","@typescript-eslint/eslint-plugin":"^4.28.0","@ianvs/prettier-plugin-sort-imports":"^3.4.2"},"peerDependencies":{"next":">=14.0.0","react":">=18.0.0"},"_npmOperationalInternal":{"tmp":"tmp/next-translate-routes_1.0.2_1762253487335_0.9307593258333964","host":"s3://npm-registry-packages-npm-production"}},"1.0.3":{"name":"@alt-digital/next-translate-routes","version":"1.0.3","keywords":["next","next.js","routes","router","routing","react","intl","i18n","dynamic"],"author":{"name":"cvolant"},"license":"MIT","_id":"@alt-digital/next-translate-routes@1.0.3","maintainers":[{"name":"axxxx0n","email":"arian@altdev.hr"},{"name":"draxx","email":"mauro@altdev.hr"}],"homepage":"https://github.com/hozana/next-translate-routes#readme","bugs":{"url":"https://github.com/hozana/next-translate-routes/issues"},"dist":{"shasum":"6937e163a7e57247684e83e4d4f61d3cad0224a9","tarball":"https://registry.npmjs.org/@alt-digital/next-translate-routes/-/next-translate-routes-1.0.3.tgz","fileCount":124,"integrity":"sha512-ndVocjA0ZQP14d6N6t7wu84GB45cm4U3mc0z/DBW3ssigUtHagQ5iHNHwpvPe/BlqeCIdIQycr/tHSs1KQMARg==","signatures":[{"sig":"MEQCIDraBz1663Bp35rmvaiCYwduVjeJE9q4NUW3/Xzla45pAiBY2lSeXsR4fJ12phgmrfvdb5qcJY50ZlTg1cPQaRqK1A==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":267338},"main":"index.js","types":"./index.d.ts","gitHead":"6e190fab29cb7b5a89086d7100d80a2dc58943af","scripts":{"link":"sudo npm link ../colours-of-istria/node_modules/react ../colours-of-istria/node_modules/react-dom ../colours-of-istria/node_modules/next","lint":"yon eslint --ignore-path .gitignore .","test":"jest","build":"npm run build:clear && tsc","start":"yon install && yon build && cd ./example && yon install && yon build && yon start","format":"yon prettier -c --write .","release":"npx release-it","prerelease":"yon lint && yon build","build:clear":"rimraf 'plugin' 'react' 'shared' './*.d.ts' './*.js.map' './*.js'"},"_npmUser":{"name":"axxxx0n","email":"arian@altdev.hr"},"deprecated":"Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.","repository":{"url":"git+https://github.com/hozana/next-translate-routes.git","type":"git"},"_npmVersion":"10.9.2","description":"Flexible and translated routes for Next.js without custom server","directories":{},"_nodeVersion":"22.14.0","dependencies":{"url":"^0.11.0","yamljs":"^0.3.0","querystring":"^0.2.1","path-to-regexp":"^6.2.0"},"publishConfig":{"registry":"https://registry.npmjs.org"},"_hasShrinkwrap":false,"packageManager":"yarn@3.6.4","devDependencies":{"jest":"^27.4.5","next":"^14.0.4","react":"^18.2.0","eslint":"^7.29.0","rimraf":"^3.0.2","ts-jest":"^27.0.3","webpack":"^5.65.0","prettier":"^2.3.2","react-dom":"^18.2.0","babel-jest":"^27.4.5","typescript":"4.9.5","@babel/core":"^7.8.0","@types/jest":"^27.0.0","yarn-or-npm":"^3.0.1","@types/react":"^18.2.0","@types/yamljs":"^0.2.31","@types/react-dom":"^18.2.0","eslint-plugin-react":"^7.24.0","@testing-library/react":"^13.3.0","eslint-config-prettier":"^8.3.0","eslint-plugin-prettier":"^3.4.0","@typescript-eslint/parser":"^4.28.0","eslint-plugin-react-hooks":"^4.2.0","@typescript-eslint/eslint-plugin":"^4.28.0","@ianvs/prettier-plugin-sort-imports":"^3.4.2"},"peerDependencies":{"next":">=14.0.0","react":">=18.0.0"},"_npmOperationalInternal":{"tmp":"tmp/next-translate-routes_1.0.3_1762253770825_0.5595543531720961","host":"s3://npm-registry-packages-npm-production"}}},"time":{"created":"2025-11-04T10:38:18.821Z","modified":"2026-07-21T12:09:22.271Z","1.0.0":"2025-11-04T10:38:19.117Z","1.0.1":"2025-11-04T10:50:26.607Z","1.0.2":"2025-11-04T10:51:27.530Z","1.0.3":"2025-11-04T10:56:10.995Z"},"bugs":{"url":"https://github.com/hozana/next-translate-routes/issues"},"author":{"name":"cvolant"},"license":"MIT","homepage":"https://github.com/hozana/next-translate-routes#readme","keywords":["next","next.js","routes","router","routing","react","intl","i18n","dynamic"],"repository":{"url":"git+https://github.com/hozana/next-translate-routes.git","type":"git"},"description":"Flexible and translated routes for Next.js without custom server","maintainers":[{"email":"arian@altdev.hr","name":"axxxx0n"}],"readme":"# Next-translate-routes\n\nTranslated routing and more for Next `/pages` router using Next regular file-base routing system\n\n- [Features](#features)\n  - [Unsupported features](#unsupported-features)\n- [Motivation](#motivation)\n- [How to](#how-to)\n  - [Basic usage](#basic-usage)\n    1. [Wrap you next config with the next-translate-routes plugin](#1-wrap-you-next-config-with-the-next-translate-routes-plugin)\n    2. [Define your routes](#2-define-your-routes)\n    3. [Wrap your `\\_app` component with the `withTranslateRoutes` hoc](#3-wrap-you-_app-component-with-the-withtranslateroutes-hoc)\n    4. [Use `next-translate-routes/link` instead of `next/link`](#4-use-next-translate-routeslink-instead-of-nextlink)\n    5. [Use `next-translate-routes/router instead` of `next/router` for singleton router (default export)](#5-use-next-translate-routesrouter-instead-of-nextrouter-for-singleton-router-default-export)\n    6. [Use a middleware to redirect from urls prefixed by default locale](#6-use-a-middleware-to-redirect-from-urls-with-the-default-locale-prefix)\n  - [Advanced usage](#advanced-usage)\n    - [Configuration](#configuration)\n    - [Translate/untranslate urls](#translateuntranslate-urls)\n    - [Alternate pages (SEO)](#alternate-pages-seo)\n    - [Sitemap](#sitemap)\n    - [Constrained dynamic paths segments](#constrained-dynamic-paths-segments)\n    - [Ignoring a path part](#ignoring-a-path-part)\n    - [Complex paths segments](#complex-paths-segments)\n    - [Custom route tree](#custom-route-tree)\n    - [Outside Next](#outside-next)\n    - [Fallback languages](#fallback-languages)\n- [Known issue](#known-issues)\n  - [Middleware with Next >=12.2.0](#middleware-with-watcher-next-1220)\n  - [Optional catch all with rewrites](#optional-catch-all-with-rewrites)\n  - [With @sentry/nextjs](#with-sentrynextjs)\n- [How does it work](#how-does-it-work)\n\n## Features\n\n- **Translated paths segments**  \n  Ex: `/contact-us` and `/fr/contactez-nous`.\n- **Complex paths segments** (path-to-regexp syntax)  \n  Ex: `/:id{-:slug}?/`\n- **Constrained dynamic paths segments** (path-to-regexp syntax)  \n  Ex: `/:id(\\\\d+)/`\n- **No duplicated content (SEO)**  \n  Simple rewrites would make a page accessible with 2 different urls which is bad for SEO.\n- **Auto-redirection to correct translated path**  \n  Ex: `/fr/english/path` redirects to `/fr/french/path`\n- **No custom server needed!**  \n  Next automatic static optimization remains available.\n\nSee it in action: <https://codesandbox.io/s/github/hozana/next-translate-routes/tree/master>\n\n### Unsupported features\n\n- **`/app` router is not supported**: with `/app` router, you can use [next-roots](https://www.npmjs.com/package/next-roots).\n- Html static export is not and will never be supported by next-translate-routes, since internationalized routing is among [static html export unsupported features](https://nextjs.org/docs/advanced-features/static-html-export#unsupported-features).\n- Domain routing is not supported yet but could be in the future. Any help would be appreciated, see [here](https://github.com/hozana/next-translate-routes/issues/20#issuecomment-1571882827).\n\n## Motivation\n\nTo build a fully internationalized website, one need to translate url segments: it is important for UX and SEO.\nFor now, Next only ship with locale prefixes ([see Next.js internationalized routing doc](https://nextjs.org/docs/advanced-features/i18n-routing)).\n\nThe [next-routes](https://github.com/fridays/next-routes) package allow fully internationalized routing but it is no longer maintained, and it is designed without the latest Next api, such as internationalized routing, new data fetching methods, automatic static optimization.  \nTo be able to use theses, a new approach is needed. Next.js provides it with [Redirects](https://nextjs.org/docs/api-reference/next.config.js/redirects) and [Rewrites](https://nextjs.org/docs/api-reference/next.config.js/rewrites), but:\n\n- the main problem is that writing the rewrites and redirects to translate all the routes by hand is long, boring, error-prone, and hard to maintain.\n- an other problem is that by default, the file path works with all the locale prefixes: it creates 2 urls for the same content, which is not good for SEO. This problem can be worked around by creating redirects from `/${localePrefix}/$(filePath)` to `/${localePrefix}/$(localePath)`, but it creates a lot more complexity to write by hand and maintain.\n\n## How to\n\n### Basic usage\n\nCheck the example folder to see next-translate-routes in action. Some advanced techniques are shown there too: they may seem complicated but those 4 steps should cover most of the cases.\n\n#### 1. Wrap you next config with the next-translate-routes plugin\n\nImport the `withTranslateRoutes` from `next-translate-routes/plugin`.\n\n```javascript\n// next.config.js\nconst withTranslateRoutes = require('next-translate-routes/plugin')\n\nmodule.exports = withTranslateRoutes({\n  // Next i18n config (mandatory): https://nextjs.org/docs/advanced-features/i18n-routing\n  i18n: {\n    locales: ['en', 'fr', 'es', 'pl'],\n    defaultLocale: 'pl',\n  },\n\n  // ...Remaining next config\n})\n```\n\n#### 2. Define your routes\n\nYou can add a `_routes.json`, or a `_routes.yaml`, file in the `pages` folder, and in the every subfolder where you want to define routes.\n\nGiven a folder structure like so, you can add a `_routes.json` in `/pages/` and in `/pages/section/`.\n\n```none\n/pages/\n ├ section/\n | ├ page1.tsx\n | ├ page2.tsx\n | └ _routes.json\n ├ somewhere/\n | └ else.json\n ├ _app.tsx\n ├ about.tsx\n ├ contact.tsx\n └ _routes.json\n```\n\nIn `/pages/section/`, the `_routes.json` file could look like this.\n\n```json\n// `/pages/section/_routes.json`\n{\n  \"/\": {\n    \"es\": \"seccion\" // Folder path in es\n  },\n  \"page1\": {\n    \"default\": \"article\", // Overwrite the default page path (fallback)\n    \"es\": \"articulo\"\n  },\n  \"page2\": \"definition\" // Overwrite the page path for all language\n}\n```\n\nThe `\"/\": { ... }` part define the folder paths, each other section define the paths of a page file in this folder:\n\n- page1 will be accessible at `/seccion/articulo` in `es`, and at `/section/article` in other languages,\n- page2 will be accessible at `/seccion/definition` in `es`, and at `/section/definition` in other languages.\n\nYou don't need a `_routes.json` file in folder where you don't customize anything. If it is empty, then delete it.\nHere, the `/somewhere/` subfolder does not have any `_routes.json` file.\n\nThen, in `/pages/`, the `_routes.json` file could look like this.\n\n```json\n// `/pages/_routes.json`\n{\n  \"/\": {\n    \"pt\": \"blog\" // As we are in the root pages folder, this will add a \"blog\" path prefix for all pages in pt\n  },\n  \"contact\": {\n    \"es\": \"contactar\",\n    \"pt\": \"contatar\"\n  }\n}\n```\n\nIn the root pages folder, the `\"/\": { ... }` part of the root `_routes.json` allows to add a different basePath\nfor each language or only some language, like \"blog\" in `pt` here:\n\n- about will be accessible at `/blog/about` in `pt` and at `/about` in other languages,\n- contact will be accessible at `/blog/contatar` in `pt`, at `/contactar` in `es` and at `/contact` in other languages,\n- page1 will in fact be accessible at `/blog/section/article` in `pt`,\n- page2 will in fact be accessible at `/blog/section/definition` in `pt`.\n\n#### 3. Wrap you `\\_app` component with the `withTranslateRoutes` hoc\n\n```js\n// `/pages/_app.js`\nimport { withTranslateRoutes } from 'next-translate-routes'\nimport { App } from 'next/app'\n\nexport default withTranslateRoutes(App)\n```\n\nOr:\n\n```js\n// `/pages/_app.js`\nimport { withTranslateRoutes } from 'next-translate-routes'\n\nconst App = ({ Component, pageProps }) => {\n  // Custom code...\n\n  return <Component {...pageProps} />\n}\n\nexport default withTranslateRoutes(App)\n```\n\n#### 4. Use `next-translate-routes/link` instead of `next/link`\n\nnext-translate-routes extends Next Link to translate routes automatically: import it from 'next-translate-routes/link' instead of 'next/link' and use as you ever did.\n\n```jsx\nimport Link from 'next-translate-routes/link'\nimport React, { useEffect, useState } from 'react'\n\nconst MyLinks = (props) => {\n  const { locales } = useRouter()\n\n  return (\n    <>\n      <Link href=\"/file/path/to/page\">Current locale</Link>\n      {locales.map((locale) => (\n        <Link\n          href={{ pathname: '/file/path/to/[dynamic]/page', query: { dynamic: props.param, otherQueryParam: 'foo' } }}\n          locale={locale}\n          key={locale}\n        >\n          {locale}\n        </Link>\n      ))}\n    </>\n  )\n}\n```\n\n#### 5. Use `next-translate-routes/router instead` of `next/router` for singleton router (default export)\n\nYou can use `next-translate-routes/router` everywhere instead of `next/router` but it is only necessary for the singleton router (which is rarely used).\n\n```typescript\nimport singletonRouter from 'next-translate-routes/router'\n// Indead of:\nimport singletonRouter from 'next/router'\n```\n\n#### 6. Use a middleware to redirect from urls with the default locale prefix\n\nIf `en` is the default locale for example, you probably will want to:\n\n- either redirect `/en` to `/` and `/en/anywhere` to `/anywhere`,\n- or redirect from `/` to `/en` and `/anywhere` to `/en/anywhere`.\n\nThis is complex: next-translate-routes cannot handle this without creating a looping redirect.\nThe only way to do this seems to be using the middleware, as stated [here](https://github.com/vercel/next.js/discussions/18419#discussioncomment-1561577).\n\n### Advanced usage\n\nCheck the example folder to see some advanced techniques in action.\n\n#### Configuration\n\nNext-translate-routes is configurable by adding a `translateRoutes` key in Next config that accept an object of the following `NTRConfig` type.\n\n```ts\ntype NTRConfig = {\n  debug?: boolean\n  routesDataFileName?: string\n  routesTree?: TRouteBranch<L>\n  pagesDirectory?: string\n}\n```\n\n<details>\n  <summary>See more about TRouteBranch</summary>\n\n> If `i18n.locales` is set to `['en', 'fr']`, then the `TRouteBranch` generic `L` prop would be `'en' | 'fr'`. A non-generic equivalent of `TRouteBranch<'en' | 'fr'>` would be the following.\n>\n> ```ts\n> /** Non generic version of the TRouteBranch type for better readability, where the generi L prop is set to `'en' | 'fr'` */\n> type TRouteBranchEnFr = {\n>   name: string\n>   en: string\n>   fr: string\n>   children: TRouteBranchEnFr[]\n> }\n> ```\n\n</details>\n\n```js\n  translateRoutes: {\n    debug: true,\n    routesDataFileName: 'routesData',\n  }\n```\n\nWhen `debug` is set to true, you will get some logs, both in the server terminal and in the browser console. By default, you will get some logs for each `router.push` and `router.replace`, but not `router.prefetch`. To enable logs for `router.prefetch` too, you can set debug to `withPrefetch`.\n\nIf `routesDataFileName` is defined, to `'routesData'` for example, next-translate-routes will look in the `pages` folder for files named `routesData.json` or `routesData.yaml` instead of the default `_routes.json` or `_routes.yaml`.\n\nIf `routesTree` is defined, next-translate-routes won't parse the `pages` folder and will use the given object as the routes tree. If you uses it, beware of building correctly the routes tree to avoid bugs.\n\nYou can see and edit these while your app is running to debug things, using `__NEXT_TRANSLATE_ROUTES_DATA` in the browser console. For exemple, executing `__NEXT_TRANSLATE_ROUTES_DATA.debug = true` will activate the logs on `router.push` and `router.replace`.\n\n#### Translate/untranslate urls\n\nTwo helpers are exposed to translate/untranslate urls:\n\n- `fileUrlToUrl` transforms a file url into a translated url\n- `urlToFileUrl` transforms a translated url into a file url\n\nBoth of them take 2 arguments: an url and a locale. `fileUrlToUrl` can take an extra option argument to prevent it to throw and return undefined instead if the file url is not found: `{ throwOnError: false }`.\n\n#### Alternate pages (SEO)\n\nYou will probably want to indicate alternate pages for SEO optimization. Here is how you can do that:\n\n```tsx\n  const { pathname, query, locale, locale } = useRouter()\n\n  return (\n    <Head>\n      {locales.map((l) => l !== locale && <link rel=\"alternate\" hrefLang={l} href={fileUrlToUrl({ pathname, query }, l)} />)}\n    </Head>\n  )\n```\n\nYou can do it in the `_app` component if you are sure to do that for all your pages. You can also use a dedicated package, like [next-seo](https://github.com/garmeeh/next-seo).\n\nSee [this article about alternate and canonical pages](https://hreflang.org/use-hreflang-canonical-together/)\n\n#### Sitemap\n\nSee [@JacbSoderblom's suggestion](https://github.com/hozana/next-translate-routes/issues/21#issuecomment-1265056041)\n\n#### Constrained dynamic paths segments\n\n```js\n// `/pages/blog/[id]/_routes.json`\n{\n  \"/\": \":id(\\\\d+)\", // Constrain a dynamic folder segment (to be a number here)\n  \"[slug]\": \":slug(\\\\w+)\", // Constrain a dynamic page segment (to be letters here)\n}\n```\n\nFor a catch all route: `\"[...path]\": \":path*\"`.\n\nYou can use a constrained dynamic path segment in the root of your application too.\n\n```none\n/pages/\n ├ [side]/\n | ├ index.tsx\n | └ _routes.yml\n ├ somewhere.tsx\n └ _app.tsx\n\n```\n\n```yml\n# /pages/[side]/_routes.yml\n---\n\"/\":\n  default: :side(heads|tails) # Important!\n  en: :side(heads|tails)\n  fr: :side(pile|face)\n  es: :side(cara|cruz)\n```\n\n#### Ignoring a path part\n\nThis will ignore the `blog` path segment:\n\n```js\n// `/pages/blog/_routes.json`\n{\n  \"/\": \".\"\n}\n```\n\nIt can be done for some lang only and not others.\n\n```js\n// `/pages/blog/_routes.json`\n{\n  \"/\": {\n    fr: \".\"\n  }\n}\n```\n\n⚠️ Ignoring a path segment can cause troubles with the **redirections**.\n\nEx: given the `/a/[b]/[c]` and `/a/[b]/[c]/d` file paths where `[b]` is ignored and the b param is merged with the c param: `:b-:c`.\n`/a/:b/:c` => `/a/:b-:c` and `/a/:b/:c/d` => `/a/:b-:c/d`\nThen `/a/bb/11` will be redirected to `/a/bb-11` and `/a/bb/11/d` to `/a/bb-11/d` and that is fine.\nBut then `/a/bb-11/d` will match `/a/:b-:c` and be redirected to `/a/bb-11-d` and that is not fine!\n\nTo handle this case, one can add a path-to-regex pattern to the default ignore token: `.(\\\\d+)`, or `.(\\[\\^-\\]+)`, or `.(what|ever)`.\nThis path-to-regex pattern will be added after the segment name in the redirect.\n`/a/:b(\\[\\^-\\]+)/:c` => `/a/:b-:c` and `/a/:b(\\[\\^-\\]+)/:c/d` => `/a/:b-:c/d`\nThen `/a/bb-11/d` will no more match `/a/[b]/[c]` (`/a/:b(\\[\\^-\\]+)/:c`). `#ignorePattern`\n\n⚠️ This is only handled in default paths (i.e. `\"/\": \".(\\\\d+)\"` or `\"/\": { \"default\": \".(\\\\d+)\" }`), not in lang-specific paths.\n\n#### Complex paths segments\n\n```js\n// `/pages/blog/[id]/_routes.json`\n{\n  \"/\": \"article{-:id}?-view\", // Add prefix, optional prefix, suffix\n}\n```\n\nIt is also possible to create a path segment with 2 dynamic parameters. Ex: `/articles/:id{-:slug}?`.  \nFirst, create a path segment for each dynamic parameter: `/articles/[id]/[slug].\nThen:\n\n```js\n// `/articles/[id]/_routes.json`\n{\n  \"/\": \".\", // Ignore the [id] segment\n  \"[slug]\": \":id{-:slug}?\" // Give the 2 params to the 2nd segment\n}\n```\n\n#### Custom route tree\n\nIf you want to avoid seeding `_routes.json` files in your `/pages` folder,\nyou can directly create a routesTree object, and inject it in the next config as follow.\n\n```javascript\n// next.config.js\nconst withTranslateRoutes = require('next-translate-routes')\nconst getRoutesTree = require('./getRoutesTree')\n\nconst routesTree = getRoutesTree()\n\nmodule.exports = withTranslateRoutes({\n  // Next i18n config (mandatory): https://nextjs.org/docs/advanced-features/i18n-routing\n  i18n: {\n    locales: ['en', 'fr', 'es', 'pl'],\n    defaultLocale: 'pl',\n  },\n\n  translateRoutes: {\n    routesTree,\n  },\n\n  // ...Remaining next config\n})\n```\n\n`routesTree` must be of type `TRouteBranch`:\n\n```typescript\ntype TRouteBranch<Locale extends string> = {\n  name: string\n  paths: { default: string } & Partial<Record<Locale, string>>\n  children?: TRouteBranch[]\n}\n```\n\n#### Outside Next\n\nYou might need to mock next-translate-routes outside Next, for example for testing or in [Storybook](https://storybook.js.org/).\n\nFirst, you need to create next-translate-routes data. You can do it using the `createNtrData` helper, but it only works in node environment. It takes the next config as first parameter. The second parameter is optional and allows to use a custom pages folder: if omitted, `createNtrData` will look for you next `pages` folder.\n\n```typescript\nimport { createNtrData } from 'next-translate-routes/plugin`\nimport nextConfig from '../next.config.js'\n\nconst ntrData = createNtrData(\n  nextConfig,\n  path.resolve(process.cwd(), './fixtures/pages'),\n)\n```\n\nThen, if you want to render you app, you need to inject the router context, then (and only then) inject next-translate-routes. You can do it manually, or using `next-tranlate-routes/loader` with Webpack.\n\n##### Manually\n\nYou will have to execute createNtrData in a node script and store the result somewhere that can be imported.\n\n```typescript\n// nextRouterMock.ts\nimport withTranslateRoutes from 'next-translate-routes'\nimport { RouterContext } from 'next/dist/shared/lib/router-context'\nimport ntrData from 'path/to/your/ntrData'\n\n//[...]\n\nconst RouteTranslationsProvider = withTranslateRoutes(ntrData, ({ children }) => <>{children}</>)\n\nconst TranslatedRoutesProvider = ({ children }) => (\n  <RouterContext.Provider value={routerMock}>\n    <RouteTranslationsProvider router={routerMock}>{children}</RouteTranslationsProvider>\n  </RouterContext.Provider>\n)\n\n// [...]\n```\n\nFor Storybook, this piece of code can be used to create a decorator function:\n\n```typescript\nexport const WithNextRouter: DecoratorFn = (Story, context): JSX.Element => (\n  <TranslatedRoutesProvider routerMock={createRouterFromContext(context)}>\n    <Story />\n  </TranslatedRoutesProvider>\n)\n```\n\n##### With `next-translate-routes/loader` for Webpack\n\n`next-translate-routes/loader` allows to create next-translate-routes data at build time. So you can do exactly the same as described in the [Manually](#manually) paragraph above, but you don't need to create and add `ntrData` as an argument to `withTranslateRoutes`.\n\n```typescript\n// nextRouterMock.ts\nimport withTranslateRoutes from 'next-translate-routes'\nimport { RouterContext } from 'next/dist/shared/lib/router-context'\n\n//[...]\n\nconst RouteTranslationsProvider = withTranslateRoutes(({ children }) => <>{children}</>)\n\n// TranslatedRoutesProvider is the same as in the manually paragraph above\n\n// [...]\n```\n\nThen all you have to do is to add this rule in your webpack config:\n\n```js\n// storybook/config/webpack.config.js for exemple\n\nconst { createNtrData } = require('next-translate-routes/plugin')\nconst nextConfig = require('../../next.config') // Your project nextConfig\n\nmodule.exports = ({ config }) => {\n  // [...]\n\n  config.module.rules.push({\n    test: /path\\/to\\/nextRouterMock/, // ⚠️ Warning! This test should only match the file where withTranslateRoutes is used! If you cannot, set the mustMatch option to false.\n    use: {\n      loader: 'next-translate-routes/loader',\n      options: { data: createNtrData(nextConfig) },\n    },\n  })\n\n  return config\n}\n```\n\n> ⚠️ Warning! The rule `test` should only match the file where `withTranslateRoutes` is used! If you cannot, then set the `mustMatch` loader option to `false`.\n\n### Fallback languages\n\nYou can define fallback languages in next-translate-routes config [as you would in i18next](https://www.i18next.com/principles/fallback#fallback-to-different-languages), using `fallbackLng`, that can take either a string (ex: `'fr'`), an array (ex: `['fr', 'en']`), or an object (ex: `{ default: ['en'], 'de-CH': ['fr'] }`), but unlike i18next, `fallbackLng` cannot be a function.\n\n```javascript\n// next.config.js\nconst withTranslateRoutes = require('next-translate-routes')\n\nmodule.exports = withTranslateRoutes({\n  // Next i18n config (mandatory): https://nextjs.org/docs/advanced-features/i18n-routing\n  i18n: {\n    defaultLocale: 'en',\n    locales: ['en', 'fr', 'de', 'de-AT', 'de-DE', 'de-CH'],\n  },\n\n  translateRoutes: {\n    fallbackLng: {\n      default: ['en'],\n      'de-AT': ['de'],\n      'de-DE': ['de'],\n      'de-CH': ['de', 'fr'],\n    },\n  },\n\n  // ...Remaining next config\n})\n```\n\nIt can avoid having `routes.json` files looking like:\n\n```json\n{\n  \"/\": {\n    \"de\": \"produkt\",\n    \"de-AT\": \"produkt\",\n    \"de-DE\": \"produkt\",\n    \"de-CH\": \"produkt\"\n  }\n}\n```\n\n## Known issues\n\n### Middleware with watcher (Next >=12.2.0)\n\nUnfortunately, Next new middleware syntax (stable) has a bug when using a \"matcher\" and rewrites.\nYou can keep track of this issue:\n\n- [in next-translate-routes repo](https://github.com/hozana/next-translate-routes/issues/19)\n- [in next.js repo](https://github.com/vercel/next.js/issues/39531)\n\nSo if you want to use a middleware with Next >= 12.2.0, you need to remove any watcher option and filter from within the middleware using [conditional statements](https://nextjs.org/docs/advanced-features/middleware#conditional-statements).\n\n### Optional catch-all with rewrites\n\n[Another issue in Next.js](https://github.com/vercel/next.js/issues/41624) messed some optional catch all routes when they are rewritten: it has been fixed starting from 13.0.4.\n\n### With @sentry/nextjs\n\n@sentry/nextjs inject a webpack loader that replaces all pages content with a proxy, including \\_app. If it does it before next-translate-routes loader execution, the latter won't be able to do its job.\n\nSo the wrapping order in next.config.js is important!\n\nWorks:\n\n```js\nmodule.exports = withTranslateRoutes(withSentryConfig(nextConfig, sentryWebpackPluginOptions))\n```\n\nDoes NOT work:\n\n```js\nmodule.exports = withSentryConfig(withTranslateRoutes(nextConfig), sentryWebpackPluginOptions)\n```\n\n## How does it work\n\n- Next-translate-routes plugin parses the page folder and builds a routes tree object that contains the path tree and the information in the `_routes.json` files.\n- The plugin then uses this information to build optimized redirects and rewrites, then add them to the next config object.\n- Rewrites take care of displaying the right page for the translates urls, redirects take care of the urls that would give an unwanted access to the pages (and would create duplicated content).\n- The plugin adds a webpack loader for the pages/\\_app file. This loader adds a data object (containing the routes tree object along with other config) as first argument of the `withTranslateRoutes` high order component that wrap the app.\n- `withTranslateRoutes` makes this data available as a global variable, `__NEXT_TRANSLATE_ROUTES_DATA`.\n- The `translateUrl` function uses this data to translate routes.\n- The `next-translate-routes/link` leverages the `translateUrl` function to set the `as` prop of `next/link` to the translated url so that the link is aware of the true url destination (which is then available on hover, or on right-click - copy link for example).\n- The `withTranslateRoutes` enhance the router by overriding the router context, to give translation skills to the router.push (which is used on click on a `next/link`), router.replace, and router.prefetch functions, using the `translateUrl` function too.\n","readmeFilename":"README.md"}