h3
h3 copied to clipboard
`useTranslation` errors when used inside a Nitro request hook
Describe the bug
When used inside a Nitro request hook, useTranslation (for server-side translation) errors:
Reproduction
nitroApp.hooks.hook("request", async (event) => { const t = await useTranslation(event) })
System Info
------------------------------
- Operating System: Linux
- Node Version: v21.1.0
- Nuxt Version: 3.11.2
- CLI Version: 3.12.0
- Nitro Version: 2.9.6
- Package Manager: [email protected]
- Builder: -
- User Config: nitro, i18n, devtools, runtimeConfig, experimental, vite
- Runtime Modules: @nuxtjs/[email protected]
- Build Modules: -
------------------------------
Used Package Manager
n/a
Additional context
The reproduction provided is extremely minimal as that's all that needs to be done in order to trigger the error. If necessary, I can provide a less minimal reproduction, please do let me know!
Validations
- [X] Follow our Code of Conduct
- [X] Read the Contributing Guide.
- [X] Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- [X] Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
- [X] The provided reproduction is a minimal reproducible of the bug.
Push
I have a similar issue in a Vercel environment. I'm using the i18n Nuxt module. (https://github.com/nuxt-modules/i18n) I have a webhook which makes an API call and sometimes the API is being called when the "server is cold" and then it fails. When it gets triggered again shortly afterwards, it works. Unfortunately I'm also not sure how I can provide a reproduction but I'm just leaving my Vercel logs here so maybe they help someone. There seems to be an issue in the resolveLocale function but I'm not sure what exactly is going on.
Using "@nuxtjs/i18n": "^8.3.1"
Webhook --> calls API --> calls function (handleLeadCreation) --> uses translation function --> fails at resolveLocale
SyntaxError: 22
at createCompileError (file:///var/task/node_modules/@intlify/message-compiler/dist/message-compiler.node.mjs:95:19)
... 8 lines matching cause stack trace ...
at async file:///var/task/chunks/runtime.mjs:3195:19 {
cause: SyntaxError: 22
at createCompileError (file:///var/task/node_modules/@intlify/message-compiler/dist/message-compiler.node.mjs:95:19)
at createCoreError (file:///var/task/node_modules/@intlify/core-base/dist/core-base.mjs:485:12)
at resolveLocale (file:///var/task/node_modules/@intlify/core-base/dist/core-base.mjs:524:23)
at getLocale (file:///var/task/node_modules/@intlify/core-base/dist/core-base.mjs:503:11)
at translate (file:///var/task/node_modules/@intlify/core-base/dist/core-base.mjs:1116:20)
at translate$1 (file:///var/task/node_modules/@intlify/h3/dist/index.mjs:41:28)
at handleLeadCreation (file:///var/task/chunks/routes/api/facebook/index.post.mjs:205:23)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.handler (file:///var/task/chunks/routes/api/facebook/index.post.mjs:340:17)
at async file:///var/task/chunks/runtime.mjs:3195:19 {
code: 22,
domain: undefined
},
statusCode: 500,
fatal: false,
unhandled: false,
statusMessage: undefined,
data: undefined
}
My code
async function handleLeadCreation(payload: WebhookPayload<'leadgen'>, event: H3Event<EventHandlerRequest>) {
try {
const supabase = serverSupabaseServiceRole<Database>(event)
const { sendMail } = useNodeMailer()
const t = await useTranslation(event)
// fails here
const subject = t('email.new_lead.subject', { campaign_name: supabaseLead?.fb_campaign_name })
resolveLocale function from the module
function resolveLocale(locale) {
if (isString(locale)) {
return locale;
}
else {
if (isFunction(locale)) {
if (locale.resolvedOnce && _resolveLocale != null) {
return _resolveLocale;
}
else if (locale.constructor.name === 'Function') {
const resolve = locale();
if (isPromise(resolve)) {
throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
}
return (_resolveLocale = resolve);
}
else {
throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
}
}
else {
throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
}
}
}
We see the same error in a Nuxt application on Vercel, but only occassionaly.
This is were it throws: https://github.com/intlify/h3/blob/3246216730bb5501fe82c4ac9a8c4d5af7ed1557/src/index.ts#L354
event.context.i18n is not always set. Because it works mostly, I think there is no problem with the locale detector or something like that. But it may be that there is an error in onRequest of the middleware and the context is not set correctly.
We are using an advanced localeDetector. The application is only using 1 locale for now. So I will simplify our localeDetector and monitor if the error this pops up.
Even with a simplified locale detector, updates of packages, the error still occurs.
FWIW in Sentry the boottime was 13 minutes before the error. So might not be related to cold start.
I might try patching h3/src/index.ts to add logging.
Some information from the logs.
First line, "config created", show that a static singleton variable on the nitro side has been created. So I believe the process just booted up.
The defineI18nMiddleware ran, because I patched it to log at the end.
But useTranslation can't see the object on the context for some reason.
Could we force the creation of the i18n object on the context?
This is the patch I applied:
This happens frequently for us too. Also on vercel serverless, tried using a retry with delay to make sure it warmed up but does not help. Any ideas? Makes it pretty unusable on the server
I also have this issue
@kazupon sorry for tagging you directly, but what can we do or where can we start looking to get us going in the right direction on this issue?
Sorry for my late reply. I'll take a look soon.
Thank you for your feadback! Would you be able to provide a reproduction 🙏
More info
Why do I need to provide a reproduction?
Reproductions make it possible for us to triage and fix issues quickly with a relatively small team. It helps us discover the source of the problem, and also can reveal assumptions you or we might be making.
What will happen?
If you've provided a reproduction, we'll remove the label and try to reproduce the issue. If we can, we'll mark it as a bug and prioritise it based on its severity and how many people we think it might affect.
If status: need more repro codes or info labeled issues don't receive any
substantial activity (e.g., new comments featuring a reproduction link), we'll
close them. That's not because we don't care! At any point, feel free to comment
with a reproduction and we'll reopen it.
How can I create a reproduction?
We have a couple of templates for starting with a minimal reproduction:
A public GitHub repository is also perfect. 👌
Please ensure that the reproduction is as minimal as possible.
You might also find these other articles interesting and/or helpful:
We need minimal reproduction, because we cannot debug.
We need minimal reproduction, because we cannot debug.
Here's a branch with the code from the OP that triggers the error. This throws locally, every time. https://github.com/DavidDeSloovere/nuxt-i18n-nitro-issue31/blob/in-request-hook/server/plugins/translationInHook.ts
I'm also trying to create something with nuxt-i18n and hosting on Vercel (in that same repro, but main branch). That would throw the same problem we have with useTranslation but in nitro event handler (no plugin/hook). Can't reproduce that now, it was something that failed sometimes, but not always.
--
If anyone has a workaround, I would love to hear it.