ロゴテキスト ロゴ

    Vercelでexpressを動かす

    Vercelでexpressを動かす

    Vercel は

    • nodeのシステムを動かす事が出来る
    • GitHubを使って簡単にプレビュー環境を作れる
    • 簡単な事であれば基本無料で使える

    と様々なメリットがあります。




    Next.jsを動かすならVercel!


    と Next.js のイメージが個人的に強かったのですが、

    よくよく考えると express を動かしてAPIサーバのような事も出来るのではないか?と思い始めました。



    この記事では、Vercelでexpressを動かす方法をご紹介します!


    検証した環境

    1 express 4.18.2
    2 @types/express 4.17.17
    3 ts-node 10.9.1
    4 typescript 5.1.6

    expressが動く環境を作成

    必要なパッケージをインストールします

    $ yarn add express
    $ yarn add -D ts-node @types/express typescript


    TypeScriptの設定を追加

    tsconfig.json
    {
      "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "strict": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true
      }
    }


    node_modules/が作成されるのでgitignoreを追加

    .gitignore
    node_modules/


    expressを起動させるためのファイルを追加

    index.ts
    import express from 'express';
     
    const app = express()
    const port = 8123
     
    app.get('/', (req, res) => {
      res.send('Express + TypeScript Server')
    })
     
    app.listen(port, () => {
      console.log(`[server]: Server is running at http://localhost:${port}`)
    })


    ここまででファイルの構成は以下のようになりました

    $ tree -L 2
     
    .
    ├── README.md
    ├── index.ts
    ├── node_modules
    │   ├── @cspotcode
    │   ├── @jridgewell
    ・・・
    │   ├── vary
    │   └── yn
    ├── package.json
    ├── tsconfig.json
    └── yarn.lock


    expressサーバを起動

    ここまで準備が出来たらサーバを起動してみます!

    $ npx ts-node index.ts
    [server]: Server is running at http://localhost:8123


    localhostにアクセスすると

    expressが起動出来ている事を確認

    無事Expressが起動出来ました!



    Vercelで実行出来るようにする

    Vercelでデプロイ出来るようにGitHubと連携します。


    Frameworkは Other を選択

    FrameworkはOtherを選択


    Next.jsなどではVercelとGitHubを連携する際にBuildの設定などを合わせて行いますが、

    expressを用いる場合は特に意識せずで大丈夫です!



    変わりに vercel.json というvercelの設定ファイルをプロジェクトに配置しそちらでコントロールします。

    vercel.jsonの詳細はこちら

    Configuring Projects with vercel.json | Vercel Docs



    vercel.jsonを追加

    vercel.jsonドキュメントのfunctions の項目を見ると


    A glob pattern that matches the paths of the Serverless Functions you would like to customize:



    カスタマイズしたいServerless Functionsのパスにマッチするグロブパターン(DeepL翻訳)

    と書かれているので

    vercel.json
    {
      "functions": {
        "index.ts": {
          "memory": 1024
        }
      }
    }

    試しにこのように書いてpushしてみます。



    するとエラーが起きます。

    apiディレクトリを指定しないとBuildが失敗する
    The pattern "index.ts" defined in `functions` doesn't 
    match any Serverless Functions inside the `api` directory.

    今回のAPIサーバのようなVercelのServerless Functions機能を使いたい場合は

    api ディレクトリ内に配置する必要があるようです。



    index.ts → api/index.ts

    expressの設定を記載したindex.jsを api/ に移動します

    $ tree -L 2
     
    .
    ├── README.md
    ├── api
    │   └── index.ts
    ├── node_modules
    │   ├── @cspotcode
    │   ├── @jridgewell
    ・・・


    vercel.jsonの指定を変更

    vercel.json
    {
      "functions": {
        "api/index.ts": {
          "memory": 1024
        }
      }
    }


    これでpushすると

    vercelへのデプロイが成功

    Vercelへのデプロイは成功!






    しかし、Vercelに表示されるドメインにアクセスすると404・・😭

    表示されたドメインにアクセスするとNOT FOUND


    /api にアクセスすればいいのかな、と試しても

    /api だとCannot GETになる

    アクセス出来ず。。



    rewritesを設定

    原因が良く分からずドキュメントを色々調べたところ、

    Vercel公式にexpressを動かすための方法の記事がありました!

    How to Deploy an Express.js Application to Vercel



    rewrites の設定が必要そう? 🤔

    というのが分かったため以下のように設定しpush

    vercel.json
    {
      "functions": {
        "api/index.ts": {
          "memory": 1024
        }
      },
      "rewrites": [{ "source": "/(.*)", "destination": "/api" }]
    }


    そしてVercelのドメインにアクセスすると

    vercelドメインでexpressが起動出来ている事を確認出来た

    無事expressで設定した内容が返ってきました!




    プロフィールの背景画像 プロフィール画像
    Yuki Takara
    都内でフリーランスのエンジニアをやってます。フロントとアプリ開発メインに幅広くやってます。