Skip to content

Commit

Permalink
feat: Add localeCookie option for middleware (#1414)
Browse files Browse the repository at this point in the history
  • Loading branch information
amannn authored Oct 10, 2024
1 parent a95bd86 commit 0e984bd
Show file tree
Hide file tree
Showing 8 changed files with 112 additions and 11 deletions.
40 changes: 39 additions & 1 deletion docs/pages/docs/routing/middleware.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const config = {
};
```

## Locale detection
## Locale detection [#locale-detection-overview]

The locale is negotiated based on your [`localePrefix`](/docs/routing#locale-prefix) and [`domains`](/docs/routing#domains) setting. Once a locale is detected, it will be remembered for future requests by being stored in the `NEXT_LOCALE` cookie.

Expand Down Expand Up @@ -122,6 +122,44 @@ In this case, only the locale prefix and a potentially [matching domain](#domain

Note that by setting this option, the middleware will no longer return a `set-cookie` response header, which can be beneficial for CDN caching (see e.g. [the Cloudflare Cache rules for `set-cookie`](https://developers.cloudflare.com/cache/concepts/cache-behavior/#interaction-of-set-cookie-response-header-with-cache)).

### Locale cookie [#locale-cookie]

By default, the middleware will set a cookie called `NEXT_LOCALE` that contains the most recently detected locale. This is used to remember the user's locale preference for future requests (see [locale detection](#locale-detection-overview)).

By default, the cookie will be configured with the following attributes:

1. [**`maxAge`**](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#max-agenumber): This value is set to 1 year so that the preference of the user is kept as long as possible.
2. [**`sameSite`**](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value): This value is set to `lax` so that the cookie can be set when coming from an external site.
3. [**`path`**](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#pathpath-value): This value is not set by default, but will use the value of your [`basePath`](#base-path) if configured.

If you have more specific requirements, you can adjust these settings accordingly:

```tsx filename="middleware.ts"
import createMiddleware from 'next-intl/middleware';
import {routing} from './i18n/routing';

export default createMiddleware(routing, {
// These options will be merged with the defaults
localeCookie: {
// Expire in one day
maxAge: 60 * 60 * 24
}
});
```

… or turn the cookie off entirely:

```tsx filename="middleware.ts"
import createMiddleware from 'next-intl/middleware';
import {routing} from './i18n/routing';

export default createMiddleware(routing, {
localeCookie: false
});
```

Note that the cookie is only set once per detected locale and is not updated on every request.

### Alternate links [#alternate-links]

The middleware automatically sets [the `link` header](https://developers.google.com/search/docs/specialty/international/localized-versions#http) to inform search engines that your content is available in different languages. Note that this automatically integrates with your routing strategy and will generate the correct links based on your configuration.
Expand Down
7 changes: 6 additions & 1 deletion examples/example-app-router-playground/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import createMiddleware from 'next-intl/middleware';
import {routing} from './i18n/routing';

export default createMiddleware(routing);
export default createMiddleware(routing, {
localeCookie: {
// 200 days
maxAge: 200 * 24 * 60 * 60
}
});

export const config = {
matcher: [
Expand Down
5 changes: 5 additions & 0 deletions examples/example-app-router-playground/tests/main.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,11 @@ it('can use `getPahname` to define a canonical link', async ({page}) => {
await expect(getCanonicalPathname()).resolves.toBe('/de/neuigkeiten/3');
});

it('can define custom cookie options', async ({request}) => {
const response = await request.get('/');
expect(response.headers()['set-cookie']).toContain('Max-Age=17280000');
});

it('can use `t.has` in a Server Component', async ({page}) => {
await page.goto('/');
await expect(page.getByTestId('HasTitle')).toHaveText('true');
Expand Down
4 changes: 2 additions & 2 deletions packages/next-intl/.size-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const config: SizeLimitConfig = [
{
name: 'import createMiddleware from \'next-intl/middleware\'',
path: 'dist/production/middleware.js',
limit: '9.63 KB'
limit: '9.675 KB'
},
{
name: 'import * from \'next-intl/routing\'',
Expand All @@ -71,7 +71,7 @@ const config: SizeLimitConfig = [
name: 'import * from \'next-intl\' (react-client, ESM)',
path: 'dist/esm/index.react-client.js',
import: '*',
limit: '14.265 kB'
limit: '14.245 kB'
},
{
name: 'import {NextIntlProvider} from \'next-intl\' (react-client, ESM)',
Expand Down
34 changes: 32 additions & 2 deletions packages/next-intl/src/middleware/config.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,38 @@
import {NextResponse} from 'next/server';

type ResponseCookieOptions = Pick<
NonNullable<Parameters<typeof NextResponse.prototype.cookies.set>['2']>,
| 'maxAge'
| 'domain'
| 'expires'
| 'partitioned'
| 'path'
| 'priority'
| 'sameSite'
| 'secure'
// Not:
// - 'httpOnly' (the client side needs to read the cookie)
// - 'name' (the client side needs to know this as well)
// - 'value' (only the middleware knows this)
>;

export type MiddlewareOptions = {
/** Sets the `Link` response header to notify search engines about content in other languages (defaults to `true`). See https://developers.google.com/search/docs/specialty/international/localized-versions#http */
/**
* Sets the `Link` response header to notify search engines about content in other languages (defaults to `true`). See https://developers.google.com/search/docs/specialty/international/localized-versions#http
* @see https://next-intl-docs.vercel.app/docs/routing/middleware#alternate-links
**/
alternateLinks?: boolean;

/** By setting this to `false`, the cookie as well as the `accept-language` header will no longer be used for locale detection. */
/**
* Can be used to disable the locale cookie or to customize it.
* @see https://next-intl-docs.vercel.app/docs/routing/middleware#locale-cookie
*/
localeCookie?: boolean | ResponseCookieOptions;

/**
* By setting this to `false`, the cookie as well as the `accept-language` header will no longer be used for locale detection.
* @see https://next-intl-docs.vercel.app/docs/routing/middleware#locale-detection
**/
localeDetection?: boolean;
};

Expand Down
18 changes: 18 additions & 0 deletions packages/next-intl/src/middleware/middleware.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,24 @@ describe('prefix-based routing', () => {
});
});

it('can turn off the cookie', () => {
const response = createMiddleware(routing, {localeCookie: false})(
createMockRequest('/')
);
expect(response.cookies.get('NEXT_LOCALE')).toBeUndefined();
});

it('restricts which options of the cookie can be customized', () => {
createMiddleware(routing, {
localeCookie: {
// @ts-expect-error
httpOnly: true,
name: 'custom',
value: 'custom'
}
});
});

it('retains request headers for the default locale', () => {
middleware(
createMockRequest('/', 'en', 'http://localhost:3000', undefined, {
Expand Down
7 changes: 4 additions & 3 deletions packages/next-intl/src/middleware/middleware.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ export default function createMiddleware<
const resolvedOptions = {
alternateLinks: options?.alternateLinks ?? routing.alternateLinks ?? true,
localeDetection:
options?.localeDetection ?? routing?.localeDetection ?? true
options?.localeDetection ?? routing?.localeDetection ?? true,
localeCookie: options?.localeCookie ?? routing?.localeCookie ?? true
};

return function middleware(request: NextRequest) {
Expand Down Expand Up @@ -311,8 +312,8 @@ export default function createMiddleware<
}
}

if (resolvedOptions.localeDetection) {
syncCookie(request, response, locale);
if (resolvedOptions.localeDetection && resolvedOptions.localeCookie) {
syncCookie(request, response, locale, resolvedOptions.localeCookie);
}

if (
Expand Down
8 changes: 6 additions & 2 deletions packages/next-intl/src/middleware/syncCookie.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,23 @@ import {
COOKIE_MAX_AGE,
COOKIE_SAME_SITE
} from '../shared/constants';
import {MiddlewareOptions} from './config';

export default function syncCookie(
request: NextRequest,
response: NextResponse,
locale: string
locale: string,
localeCookie: MiddlewareOptions['localeCookie']
) {
const hasOutdatedCookie =
request.cookies.get(COOKIE_LOCALE_NAME)?.value !== locale;

if (hasOutdatedCookie) {
response.cookies.set(COOKIE_LOCALE_NAME, locale, {
path: request.nextUrl.basePath || undefined,
sameSite: COOKIE_SAME_SITE,
maxAge: COOKIE_MAX_AGE
maxAge: COOKIE_MAX_AGE,
...(typeof localeCookie === 'object' && localeCookie)
});
}
}

0 comments on commit 0e984bd

Please sign in to comment.