如何为next-intl配置异步获取的pathnames
解决next-intl异步获取pathnames不生效的问题
问题原因
createIntlMiddleware 的 pathnames 参数不支持直接传入异步函数——中间件初始化是同步过程,它无法等待Promise解析,只会把你传的async函数当作无效配置,自然不会生效。
解决方案
方案1:构建时静态预获取(适合pathnames不频繁更新)
在项目构建前从管理端拉取pathnames并保存为静态JSON文件,之后在middleware里同步读取:
- 编写预获取脚本
scripts/fetch-pathnames.js:
import fs from 'fs/promises'; import getPathnames from '../path-to-your-getPathnames-function'; async function fetchAndSavePathnames() { const pathnames = await getPathnames(); await fs.writeFile('./pathnames.json', JSON.stringify(pathnames)); } fetchAndSavePathnames();
- 在
package.json的scripts里添加预构建命令:
{ "scripts": { "prebuild": "node scripts/fetch-pathnames.js", "build": "next build" } }
- 在middleware.ts里同步导入使用:
import pathnames from './pathnames.json'; const intlMiddleware = createIntlMiddleware({ locales, defaultLocale: 'en', localeDetection: false, localePrefix: 'always', pathnames });
方案2:请求时动态获取+缓存(适合pathnames频繁更新)
自己封装中间件逻辑,每次请求时先获取(并缓存)pathnames,再创建intl中间件实例处理请求:
import { NextRequest } from 'next/server'; import createIntlMiddleware from 'next-intl/middleware'; import getPathnames from './path-to-your-getPathnames-function'; let cachedPathnames: Record<string, string> | null = null; async function getCachedPathnames() { if (cachedPathnames) return cachedPathnames; cachedPathnames = await getPathnames(); // 设置缓存过期时间(示例:5分钟后清空缓存) setTimeout(() => { cachedPathnames = null; }, 5 * 60 * 1000); return cachedPathnames; } export default async function middleware(request: NextRequest) { const pathnames = await getCachedPathnames(); const intlMiddlewareInstance = createIntlMiddleware({ locales, defaultLocale: 'en', localeDetection: false, localePrefix: 'always', pathnames }); return intlMiddlewareInstance(request); } export const config = { matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'] };
内容的提问来源于stack exchange,提问作者Victor Parenyuk
相关产品推荐
相关产品推荐

