Skip to main content

JavaScript & Assets

Assets require a Custom Domain Name to link properly when using API Gateway. For Function URLs, the work out of the box. Both API Gateway and Function URLs can benefit from a CloudFront CDN to cache /assets and avoid hitting your backend function on each request.

Serving Static Assets

Our Quick Start cookiecutter project leverages Rails' built in ability to serve static assets. We do this by setting this environment variable in your Dockerfile.

Dockerfile
ENV RAILS_SERVE_STATIC_FILES=1

We also add this configuration to your config/environments/production.rb file. In this case we are setting the cache control to 30 days, which you can change. The X-Lamby-Base64 header signals to the Lamby rack adapter that the content requires base64 binary encoding.

config/environments/production.rb
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{30.days.seconds.to_i}",
'X-Lamby-Base64' => '1'
}

Adding CloudFront

CloudFront is an amazing CDN and is pretty easy to setup with Rails. Simply point CloudFront to your Rails app and allow the origin to set the cache headers. Because we set the public_file_server headers above, everything should work out perfectly. Assuming you have setup a Custom Domain Name via CloudFront, here is how to setup an behavior for your /assets path. From your CloudFront distribution

  • Click the "Behaviors" tab
  • Click "Create Behavior" button
  • Path Pattern: /assets/*
  • Select your API Gateway or Function URL origin.
  • Compress objects automatically: Yes
  • Viewer protocol policy: Redirect HTTP to HTTPS
  • Allowed HTTP Methods: GET, HEAD
  • Restrict viewer access: No
  • 🔘 Cache policy and origin request policy (recommended)
    • Cache policy: CachingOptimized
    • Origin request policy: None

JavaScript Ready

Our Quick Start cookiecutter project is ready to hit the ground running with all the latest Rails defaults for JavaScript & CSS development. We do this by adding Node.js to the development container which is also used to build your production image. See our How Lamby Works guide for details.

For example, we can add the TailwindCSS Rails gem, run the ./bin/rails tailwindcss:install command, and edit the temporary starter index page like so. Once redeployed, we should see our Hello TailwindCSS page working correctly.

Gemfile
gem 'tailwindcss-rails'
app/views/application/index.html.erb
<h1 class="
text-center
text-9xl
text-blue-400
mt-5
">Hello TailwindCSS</h1>
TailwindCSS on Rails on LambdaTailwindCSS on Rails on Lambda