QuiiBz / next-international

Type-safe internationalization (i18n) for Next.js
https://next-international.vercel.app
MIT License
1.19k stars 52 forks source link

Internationalization in actions #386

Open user72356 opened 3 months ago

user72356 commented 3 months ago

I use the new-ish action feature of Next.js to process form submissions. I use zod to validate the data object coming from the form and I'm defining the error strings directly in the zod schema, at the top level of the action module:

const formSchema = z.object(
    {
        name: z.string()
            .min(1, { message: t("contactErrorNameRequired") }),

        email: z.string()
            .min(1, { message: t("contactErrorEmailRequired") })
            .email({ message: t("contactErrorEmailFormat") })
    });

I'm trying to internationalize the error messages but it's not working.

At the top of the action before the zod stuff I'm instantiating t() like so: const t = await getI18n(); but it's not working because apparently await isn't (yet) working at the top level of actions modules when the action is called from a client component (See https://github.com/vercel/next.js/issues/54282)

This bug report has a workaround which appears to get past the error (call an empty action from a server component such as the layout), but then I get another error coming from the t() instantiation again:

Error: Could not find locale while pre-rendering page, make sure you called `setStaticParamsLocale` at the top of your pages

I didn't fully understand the documentation, apparently I have to call setStaticParamsLocale("en"); at the top of my action? That doesn't seem to help. Also try calling it in the server layout component and got the same error.

I would love to see an example of next-international used at the top level of an action module... The obvious use-case here is creating a zod schema with international error handling.

Thanks!

matmkian commented 2 months ago

I got the exact same need, any help appreciated :-)