Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add support for basePath in middleware and navigation APIs #699

Merged
merged 8 commits into from
Dec 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions docs/pages/docs/routing/middleware.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,26 @@ export const config = {

Note that some third-party providers like [Vercel Analytics](https://vercel.com/analytics) and [umami](https://umami.is/docs/running-on-vercel) typically use internal endpoints that are then rewritten to an external URL (e.g. `/_vercel/insights/view`). Make sure to exclude such requests from your middleware matcher so they aren't accidentally rewritten.

### Base path

The `next-intl` middleware as well as [the navigation APIs](/docs/routing/navigation) will automatically pick up a [`basePath`](https://nextjs.org/docs/app/api-reference/next-config-js/basePath) that you might have configured in your `next.config.js`.

Note however that you should make sure that your [middleware `matcher`](#matcher-config) matches the root of your base path:

```tsx filename="middleware.ts"
// ...

export const config = {
matcher: [
'/' // Make sure the root of your base path is matched

// ... other matcher config
]
};
```

See also [`vercel/next.js#47085`](https://github.com/vercel/next.js/issues/47085).

## Composing other middlewares

By calling `createMiddleware`, you'll receive a function of the following type:
Expand Down
2 changes: 1 addition & 1 deletion packages/next-intl/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@
},
{
"path": "dist/production/middleware.js",
"limit": "5.72 KB"
"limit": "5.8 KB"
}
]
}
26 changes: 18 additions & 8 deletions packages/next-intl/src/middleware/getAlternateLinksHeaderValue.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,13 @@ import {NextRequest} from 'next/server';
import {AllLocales, Pathnames} from '../shared/types';
import {MiddlewareConfigWithDefaults} from './NextIntlMiddlewareConfig';
import {
applyBasePath,
formatTemplatePathname,
getHost,
getNormalizedPathname,
isLocaleSupportedOnDomain
} from './utils';

function getAlternateEntry(url: string, locale: string) {
return `<${url}>; rel="alternate"; hreflang="${locale}"`;
}

/**
* See https://developers.google.com/search/docs/specialty/international/localized-versions
*/
Expand All @@ -29,6 +26,7 @@ export default function getAlternateLinksHeaderValue<
localizedPathnames?: Pathnames<Locales>[string];
}) {
const normalizedUrl = request.nextUrl.clone();

const host = getHost(request.headers);
if (host) {
normalizedUrl.port = '';
Expand All @@ -42,6 +40,15 @@ export default function getAlternateLinksHeaderValue<
config.locales
);

function getAlternateEntry(url: URL, locale: string) {
if (request.nextUrl.basePath) {
url = new URL(url);
url.pathname = applyBasePath(url.pathname, request.nextUrl.basePath);
}

return `<${url.toString()}>; rel="alternate"; hreflang="${locale}"`;
}

function getLocalizedPathname(pathname: string, locale: Locales[number]) {
if (localizedPathnames && typeof localizedPathnames === 'object') {
return formatTemplatePathname(
Expand Down Expand Up @@ -75,7 +82,10 @@ export default function getAlternateLinksHeaderValue<
url = new URL(normalizedUrl);
url.port = '';
url.host = domainConfig.domain;
url.pathname = getLocalizedPathname(url.pathname, locale);

// Important: Use `normalizedUrl` here, as `url` potentially uses
// a `basePath` that automatically gets applied to the pathname
url.pathname = getLocalizedPathname(normalizedUrl.pathname, locale);

if (
locale !== domainConfig.defaultLocale ||
Expand All @@ -84,7 +94,7 @@ export default function getAlternateLinksHeaderValue<
url.pathname = prefixPathname(url.pathname);
}

return getAlternateEntry(url.toString(), locale);
return getAlternateEntry(url, locale);
});
} else {
let pathname: string;
Expand All @@ -100,7 +110,7 @@ export default function getAlternateLinksHeaderValue<
url = new URL(pathname, normalizedUrl);
}

return getAlternateEntry(url.toString(), locale);
return getAlternateEntry(url, locale);
});

// Add x-default entry
Expand All @@ -109,7 +119,7 @@ export default function getAlternateLinksHeaderValue<
getLocalizedPathname(normalizedUrl.pathname, config.defaultLocale),
normalizedUrl
);
links.push(getAlternateEntry(url.toString(), 'x-default'));
links.push(getAlternateEntry(url, 'x-default'));
} else {
// For domain-based routing there is no reasonable x-default
}
Expand Down
39 changes: 30 additions & 9 deletions packages/next-intl/src/middleware/middleware.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import {
getKnownLocaleFromPathname,
getNormalizedPathname,
getPathWithSearch,
isLocaleSupportedOnDomain
isLocaleSupportedOnDomain,
applyBasePath
} from './utils';

