'setLocale on the server side with node, koa, and i18next

I'm not able to have setLocale work on the server side with node, koa, and i18next. as i18n library

I've followed this issue (https://github.com/jquense/yup/issues/758) proposed solution but no luck...

I'm setting the locale in a middleware which detects the client accept-language header.

This is the koa middleware which sets the language:


import i18next from "i18next";
import { setLocale } from 'yup';

export default async (ctx, next) => {
    if (ctx.req.method != 'OPTIONS' && ctx.headers['accept-language']) {
        let acceptLanguages = []
        ctx.headers['accept-language'].split(',').forEach(x => acceptLanguages.push(x.substring(0,2)))
        if (acceptLanguages.some(x => x == acceptLanguages[0]) && i18next.language != acceptLanguages[0]) {
            i18next.changeLanguage(acceptLanguages[0])
            buildYupLocale(i18next.t)
        }
    }
    await next()
}

const buildYupLocale = (t) => {
    setLocale({
        // use constant translation keys for messages without values
        mixed: {
            required: t('field_required'),
        },
        // use functions to generate an error object that includes the value from the schema
        string: {
            max: ({ max }) => t('field_too_long', { max }),
        },
    });
}

Any suggestions or examples will be much appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source