Learn Remix · 13/13

Going Live: Deployment & Architecture

9 min read

Going Live: Deployment & Architecture 🚀

So, you've built a fantastic Remix application. The components are sparkling, the loaders are loading, and the actions are... acting. Now it's time to unleash your creation upon the world! This guide will walk you through the final frontier: deploying your app and understanding the architecture that makes it all possible.


1. Understanding Remix Adapters: Node, Edge, and Serverless

The What and The Why

Before we dive in, let's address a fundamental question: what in the world is a Remix adapter, and why should you care?

At its core, Remix is not an HTTP server itself. Instead, it's a handler that can plug into an existing server. Think of it like a universal remote for your television. The remote (Remix) knows what it wants to do (change the channel, adjust the volume), but it needs a specific adapter to communicate with your particular brand of TV (the server environment).

This is where Remix adapters come in. They are the crucial bridge between your Remix application and the specific JavaScript runtime environment where it will be deployed. This brilliant design choice makes Remix incredibly flexible, allowing you to deploy your application to a wide variety of platforms.

The Problem Solved

Imagine a world without adapters. You'd have to write custom code to make your Remix app work with every single deployment target. Want to deploy to Vercel? Write some Vercel-specific code. Moving to Netlify? Time to rewrite that deployment logic. It would be a tedious and error-prone process.

Adapters solve this by abstracting away the differences between deployment environments. You write your Remix code once, and the adapter handles the translation to the specific runtime, whether it's Node.js, a serverless function, or an edge worker.

The Three Flavors of Deployment

Let's break down the main types of deployment environments and their corresponding adapters:

a. Node.js: The Traditional Powerhouse servidores

  • What it is: This is your classic, long-running server environment. Think of a dedicated restaurant kitchen that's always open and ready to cook. You have full control over the environment, which is great for complex applications.
  • When to use it:
    • You need to perform long-running tasks.
    • You want maximum control over your server environment.
    • You're migrating an existing Node.js application.
  • Popular Adapters:
    • @remix-run/express: For deploying with the popular Express.js framework.
    • @remix-run/node: A more general adapter for Node.js environments.
  • Example (server.js with Express):
    javascript
    import { createRequestHandler } from "@remix-run/express";
    import express from "express";
    
    const app = express();
    
    app.all(
      "*",
      createRequestHandler({
        // getLoadContext is a function that returns the context for your loaders
        getLoadContext(req, res) {
          // This is where you can add things to your context
          return {};
        },
      })
    );
    
    const port = process.env.PORT || 3000;
    app.listen(port, () => {
      console.log(`Express server listening on port ${port}`);
    });

b. Serverless: Pay-as-you-go Functions 🚀

  • What it is: Instead of a constantly running server, your code is executed in stateless functions that spin up on demand to handle requests. It's like a food truck that only fires up the grill when a customer orders a burger. This can be incredibly cost-effective for applications with variable traffic.
  • When to use it:
    • Your application has unpredictable traffic spikes.
    • You want to minimize infrastructure management.
    • You're building a "Jamstack" style application.
  • Popular Adapters:
    • @vercel/remix: The official adapter for deploying to Vercel.
    • @netlify/remix-adapter: For deploying to Netlify's serverless functions.
    • @remix-run/architect: For deploying to AWS Lambda with Architect.
  • Interesting Fact: The term "serverless" is a bit of a misnomer. There are still servers involved, but you don't have to manage them!

c. The Edge: Blazing Fast and Close to Users ⚡

  • What it is: This is the new kid on the block. Your code is deployed to a global network of servers (a Content Delivery Network or CDN). When a user makes a request, it's handled by the server closest to them, resulting in incredibly low latency. It's like having a mini-food truck on every street corner.
  • When to use it:
    • You need the absolute best performance and lowest latency.
    • Your application has a global user base.
    • You want to deliver dynamic content at the speed of static assets.
  • Popular Adapters:
    • @remix-run/cloudflare-workers: For Cloudflare's powerful edge computing platform.
    • @remix-run/cloudflare-pages: A streamlined option for deploying to Cloudflare Pages.
    • @netlify/remix-edge-adapter: For running your Remix app on Netlify's Edge Functions.

Choosing Your Adapter: It's All About Your Needs

The best adapter for your project depends entirely on your specific requirements. Consider factors like:

  • Performance: Do you need the absolute lowest latency? Go for the Edge.
  • Scalability: Do you expect sudden traffic spikes? Serverless might be your best bet.
  • Control: Do you need fine-grained control over your environment? A traditional Node.js server is the way to go.
  • Cost: Serverless can be very cost-effective for low-traffic applications, while long-running servers have more predictable pricing.

Don't be afraid to experiment! The beauty of Remix adapters is that it's relatively easy to switch between them as your needs evolve.


2. Environment Variables: Managing Secrets Securely in Production 🤫

The What and The Why

As you build your application, you'll inevitably need to store sensitive information, such as API keys, database credentials, and other secrets. Hardcoding these values directly into your code is a huge security risk. Imagine accidentally committing your secret API key to a public GitHub repository – yikes!

This is where environment variables come to the rescue. They are variables that are external to your application and are injected into the environment where your code is running. This allows you to keep your sensitive data separate from your codebase.

The Problem Solved

Environment variables solve two major problems:

  1. Security: They prevent you from exposing sensitive information in your code.
  2. Configuration: They allow you to use different configurations for different environments (development, staging, production) without changing your code.

Using Environment Variables in Remix

Remix has a built-in way to handle environment variables. By default, it uses a .env file in the root of your project to load environment variables into process.env.

