Jakub Kolčář
Jakub Kolčář

Reputation: 304

AWS Serverless how to serve static files from S3 and some other through lambda

I am creating website on AWS using serverless framework. There are 3 parts which I need to serve clients:

  1. endpoints of lambda functions (/getusers)
  2. index.html served throught lambda (I need to insert some constants to it)
  3. static html, js, css, img files, which should be served directly from S3, without going throught costly lambda.

How do I accomplish that? I need all parts of the app to be able to cooperate thus, probably on the same domain. I need index.html and js files to be able to call the lambda endpoints (setted up by API Gateway). Also I would like all files be cached throught CloudFront. I searched google but did not found any example.

Upvotes: 2

Views: 3218

Answers (2)

Daniel Rocco
Daniel Rocco

Reputation: 121

The serverless-apigateway-service-proxy plugin will create API Gateway endpoints backed by services other than Lambda, including S3. Here is a complete example serverless.yml that defines an S3 bucket of public static resources and creates an API method connected to it at path /static/{asset}:

service: s3-static-asset-example

frameworkVersion: '2'

plugins:
  - serverless-apigateway-service-proxy

provider:
  name: aws

custom:
  apiGatewayServiceProxies:
    - s3:
        path: /static/{asset}
        method: get
        action: GetObject
        bucket:
          Ref: StaticAssetBucket
        key:
          pathParam: asset
        cors: true

resources:
  Resources:
    StaticAssetBucket:
      Type: AWS::S3::Bucket
      Properties:
        VersioningConfiguration:
          Status: Enabled
        PublicAccessBlockConfiguration:
          BlockPublicAcls: true
          BlockPublicPolicy: true
          IgnorePublicAcls: true
          RestrictPublicBuckets: true
        BucketEncryption:
          ServerSideEncryptionConfiguration:
            - ServerSideEncryptionByDefault:
                SSEAlgorithm: AES256

  Outputs:
    StaticAssetBucket:
      Value:
        Ref: StaticAssetBucket

A file app.js placed in the bucket

aws s3 cp app.js s3://s3-static-asset-example-dev-staticassetbucket-xxxxxx

is made available at

https://xxxxxx.execute-api.us-east-1.amazonaws.com/dev/static/app.js

Since each service proxy integration has its own path, a Serverless app can include a mix of proxy integrations and normal Lambda method handlers.

Upvotes: 2

Related Questions