// OK: await-ing a Promise before sending an HTTP responseawaitPromise.resolve();// WRONG: HTTP functions should send an// HTTP response instead of returning.returnPromise.resolve();// HTTP functions should signal termination by returning an HTTP response.// This should not be done until all background tasks are complete.res.send(200);res.end();// WRONG: this may not execute since an// HTTP response has already been sent.returnPromise.resolve();
ミドルウェアを使用して HTTP リクエストを処理する
Node.js HTTP Cloud Run functions では、HTTP リクエストを単純にするために、ExpressJS との互換性がある request および response オブジェクトが提供されます。Cloud Run functions ではリクエスト本文が自動的に読み取られるため、常にメディアタイプから独立したリクエスト本文を受け取ります。つまり、HTTP リクエストはコードの実行時までに完全に読み取られているものと想定されています。ExpressJS アプリをネストする際は、この点に注意する必要があります。特に、リクエスト本文が読み取られていないと想定しているミドルウェアは、想定どおりに動作しない可能性があります。
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["わかりにくい","hardToUnderstand","thumb-down"],["情報またはサンプルコードが不正確","incorrectInformationOrSampleCode","thumb-down"],["必要な情報 / サンプルがない","missingTheInformationSamplesINeed","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 2025-09-03 UTC。"],[[["\u003cp\u003eCloud Run functions use Node.js runtimes, which include the operating system, add-on packages, language support, and the Functions Framework library.\u003c/p\u003e\n"],["\u003cp\u003eYou can select different versions of Node.js runtimes for your Cloud Run function, with Node.js 18 and newer versions using an execution environment based on Ubuntu 22.04.\u003c/p\u003e\n"],["\u003cp\u003eDependencies for Cloud Run functions are specified in a \u003ccode\u003epackage.json\u003c/code\u003e file, and the Node.js runtime can execute \u003ccode\u003enpm run build\u003c/code\u003e by default, unless a \u003ccode\u003egcp-build\u003c/code\u003e script is defined or scripts are disabled.\u003c/p\u003e\n"],["\u003cp\u003eAsynchronous tasks in Cloud Run functions must be explicitly signaled as complete to the runtime to avoid premature termination, or risk continuing to run until they timeout.\u003c/p\u003e\n"],["\u003cp\u003eES modules (ESM) can be used in Node.js Cloud Run functions by declaring \u003ccode\u003e"type": "module"\u003c/code\u003e in the \u003ccode\u003epackage.json\u003c/code\u003e file, allowing the use of \u003ccode\u003eimport\u003c/code\u003e and \u003ccode\u003eexport\u003c/code\u003e statements.\u003c/p\u003e\n"]]],[],null,["# The Node.js Runtime\n===================\n\nYour Cloud Run function runs in an environment consisting of an operating\nsystem version plus add-on packages, language support, and the Functions\nFramework library that supports and invokes your function. This environment is\nidentified by the language version, and is known as the runtime.\n\nFor information about runtimes in general, and to learn which Ubuntu version\neach Node.js runtime uses, see the [Cloud Run functions execution environment](/static/functions/1stgendocs/concepts/execution-environment#node.js).\n\nTo start building and deploying Cloud Run functions with Node.js, see the\n[Quickstart](/functions/1stgendocs/create-deploy-gcloud-1st-gen).\n\nTo build and test your functions on your local system, see\n[Run Functions with Functions Framework](/functions/1stgendocs/running/function-frameworks).\n\nSelect the runtime\n------------------\n\nCloud Run functions supports several versions of Node.js, listed on the\n[Runtime support](/static/functions/1stgendocs/runtime-support#node.js) page. You can select\nthe preferred Node.js runtime for your function during deployment:\n\n- See [Deploy a Cloud Run function](/functions/1stgendocs/deploy#basics)\n for details on deploying from the Google Cloud CLI.\n\n- See the [Google Cloud console quickstart](/functions/1stgendocs/console-quickstart-1st-gen) for details on\n deploying from the Google Cloud console.\n\nExecution environment\n---------------------\n\nThe execution environment includes the runtime, the operating system, packages,\nand a library that invokes your function.\n\nNode.js 18 and newer versions use an execution environment based on\nUbuntu 22.04. Versions earlier than Node.js 18 are based on\nUbuntu 18.04. See\n[Cloud Run functions execution environment](/functions/1stgendocs/concepts/execution-environment#runtimes)\nfor more information.\n\nThe library that invokes your function is the\n[Node.js Functions Framework](/functions/1stgendocs/functions-framework).\n\nSource code structure\n---------------------\n\nIn order for Cloud Run functions to find your function's definition, each\nruntime has certain structuring requirements for your source code. See\n[Writing Cloud Run functions](/functions/1stgendocs/writing#structuring_source_code)\nfor more information.\n\nSpecify dependencies\n--------------------\n\nYou can specify dependencies for your functions by listing them in a\n`package.json` file. For more information, see\n[Specifying dependencies in Node.js](/functions/1stgendocs/writing/specifying-dependencies-nodejs).\n\nNPM build script\n----------------\n\nBy default, the Node.js runtime executes `npm run build` if a `build` script\nis detected in `package.json`. If you require additional control over your build\nsteps before starting your application, you can provide a [custom build step](/docs/buildpacks/nodejs#executing_custom_build_steps_during_deployment)\nby adding a `gcp-build` script to your `package.json` file.\n\nYou can prevent your build from running the `npm run build` script by either:\n\n- Adding a `gcp-build` script with an empty value in your `package.json` file: `\"gcp-build\":\"\"`.\n\n- Setting the build environment variable `GOOGLE_NODE_RUN_SCRIPTS` to the empty string to prevent all scripts from running.\n\nAsynchronous function completion\n--------------------------------\n\nWhen working with asynchronous tasks that involve callbacks or `Promise`\nobjects, you must explicitly inform the runtime that your function has finished\nexecuting these tasks. You can do this in several different ways, as shown in\nthe following samples. The key is that your code must wait for the\nasynchronous task or `Promise` to complete before returning; otherwise the\nasynchronous component of your function may be terminated before it completes.\n\n### Event-driven functions\n\n**Implicit return** \n\n exports.implicitlyReturning = async (event, context) =\u003e {\n return await asyncFunctionThatReturnsAPromise();\n };\n\n**Explicit return** \n\n exports.explicitlyReturning = function (event, context) {\n return asyncFunctionThatReturnsAPromise();\n };\n\n### HTTP functions\n\n### Node.js\n\n // OK: await-ing a Promise before sending an HTTP response\n await Promise.resolve();\n\n // WRONG: HTTP functions should send an\n // HTTP response instead of returning.\n return Promise.resolve();\n\n // HTTP functions should signal termination by returning an HTTP response.\n // This should not be done until all background tasks are complete.\n res.send(200);\n res.end();\n\n // WRONG: this may not execute since an\n // HTTP response has already been sent.\n return Promise.resolve();\n\n| **Warning:** failure to properly signal your function's termination may cause your function to either terminate early, or keep running until its timeout is reached. See the [Troubleshooting guide](/functions/docs/troubleshooting#unexpected-stops) for more information.\n\nUse middleware to handle HTTP requests\n--------------------------------------\n\nNode.js HTTP Cloud Run functions provide `request` and `response` objects\nthat are compatible with\n[ExpressJS](https://expressjs.com/en/4x/api.html)\nto make consuming HTTP requests simple. Cloud Run functions automatically reads the\nrequest body, so you will always receive the body of a request independent of\nthe media type. This means that HTTP requests should be considered to have\nbeen fully read by the time your code is executed. The nesting of ExpressJS\napps should be used with this caveat---specifically, middleware that expects the\nbody of a request to be unread might not behave as expected.\n\nUse ES Modules\n--------------\n\nECMAScript modules (ES modules or ESM) are a TC39 standard, unflagged feature\nin Node version 14+ for loading JavaScript modules. Unlike CommonJS, ESM\nprovides an asynchronous API for loading modules. It also provides a popular\nsyntax improvement with `import` and `export` statements that can be used within\na Cloud Run function (instead of `require` statements).\n\nTo use ESM within a Cloud Run function, you must declare `\"type\": \"module\"` within\nyour `package.json`. \n\n {\n ...\n \"type\": \"module\",\n ...\n }\n\nThen you can use `import` and `export` statements.\n| **Note:** Learn more about using [ES modules](https://github.com/GoogleCloudPlatform/functions-framework-nodejs/blob/main/docs/esm/README.md)."]]