const ROOT_URL = '/';
Expand Down Expand Up @@ -66,7 +67,16 @@ export default function createMiddleware<Locales extends AllLocales>(
}

function rewrite(url: string) {
return NextResponse.rewrite(new URL(url, request.url), getResponseInit());
const urlObj = new URL(url, request.url);

if (request.nextUrl.basePath) {
urlObj.pathname = applyBasePath(
urlObj.pathname,
request.nextUrl.basePath
);
}

return NextResponse.rewrite(urlObj, getResponseInit());
}

function redirect(url: string, redirectDomain?: string) {
Expand Down Expand Up @@ -104,6 +114,13 @@ export default function createMiddleware<Locales extends AllLocales>(
urlObj.host = redirectDomain;
}

if (request.nextUrl.basePath) {
urlObj.pathname = applyBasePath(
urlObj.pathname,
request.nextUrl.basePath
);
}

return NextResponse.redirect(urlObj.toString());
}

Expand Down Expand Up @@ -187,19 +204,19 @@ export default function createMiddleware<Locales extends AllLocales>(
);

if (hasLocalePrefix) {
const basePath = getNormalizedPathname(
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed getNormalizedPathname here because it's not necessary (already applied above)

getPathWithSearch(normalizedPathname, request.nextUrl.search),
configWithDefaults.locales
const normalizedPathnameWithSearch = getPathWithSearch(
normalizedPathname,
request.nextUrl.search
);

if (configWithDefaults.localePrefix === 'never') {
response = redirect(basePath);
response = redirect(normalizedPathnameWithSearch);
} else if (pathLocale === locale) {
if (
hasMatchedDefaultLocale &&
configWithDefaults.localePrefix === 'as-needed'
) {
response = redirect(basePath);
response = redirect(normalizedPathnameWithSearch);
} else {
if (configWithDefaults.domains) {
const pathDomain = getBestMatchingDomain(
Expand All @@ -209,7 +226,10 @@ export default function createMiddleware<Locales extends AllLocales>(
);

if (domain?.domain !== pathDomain?.domain && !hasUnknownHost) {
response = redirect(basePath, pathDomain?.domain);
response = redirect(
normalizedPathnameWithSearch,
pathDomain?.domain
);
} else {
response = rewrite(internalPathWithSearch);
}
Expand All @@ -218,7 +238,7 @@ export default function createMiddleware<Locales extends AllLocales>(
}
}
} else {
response = redirect(`/${locale}${basePath}`);
response = redirect(`/${locale}${normalizedPathnameWithSearch}`);
}
} else {
if (
Expand All @@ -237,6 +257,7 @@ export default function createMiddleware<Locales extends AllLocales>(

if (hasOutdatedCookie) {
response.cookies.set(COOKIE_LOCALE_NAME, locale, {
path: request.nextUrl.basePath || undefined,
sameSite: 'strict',
maxAge: 31536000 // 1 year
});
Expand Down
22 changes: 15 additions & 7 deletions packages/next-intl/src/middleware/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,9 @@ export function formatTemplatePathname(
if (localePrefix) {
targetPathname = `/${localePrefix}`;
}
targetPathname += formatPathname(targetTemplate, params);

if (targetPathname.endsWith('/')) {
targetPathname = targetPathname.slice(0, -1);
}
targetPathname += formatPathname(targetTemplate, params);
targetPathname = normalizeTrailingSlash(targetPathname);

return targetPathname;
}
Expand All @@ -76,9 +74,8 @@ export function getNormalizedPathname<Locales extends AllLocales>(
const match = pathname.match(`^/(${locales.join('|')})/(.*)`);
let result = match ? '/' + match[2] : pathname;

// Remove trailing slash
if (result.endsWith('/') && result !== '/') {
result = result.slice(0, -1);
if (result !== '/') {
result = normalizeTrailingSlash(result);
}

return result;
Expand Down Expand Up @@ -188,3 +185,14 @@ export function getBestMatchingDomain<Locales extends AllLocales>(

return domainConfig;
}

export function applyBasePath(pathname: string, basePath: string) {
return normalizeTrailingSlash(basePath + pathname);
}

function normalizeTrailingSlash(pathname: string) {
if (pathname.endsWith('/')) {
pathname = pathname.slice(0, -1);
}
return pathname;
}
Loading
Loading