getT on API route on Vercel (serverless)
See original GitHub issueFirst: Thanks for this great lib!
I’m using next-translate
@ 1.0.1 and next
@ 10.0.5, and I have trouble to use getT
on my API route.
The following error occurred in production on Vercel, when calling the API:
ERROR TypeError: Cannot read property 'loadLocaleFrom' of undefined
The API is called serverless on Vercel which mean the NodeJS global
didn’t contain the i18nConfig
, which leads to this error message.
I tried to set the config to global inside the API route:
import getT from 'next-translate/getT'
import i18n from '../../i18n.json'
const handler = async (
req,
res,
) => {
global.i18nConfig = i18n
const t = await getT(req.query.__nextLocale, 'api')
const error = t('error')
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ error }))
}
export default handler
The error disappears, but I get only the translation key instead of the translated text.
You can reproduce this on your local machine: Build and start Next and call the API directly without any page load, because the page load will add the config to global.
Any ideas how to resolve this?
Issue Analytics
- State:
- Created 3 years ago
- Reactions:4
- Comments:10 (4 by maintainers)
Thanks to @aralroca and @Fivedark 😃
I was having the exact same issue and after applying the solution above from @Fivedark, everything is working as expected now. For the locale, I’m passing the value to my api function. Here’s my code in case it could help anyone else:
@goellner No, the workaround will need to be added in every api route where you use
getT
.The following patch works for me until this issue is resolved:
and then:
Once
getT
fromnext-translate
works properly, refactoring will be a piece of cake.