Hands-on: Setting up Environment Variables

  1. Create a .env file in the root of your Remix project.

  2. Add your environment variables to the file in the KEY=VALUE format:

    ini
    DATABASE_URL="your-database-url"
    SESSION_SECRET="a-very-secret-key"
  3. Access your environment variables in your server-side code (loaders and actions):

    javascript
    // app/routes/some-route.jsx
    export const loader = async () => {
      const dbUrl = process.env.DATABASE_URL;
      // ... use the dbUrl to connect to your database
      return null;
    };

Client-Side vs. Server-Side Variables

It's crucial to understand that not all environment variables should be exposed to the client-side (the browser). By default, Remix only exposes environment variables that start with REMIX_ to the browser.

  • Server-Side Only (recommended for secrets):

    ini
    DATABASE_URL="your-secret-database-url"
    API_KEY="your-secret-api-key"
  • Exposed to the Client-Side:

    basic
    REMIX_PUBLIC_API_ENDPOINT="https://api.example.com"

Best Practices for Managing Secrets

  • Never commit your .env file to version control. Add it to your .gitignore file.
  • Use a .env.example file to show what variables are needed for the project.
  • For production, use your hosting provider's interface to set environment variables securely. Most platforms like Vercel, Netlify, and Fly.io have a dedicated section for this in their dashboards.

3. Serverless Deployment: Shipping to Vercel or Netlify ☁️

Serverless deployment is a popular choice for Remix applications due to its scalability and ease of use. Let's look at how to deploy to two of the most popular serverless platforms: Vercel and Netlify.

a. Deploying to Vercel

Vercel is a platform that is highly optimized for Next.js, but it also has excellent support for Remix.

Getting Started

  1. Push your code to a Git provider (GitHub, GitLab, Bitbucket).
  2. Sign up for a Vercel account and connect it to your Git provider.
  3. Import your Remix project into Vercel.

Vercel will automatically detect that you are deploying a Remix application and configure the build settings for you. With the @vercel/remix adapter, you don't even need a custom server.js file.

Environment Variables on Vercel

You can add your production environment variables in the "Environment Variables" section of your project settings on the Vercel dashboard.

b. Deploying to Netlify

Netlify is another excellent serverless platform with great support for Remix.

Getting Started

  1. Push your code to a Git provider.
  2. Sign up for a Netlify account and connect it to your Git provider.
  3. Create a new site from Git and select your Remix repository.

Netlify will also auto-detect your Remix project.

Environment Variables on Netlify

You can set your environment variables in the "Build & deploy" -> "Environment" section of your site settings on the Netlify dashboard.


4. Containerized Deployment: Shipping to Long-Running Servers (Fly.io/Docker) 🐳

For applications that require more control or have specific infrastructure needs, containerization with Docker is a fantastic option. Docker allows you to package your application and its dependencies into a standardized unit called a container.

Why Docker?

  • Consistency: Your application runs the same way everywhere, from your local machine to production.
  • Portability: You can deploy your containerized app to any platform that supports Docker.
  • Isolation: Your application and its dependencies are isolated from the underlying system.

Deploying with Fly.io

Fly.io is a platform that makes it incredibly easy to deploy Docker containers globally.

Getting Started with Fly.io

  1. Install the Fly.io CLI (flyctl).
  2. Run fly launch in your Remix project directory. This will:
    • Detect that you have a Remix app.
    • Generate a Dockerfile for you.
    • Create a fly.toml configuration file.
  3. Run fly deploy to deploy your application.

A Look at the Dockerfile

The generated Dockerfile will look something like this:

dockerfile
# Use a Node.js base image
FROM node:18-alpine

# Set the working directory
WORKDIR /app

# Copy package.json and package-lock.json
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy the rest of your app's source code
COPY . .

# Build your Remix app
RUN npm run build

# Expose the port your app will run on
EXPOSE 3000

# The command to start your app
CMD ["npm", "start"]

This Dockerfile provides a set of instructions for building your Docker image. It starts with a base Node.js image, installs your dependencies, builds your Remix app, and specifies the command to run when the container starts.

References for Extra Reading 📚

Challenge

You are tasked with preparing a Remix application for a containerized deployment using Docker. Your goal is to create an efficient, multi-stage Dockerfile that produces a lean production image.

Requirements:

  1. Base Image: Use node:18-alpine for all stages to keep the image size small.
  2. Dependency Stage: Create a stage named deps. This stage should only be responsible for copying package.json and package-lock.json and running npm install. This optimizes Docker's layer caching.
  3. Build Stage: Create a stage named build. This stage should:
    • Copy the node_modules from the deps stage.
    • Copy the entire application source code.
    • Run the Remix build command, npm run build.
  4. Production Stage: Create the final, unnamed stage. This stage will be the production image. It must:
    • Set the NODE_ENV environment variable to production.
    • Copy only the necessary production artifacts from the build stage: the build directory, the public directory, the node_modules directory, and package.json.
    • Expose port 3000.
    • Set the default command to start the application server using npm start.

Write the complete Dockerfile that meets all these requirements.

Expected result

Your submission should be a single, valid Dockerfile. The file must implement a three-stage build process (deps, build, and final production).

A correct solution will contain:

  • FROM node:18-alpine AS deps and subsequent commands to install dependencies.
  • FROM node:18-alpine AS build and subsequent commands to build the application, utilizing artifacts from the deps stage.
  • A final FROM node:18-alpine stage that does not have a name.
  • COPY commands in the final stage that use the --from=build flag to selectively copy build, public, node_modules, and package.json.
  • The instruction ENV NODE_ENV production.
  • The instruction EXPOSE 3000.
  • The final instruction CMD ["npm", "start"].
dockerfile

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.