question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

getT on API route on Vercel (serverless)

See original GitHub issue

First: 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:open
  • Created 3 years ago
  • Reactions:4
  • Comments:10 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
guydumaiscommented, Apr 12, 2021

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:

// I18N
import getT from 'next-translate/getT'
import i18n from '../i18n'

const SENDGRID_API = 'https://api.sendgrid.com/v3/mail/send'

const sendEmail = async ({ name, email, message, locale }) => {
  // I18N
  global.i18nConfig = i18n
  const t = await getT(locale, 'contact')

  /* Send to client */
  await fetch(SENDGRID_API, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
        'Accept-Language': `${locale}`
      },
      body: JSON.stringify({
        personalizations: [
          {
            to: [
              {
                email: email
              }
            ],
            subject: t('EmailSubject')
          }
        ],
        from: {
          email: 'noreply@guydumais.digital',
          name: 'Guy Dumais'
        },
        content: [
          {
            type: 'text/html',
            value: `${t('Thank You')} <b><a href='mailto:${email}'>${name}</a></b>,<br/><br/>${t('EmailConfirmation')}<br/><br/>Message:<br/>${message}`
          }
        ]
      })
  })
    
}

export default sendEmail
2reactions
jzzfscommented, Jul 29, 2021

@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:

// monkey-patches.ts
import getT from "next-translate/getT";
import i18n from "../i18n";

export const ensureAvailabilityOfGetT = () => {
  global.i18nConfig = i18n;
  return getT;
};

and then:

// some-api-route.ts

import { ensureAvailabilityOfGetT } from "../../../utils/api/utils/monkey-patches";

const parsedLocale = "..."; 

const getT = ensureAvailabilityOfGetT();
const errorsT = await getT(parsedLocale, "errors");
const feedbackT = await getT(parsedLocale, "feedback");

// do your thing

Once getT from next-translate works properly, refactoring will be a piece of cake.

Read more comments on GitHub >

github_iconTop Results From Across the Web

API routes with Vercel Serverless Functions and NextJS
First being Vercel's Serverless Functions and second being Next.js API routes. Both allow you to serve API endpoints .
Read more >
getT on API route on Vercel (serverless) · Issue #484 - GitHub
The API is called serverless on Vercel which mean the NodeJS global didn't contain the i18nConfig , which leads to this error message....
Read more >
Deploying with Custom Serverless Next.js Routing - Vercel
Next.js offers developers a built-in routing system that allows you to link to other pages whilst also giving those pages a custom URL....
Read more >
How do I get the raw body of a Serverless Function? - Vercel
You can use Vercel Serverless Functions to recieve webhooks from third-party services like Stripe. Certain providers require access to the raw body inside ......
Read more >
Serverless Functions – Vercel Docs
To deploy a Next.js API Route as a Serverless Function, you can create a new file inside the /pages/api folder. The following example...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found