# Web ビルド用の Node.js サーバー設定

> Information about how to set up your Node.js server to serve your Web build.

Node.js サーバー設定ファイルを作成し、Node.js サーバーで Unity Web ビルドを操作できるようにします。

Node.js は、サーバー側で JavaScript コードを実行することができるオープンソースのランタイム環境です。Unity では、Node.js アプリケーションを使用して Unity Web ビルドを提供できます。

Node.js の詳細とインストールおよび使用方法については、[Node.js のドキュメント](https://nodejs.org/en/learn/getting-started/introduction-to-nodejs) を参照してください。

## package.json ファイルの設定##set-up-your-package.json-file

Unity Web で使用する準備ができている package.json ファイルを作成するには、以下を行います。

1. テキストエディターまたは IDE でファイルを作成します。

2. ファイル名を `package.json` にします。

3. Node.js プロジェクトディレクトリにファイルを保存します。

4. ファイルに以下のコードを貼り付けます。

   ```json
   {
     "name": "node_server_example",
     "version": "1.0.0",
     "description": "An example for serving a Unity Web build with Node.js",
     "main": "index.js",
     "dependencies": {
       "express": "^4.19.2"
     }
   }
   ```

これで、`package.json` ファイルを使用する準備ができました。このコードは、`index.js` ファイルをサーバープロジェクトのエントリーポイントとして定義し、プロジェクトが依存するライブラリを定義します。

## index.js ファイルの設定##set-up-your-index.js-file

Unity Web で使用する index.js ファイルを準備するには、以下を行います。

1. テキストエディターまたは IDE でファイルを作成します。

2. ファイル名を `package.json` にします。

3. Node.js プロジェクトディレクトリにファイルを保存します。

4. ファイルに以下のコードを貼り付けます。

   ```javascript
   #!/usr/bin/env node
   const path = require('path');
   const express = require('express');

   // Create express application
   const app = express();

   // Settings
   const hostname = 'localhost';
   const port = 8080;
   const enableCORS = true; 
   const enableWasmMultithreading = true;


   // Serve the current working directory 
   const unityBuildPath = __dirname; // Note: this makes the current working directory visible to all computers over the network.

   app.use((req, res, next) => {
       var path = req.url;

       // Provide COOP, COEP and CORP headers for SharedArrayBuffer
       // multithreading: https://web.dev/coop-coep/
       if (enableWasmMultithreading &&
           (
               path == '/' ||
               path.includes('.js') ||
               path.includes('.html') ||
               path.includes('.htm')
           )
       ) {
           res.set('Cross-Origin-Opener-Policy', 'same-origin');
           res.set('Cross-Origin-Embedder-Policy', 'require-corp');
           res.set('Cross-Origin-Resource-Policy', 'cross-origin');
       }

       // Set CORS headers
       if (enableCORS) {
           res.set('Access-Control-Allow-Origin', '*');
       }    

       // Set content encoding depending on compression
       if (path.endsWith('.br')) {
           res.set('Content-Encoding', 'br');
       } else if (path.endsWith('.gz')) {
           res.set('Content-Encoding', 'gzip');
       }

       // Explicitly set content type. Files can have wrong content type if build uses compression.
       if (path.includes('.wasm')) {
           res.set('Content-Type', 'application/wasm');
       } else if (path.includes('.js')) {
           res.set('Content-Type', 'application/javascript');
       } else if (path.includes('.json')) {
           res.set('Content-Type', 'application/json');
       } else if (
       path.includes('.data') ||
       path.includes('.bundle') ||
       path.endsWith('.unityweb')
       ) {
           res.set('Content-Type', 'application/octet-stream');
       }

       // Ignore cache-control: no-cache 
       // when if-modified-since or if-none-match is set
       // because Unity Loader will cache and revalidate manually
       if (req.headers['cache-control'] == 'no-cache' &&
       (
           req.headers['if-modified-since'] ||
           req.headers['if-none-match']
       )
       ) {       
           delete req.headers['cache-control'];
       }        

       next();
   });

   app.use('/', express.static(unityBuildPath, { immutable: true }));

   const server = app.listen(port, hostname, () => {
       console.log(`Web server serving directory ${unityBuildPath} at http://${hostname}:${port}`);
   });

   server.addListener('error', (error) => {
       console.error(error);
   });

   server.addListener('close', () => {
       console.log('Server stopped.');
       process.exit();
   });
   ```

5. オリジン間リソース共有 (CORS) を使用してビルドをロードする場合 (例えば、異なるウェブサイトに埋め込まれている場合) は、コードの以下の行を `true` に設定します。それ以外の場合は、`false` に設定します。

   ```
   const enableCORS = true; 
   ```

6. マルチスレッドサポートを使用してビルドを作成した場合は、コードの以下の行を `true` に設定します。それ以外の場合は、`false` に設定します。

   ```
   const enableWasmMultithreading = true;
   ```

これで、サーバー設定が Unity Web ビルドで使用できるようになりました。

## 追加リソース##additional-resources

* [圧縮されたビルドとサーバーの設定](/engine/6000.0/manual/platform-specific/webgl/building-distribution/deploying.md)
* [サーバー設定コードサンプル](/engine/6000.0/manual/platform-specific/webgl/building-distribution/server-configuration-code-samples.md)
* [Web ビルド用の IIS サーバー設定](/engine/6000.0/manual/platform-specific/webgl/building-distribution/server-configuration-code-samples/web-server-config-iis.md)
* [Web ビルド用の Apache サーバー設定](/engine/6000.0/manual/platform-specific/webgl/building-distribution/server-configuration-code-samples/web-server-config-apache.md)
* [Web ビルド用の Nginx サーバー設定](/engine/6000.0/manual/platform-specific/webgl/building-distribution/server-configuration-code-samples/web-server-config-nginx.md)
