next-translate
next-translate copied to clipboard
get current locale on api route
apparently the example given in the readme isn't valid anymore: https://github.com/vercel/next.js/discussions/21798
It seems a limitation that Next.js has made (no idea why), I see that it doesn't allow to make requests to /en/api/endpoint
either, it has to be /api/endpoint
... Luckily the getT
helper defaults to the defaultLanguage
if it's not defined, but you lose a great functionality... It would be great to understand the reason for this change.
It's not the best solution, but If you save the NEXT_LOCALE
on document.cookie
you can use req.cookies.NEXT_LOCALE
https://nextjs.org/docs/advanced-features/i18n-routing#leveraging-the-next_locale-cookie
I use this as a fallback for when the cookie isn't set:
import { defaultLocale, locales } from '../../i18n';
export default async function handler(req, res) {
const requestPath = new URL(req.headers.referer as string).pathname;
const currentLocale =
req.cookies.NEXT_LOCALE ??
locales.find((locale) => requestPath.startsWith(`/${locale}`)) ??
defaultLocale;
}
For me this does work:
import getT from 'next-translate/getT';
export default async function handler(req, res) {
const NextRequestMetaSymbol = Reflect.ownKeys(req).find(key => key.toString() === 'Symbol(NextRequestMeta)');
const lang = NextRequestMetaSymbol && req[NextRequestMetaSymbol].__NEXT_INIT_QUERY ? req[NextRequestMetaSymbol].__NEXT_INIT_QUERY.__nextLocale : undefined
const t = await getT(lang, 'common')
const address = t('Welcome')
res.status(200).json({ address: address, name: 'John Doe' });
}
@TomFreudenberg 's solution doesn't seem to work for me, req[NextRequestMetaSymbol].__NEXT_INIT_QUERY
is an empty object (though it is present). I see req.query.__nextLocale
is still referred to in the README at https://github.com/vinissimus/next-translate#gett
I did notice on this commit that it seems we can't rely on next's i18n support to provide this at the moment as they say "we don't provide the locale to the API in any way currently".
@skomorokh you are right - same on my site.
I am not sure when this did break with my above info but it does not work anymore.
We are also on the way to move away from this component and going to try https://github.com/Avansai/next-multilingual in case of some nice features as translated path urls and default language rewrites.
Sorry for that Tom
I really hoped that eventually nextjs will incorporate a solution. Counting the number of projects in this space, this seems to be an issue many nextjs users demand.