Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading "Accept-language" header in Next.js to determine user's preferred language

I'm working on a project where I have a Strapi API set up with the internationalization plugin to manage content in multiple languages. This approach allows me to avoid translating content on the front end, which is great.

However, I'm encountering a challenge when it comes to determining the user's preferred language based on the Accept-language header sent with their requests. My front end is built with Next.js, and I'm struggling to create a middleware that can handle this.

Here are the specifics of my situation:

  • I'm using Strapi as the backend for my application.

  • Strapi's internationalization plugin is enabled to manage content in multiple languages.

  • I want to read the Accept-language header sent with each request to determine the user's preferred language.

  • Depending on the user's preferred language, I need to fetch API responses in that language to provide content without client-side translation.

I've attempted to create a middleware in Next.js to handle this, but I'm having trouble getting it to work as expected. Here's what I've tried so far:

import { match } from '@formatjs/intl-localematcher';
import Negotiator from 'negotiator';

export default function middleware(req, res, next) {
  const headers = { 'accept-language': req.headers['accept-language'] || 'en-US,en;q=0.5' };
  const negotiator = new Negotiator({ headers });
  const languages = negotiator.languages();
  const locales = ['en-US', 'nl-NL', 'nl'];
  const defaultLocale = 'en-US';

  // Determine the user's preferred language using the locale matcher.
  req.preferredLanguages = match(languages, locales, defaultLocale);

  // Continue to the next middleware or route handler.
  next();
}

I'm unsure whether I'm implementing the middleware correctly or if there's a better approach to achieving my goal. Could someone please provide guidance on how to correctly read the Accept-language header in Strapi with Next.js and use it to customize API responses based on the user's preferred language?

Any code examples, alternative solutions, or detailed steps would be highly appreciated. Thank you for your assistance!

like image 595
Samuel Avatar asked Oct 31 '25 18:10

Samuel


1 Answers

You can get the headers with: req.headers.get("accept-language")

like image 185
Beto Toro Avatar answered Nov 03 '25 12:11

Beto Toro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!