# node: ロケールの検出とミドルウェア URL: https://generaltranslation.com/ja/docs/node/guides/middleware.mdx --- title: ロケールの検出とミドルウェア description: ユーザーのロケールを検出し、withGT でリクエストごとに設定する方法 --- `gt-node` のすべての翻訳関数は、現在のリクエストがどのロケールを対象にしているかを把握しておく必要があります。[`withGT`](/docs/node/api/with-gt) は、非同期ローカルストレージを使ってこのコンテキストを設定します。リクエストハンドラーをラップすると、それ以降のすべての翻訳呼び出しで正しいロケールが自動的に使われます。 ## `withGT` の仕組み `withGT` はロケール文字列とコールバックを受け取ります。そのコールバック内では、[`getGT()`](/docs/node/api/get-gt)、[`getMessages()`](/docs/node/api/get-messages)、[`getLocale()`](/docs/node/api/get-locale) はすべて、設定したロケールを基準に値を読み取ります。 ```js import { withGT, getLocale } from 'gt-node'; app.use((req, res, next) => { const locale = detectLocale(req); withGT(locale, () => next()); }); ``` `withGT` コンテキスト外で呼び出された翻訳関数は、`defaultLocale` を使用します。リクエスト処理は必ず `withGT` でラップしてください。 ## ロケールの検出方法 ### Accept-Language ヘッダー [`getRequestLocale`](/docs/node/api/get-request-locale) を使って `Accept-Language` ヘッダーを解析し、設定済みのロケールと照合します。 ```js import { getRequestLocale } from 'gt-node'; function detectLocale(req) { return getRequestLocale(req); } ``` `getRequestLocale` は、quality 値、ワイルドカードエントリ、言語とリージョンの照合を自動的に処理します。 ### クッキー ベース ユーザーの言語選択をセッション間で保持します: ```js import cookieParser from 'cookie-parser'; app.use(cookieParser()); function detectLocale(req) { return req.cookies.locale || 'en'; } // 言語設定を保存するエンドポイント app.post('/api/set-language', (req, res) => { res.cookie('locale', req.body.locale, { maxAge: 365 * 24 * 60 * 60 * 1000 }); res.json({ ok: true }); }); ``` ### URL パラメータ URL パスからロケールを抽出します (例: `/es/api/greeting`) : ```js function detectLocale(req) { const segments = req.path.split('/').filter(Boolean); const supported = new Set(['es', 'fr', 'ja', 'de']); if (segments[0] && supported.has(segments[0])) { return segments[0]; } return 'en'; } ``` ### クエリパラメータ `?lang=` というクエリパラメータを使用します: ```js function detectLocale(req) { return req.query.lang || 'en'; } ``` ## 戦略の組み合わせ 実際には、優先順位の高いものから複数の戦略を試していくことになります。 ```js function detectLocale(req) { // 1. 明示的なクエリパラメータ(最優先) if (req.query.lang) return req.query.lang; // 2. クッキー(ユーザーの保存済み設定) if (req.cookies?.locale) return req.cookies.locale; // 3. Accept-Language ヘッダー(ブラウザのデフォルト) const acceptLang = req.headers['accept-language']?.split(',')[0]; if (acceptLang) return acceptLang; // 4. デフォルト return 'en'; } ``` ## Express ミドルウェア Express ミドルウェアのセットアップ全体: ```js title="middleware/locale.js" import { withGT } from 'gt-node'; export function localeMiddleware(req, res, next) { const locale = req.query.lang || req.cookies?.locale || req.headers['accept-language']?.split(',')[0] || 'en'; withGT(locale, () => next()); } ``` ```js title="server.js" import express from 'express'; import cookieParser from 'cookie-parser'; import { initializeGT } from 'gt-node'; import { localeMiddleware } from './middleware/locale.js'; initializeGT({ defaultLocale: 'en', locales: ['en', 'es', 'fr', 'ja'], projectId: process.env.GT_PROJECT_ID, }); const app = express(); app.use(cookieParser()); app.use(localeMiddleware); ``` ## Fastify ミドルウェア Fastify でも、`preHandler` Hook を使って同じパターンを適用できます。 ```js title="server.js" import Fastify from 'fastify'; import cookie from '@fastify/cookie'; import { initializeGT, withGT, getGT } from 'gt-node'; initializeGT({ defaultLocale: 'en', locales: ['en', 'es', 'fr', 'ja'], projectId: process.env.GT_PROJECT_ID, }); const app = Fastify(); await app.register(cookie); app.addHook('preHandler', (req, reply, done) => { const locale = req.query.lang || req.cookies?.locale || req.headers['accept-language']?.split(',')[0] || 'en'; withGT(locale, () => done()); }); app.get('/api/greeting', async (req, reply) => { const gt = await getGT(); return { message: gt('Hello, world!') }; }); app.listen({ port: 3000 }); ``` ## 現在のロケールを確認する `withGT` コンテキスト内であればどこでも [`getLocale()`](/docs/node/api/get-locale) を使って、確定したロケールを取得できます。 ```js import { getLocale } from 'gt-node'; app.get('/api/info', async (req, res) => { const locale = getLocale(); res.json({ currentLocale: locale }); }); ``` ## 次のステップ * [`withGT` API リファレンス](/docs/node/api/with-gt) * [`getLocale` API リファレンス](/docs/node/api/get-locale) * [`getRequestLocale` API リファレンス](/docs/node/api/get-request-locale) * [文字列翻訳のパターン](/docs/node/guides/strings) — コンテンツを翻訳する方法 * [ローカル翻訳ストレージ](/docs/node/guides/local-tx) — アプリに翻訳を含める