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

useTranslation errors when used inside a Nitro request hook #31

Open
5 tasks done
GalacticHypernova opened this issue Jul 6, 2024 · 4 comments
Open
5 tasks done
Labels
status: review needed Request for review

Comments

@GalacticHypernova
Copy link

GalacticHypernova commented Jul 6, 2024

Describe the bug

When used inside a Nitro request hook, useTranslation (for server-side translation) errors:
image

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

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.
@GalacticHypernova GalacticHypernova added the status: review needed Request for review label Jul 6, 2024
@GalacticHypernova GalacticHypernova changed the title useTranslation errors when used inside a [Nitro](https://nitro.unjs.io) request hook useTranslation errors when used inside a Nitro request hook Jul 6, 2024
@phillipmohr
Copy link

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);
        }
    }
}

@DavidDeSloovere
Copy link
Contributor

We see the same error in a Nuxt application on Vercel, but only occassionaly.

This is were it throws:

h3/src/index.ts

Line 354 in 3246216

if (event.context.i18n == null) {

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.

@DavidDeSloovere
Copy link
Contributor

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.
image

I might try patching h3/src/index.ts to add logging.

@DavidDeSloovere
Copy link
Contributor

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.

image

Could we force the creation of the i18n object on the context?

This is the patch I applied:
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
status: review needed Request for review
Projects
None yet
Development

No branches or pull requests

3 participants