Unverified Commit 5fb56312 authored by Jan Kaifer's avatar Jan Kaifer Committed by GitHub

Create i18n example using app-dir and middleware (#44257)

Co-authored-by: 's avatarVu Van Dung <joulev.vvd@yahoo.com>
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
parent 2c23da07
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
{
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true
}
# Internationalized Routing
Next.js doesn't support internationalized routing in `app` directory out of the box. But you can easily implement it yourself. This example shows how to implement internationalized routing on the Edge.
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) or preview live with [StackBlitz](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/app-dir-i18n-routing)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/app-dir-i18n-routing&project-name=app-dir-i18n-routing&repository-name=app-dir-i18n-routing)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
```bash
npx create-next-app --example app-dir-i18n-routing i18n-app
# or
yarn create next-app --example app-dir-i18n-routing i18n-app
# or
pnpm create next-app --example app-dir-i18n-routing i18n-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
'use client'
import { useState } from 'react'
export default function Counter({
dictionary,
}: {
dictionary: {
increment: string
decrement: string
}
}) {
const [count, setCount] = useState(0)
return (
<p>
This compoment is rendered on client:{' '}
<button onClick={() => setCount((n) => n - 1)}>
{dictionary.decrement}
</button>{' '}
{count}{' '}
<button onClick={() => setCount((n) => n + 1)}>
{dictionary.increment}
</button>
</p>
)
}
'use client'
import { usePathname } from 'next/navigation'
import Link from 'next/link'
import { i18n } from '../../../i18n-config'
export default function LocaleSwitcher() {
const pathName = usePathname()
const redirectedPathName = (locale: string) => {
if (!pathName) return '/'
const segments = pathName.split('/')
segments[1] = locale
return segments.join('/')
}
return (
<div>
<p>Locale switcher:</p>
<ul>
{i18n.locales.map((locale) => {
return (
<li key={locale}>
<Link href={redirectedPathName(locale)}>{locale}</Link>
</li>
)
})}
</ul>
</div>
)
}
export default function Head() {
return (
<>
<title>{`i18n within app directory - Vercel Examples`}</title>
<meta
name="description"
content="How to do i18n in Next.js 13 within app directory"
/>
<link rel="icon" href="/favicon.ico" />
</>
)
}
import { getDictionary } from '../../get-dictionary'
import { Locale } from '../../i18n-config'
import Counter from './components/counter'
import LocaleSwitcher from './components/locale-switcher'
export default async function IndexPage({
params: { lang },
}: {
params: { lang: Locale }
}) {
const dictionary = await getDictionary(lang)
return (
<div>
<LocaleSwitcher />
<p>Current locale: {lang}</p>
<p>
This text is rendered on the server:{' '}
{dictionary['server-component'].welcome}
</p>
<Counter dictionary={dictionary.counter} />
</div>
)
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
{
"server-component": {
"welcome": "Vítejte"
},
"counter": {
"increment": "Přidat",
"decrement": "Ubrat"
}
}
{
"server-component": {
"welcome": "Willkommen"
},
"counter": {
"increment": "Zuwachs",
"decrement": "Dekrementieren"
}
}
{
"server-component": {
"welcome": "Welcome"
},
"counter": {
"increment": "Increment",
"decrement": "Decrement"
}
}
import type { Locale } from './i18n-config'
// We enumerate all dictionaries here for better linting and typescript support
// We also get the defalt import for cleaner types
const dictionaries = {
en: () => import('./dictionaries/en.json').then((module) => module.default),
de: () => import('./dictionaries/de.json').then((module) => module.default),
cs: () => import('./dictionaries/cs.json').then((module) => module.default),
}
export const getDictionary = async (locale: Locale) => dictionaries[locale]()
export const i18n = {
defaultLocale: 'en',
locales: ['en', 'de', 'cs'],
} as const
export type Locale = typeof i18n['locales'][number]
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { i18n } from './i18n-config'
import { match as matchLocale } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
function getLocale(request: NextRequest): string | undefined {
// Negotiator expects plain object so we need to transform headers
const negotiatorHeaders: Record<string, string> = {}
request.headers.forEach((value, key) => (negotiatorHeaders[key] = value))
// Use negotiator and intl-localematcher to get best locale
let languages = new Negotiator({ headers: negotiatorHeaders }).languages()
// @ts-ignore locales are readonly
const locales: string[] = i18n.locales
return matchLocale(languages, locales, i18n.defaultLocale)
}
export function middleware(request: NextRequest) {
// Skip next internal requests
if (request.nextUrl.pathname.startsWith('/_next')) return
// Check if there is any supported locale in the pathname
const pathname = request.nextUrl.pathname
const pathnameIsMissingLocale = i18n.locales.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
)
// Let's redirect if there is no locale
if (pathnameIsMissingLocale) {
const locale = getLocale(request)
return NextResponse.redirect(new URL(`/${locale}/${pathname}`, request.url))
}
}
export const config = {
// We can enable redirect just from root
// matcher: "/"
}
// @ts-check
/**
* @type {import('next').NextConfig}
**/
const nextConfig = {
experimental: {
appDir: true,
},
}
module.exports = nextConfig
{
"private": true,
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@formatjs/intl-localematcher": "0.2.32",
"negotiator": "0.6.3",
"next": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/negotiator": "0.6.1",
"@types/node": "^18.11.5",
"@types/react": "^18.0.23",
"@types/react-dom": "^18.0.7",
"typescript": "^4.8.4"
}
}
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
]
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
"next.config.js",
".next/types/**/*.ts"
],
"exclude": ["node_modules"]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment