LoginSignup
37
34

More than 5 years have passed since last update.

「Serverlessでwebサイト」っていうと大体「S3にHTMLを置いて、APIでやりとりしよう」という構成の話が出てきますよね。
でもそれだとSPAでは良いのですが、通常のwebサイトのような動的にコンテンツやmetaタグを出したいサイトでは、都度都度S3にHTMLをアップロードしないといけなくなっちゃいます。

ということでLambda + API Gatewayで動的にコンテンツ配信やっちゃいましょう。

Serverless Frameworkでプロジェクトを作る

なにはともかくプロジェクト作りましょう。
以下のコマンドでプロジェクト雛形が作れます。

$ npm install serverless -g
$ serverless create --template aws-nodejs --path sample
$ cd sample

API / Lambdaの設定をする

続いてAPI Gatewayの設定をします。

serverless.yml
functions:
  hello:
    handler: handler.hello
    description: Index Page
    events:
      - http:
          method: get
          path: index
          response:
            headers:
              Content-Type: "'text/html'"
            template: $input.path('$')

Response.headersのContent-Type"'text/html'"に設定することで、API GatewayからHTMLを配信することが可能になります。

LambdaからHTMLを返す

あとはLambdaからHTMLを返せばOKです。

'use strict';

// Your first function handler
module.exports.hello = (event, context, cb) => {
    var renderedPage = renderFullPage( 'Go Serverless v1.0! Your function executed successfully!');
  cb(null, renderedPage );
};

// You can add more handlers here, and reference them in serverless.yml

function renderFullPage(renderedContent) {
  return `<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <div id="container">${renderedContent}</div>
    </body>
</html>`;
}

デプロイ・動作確認

sls deploy
Serverless: Packaging service...
Serverless: Removing old service versions...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading service .zip file to S3...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...

..........
Serverless: Stack update finished...

Service Information
service: serverless-react
stage: dev
region: us-east-1
api keys:
  None
endpoints:
  GET - https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/index
functions:
  serverless-react-dev-hello: arn:aws:lambda:us-east-1:xxxxxxxxxxxx:function:serverless-react-dev-hello

デプロイが成功すれば、endpointsにURLが表示されます。
アクセスすると、このようにHTMLが表示されます。
スクリーンショット 2016-10-15 14.13.32.png

最後に

今回はとりあえずHTML返すだけにしましたが、APIのクエリを動的にしたりReactあたりを使ってSSRしていくとより良い感じになるかなと思います。

37
34
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
37
34