# gt-node: General Translation Node.js SDK: リクエストのロケールを検出する URL: https://generaltranslation.com/ja/docs/node/guides/detecting-locale.mdx --- title: リクエストのロケールを検出する description: gt-node で General Translation を使い、各リクエストのロケールを特定して関連付ける方法。 related: links: - /docs/node/guides/translating-strings - /docs/node/guides/configuring - /docs/node/guides/storing-translations --- `gt-node` でのすべての翻訳呼び出しは、現在のリクエストのロケールに基づいて実行されます。ロケールはリクエストから特定し、[`withGT`](/docs/node/reference/functions/with-gt) で関連付けることで、後続のすべての翻訳関数でそのロケールが使われます。 ## `withGT` でロケールを関連付ける [#with-gt] リクエスト処理を `withGT(locale, fn)` でラップします。これにより、リクエストの処理中はそのロケールが保持され、[`getGT`](/docs/node/reference/functions/get-gt)、[`getMessages`](/docs/node/reference/functions/get-messages)、[`tx`](/docs/node/reference/functions/tx)、[`getLocale`](/docs/node/reference/functions/get-locale) はそのロケールを基準に解決されます。 ```ts import { withGT } from 'gt-node'; app.use((req, res, next) => withGT(resolveLocale(req), () => next())); ``` *注: `withGT` スコープ外で翻訳関数またはロケール関数を呼び出すと、開発環境では例外がスローされ、本番環境ではデフォルトロケールにフォールバックします。* ## `Accept-Language` から検出する [#accept-language] [`getRequestLocale`](/docs/node/reference/functions/get-request-locale) を使うと、リクエストの `Accept-Language` ヘッダーから最適な対応ロケールを選び、該当するものがない場合はデフォルトロケールにフォールバックできます。 ```ts import { withGT, getRequestLocale } from 'gt-node'; app.use((req, res, next) => withGT(getRequestLocale(req), () => next())); ``` ## 独自のシグナルを使って検出する [#custom] 明示的なユーザーの選択を尊重するには、ロケールを自分で判定します。たとえば、クッキーやパスセグメントから取得し、取得できない場合は `getRequestLocale` にフォールバックします。取得した結果を `withGT` に渡します。 ```ts function resolveLocale(req) { return req.cookies?.locale || getRequestLocale(req); } app.use((req, res, next) => withGT(resolveLocale(req), () => next())); ``` `withGT` は、渡した値を設定済みの `locales` に照らして解決するため、サポートされていないロケールはデフォルトにフォールバックします。リクエスト内のどこからでも、[`getLocale`](/docs/node/reference/functions/get-locale) を使ってアクティブなロケールを取得できます。 ## Next steps - /docs/node/guides/translating-strings - /docs/node/guides/configuring - /docs/node/guides/storing-translations