Locale selection
An endpoint supports several localized responses and needs to choose the client’s preferred supported language.
Express.js · Pipe
req.acceptsLanguages() negotiates languages against the request’s Accept-Language header. It returns the best supplied match, false when no candidate is accepted, or all accepted languages when called without arguments.
This request method compares candidate languages with the request’s Accept-Language header. It returns the best matching candidate, false when none matches, or the complete ordered preference list when called without an argument.
req.acceptsLanguages([lang])| Name | Type | Description |
|---|---|---|
lang | String | String[] | undefined | One or more languages to test against the request’s Accept-Language header; omit it to retrieve all accepted languages. |
With a language argument, the first accepted language as a String or false if no supplied language is accepted. Without an argument, an Array of languages from the Accept-Language header.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
const preferred = req.acceptsLanguages('en', 'es');
if (preferred === false) return res.status(406).send('Language not supported');
res.send(`Using ${preferred}`);
});
app.listen(3000);Run the server and send an Accept-Language header such as es,en;q=0.8 to select a supported language.
An endpoint supports several localized responses and needs to choose the client’s preferred supported language.
An application must inspect every language preference supplied by a browser or API client.
A route should reject requests whose language preferences do not match its supported set.
It checks the request’s Accept-Language header against one or more supplied languages and returns the first accepted candidate. If no candidate is accepted, the result is false.
Follow-up: What does calling it without candidates do? It returns all languages from the header as an array, ordered by preference.
The argument may be one language, an array of languages, or undefined. The method returns a matching string, false, or—when omitted—an array of accepted languages.
Follow-up: How should code handle the result safely? Narrow the result by checking for false before treating it as a string or iterating it as an array.
The singular req.acceptsLanguage() name is deprecated and has emitted a warning since Express 4.5.0. The plural req.acceptsLanguages() method is the supported replacement.
Follow-up: Why might this matter during an Express upgrade? Express 5 removes the deprecated singular signature, so plural usage avoids migration breakage.
req.acceptsreq.acceptsCharsetsreq.acceptsEncodingsreq.acceptsTypesreq.acceptsLanguage