Skip to main content
Remix is a full-stack, server-side web framework built on modern web standards and designed for fast, resilient, and highly interactive applications. Its core philosophy is to embrace the browser platform, using web APIs wherever possible, and to prioritize user experience through advanced routing, progressive enhancement, and optimized data loading patterns. Remix can only be used on Application Hosting; it cannot be deployed as a static site. We recommend the following best practices to get the best performance when using Remix on Sevalla:
  • Use Remix loaders for efficient, server-side data fetching.
  • Apply appropriate Cache-Control headers in loader responses to maximize CDN performance.
  • Take advantage of Remix’s built-in prefetching to speed up client-side navigation.
  • Use resource routes for API endpoints to simplify data access and caching.

Containerization

Dockerfile

The build for Dockerfiles is fully customizable. The following is an example Dockerfile for Remix:
# Dockerfile for Remix on Sevalla

FROM node:lts-alpine AS deps
WORKDIR /app

COPY package*.json ./
RUN npm ci

FROM node:20-alpine AS builder
WORKDIR /app

COPY --from=deps /app/node_modules ./node_modules
COPY . .

RUN npm run build

FROM node:lts-alpine AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV PORT=3000

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 remixuser

COPY --from=builder --chown=remixuser:nodejs /app/build ./build
COPY --from=builder --chown=remixuser:nodejs /app/package*.json ./
COPY --from=builder --chown=remixuser:nodejs /app/node_modules ./node_modules

USER remixuser

EXPOSE 3000

CMD ["npm", "start"]

Nixpacks

You can customize the Nixpacks build process by defining a nixpacks.toml file and using Nixpacks-specific environment variables. This allows you to fine-tune how dependencies are installed, how your application is built, and which runtime settings are applied. The following is an example nixpacks.toml configuration:
[phases.setup]
nixPkgs = ["nodejs", "npm"]

[phases.install]
cmds = ["npm install --frozen-lockfile"]

[phases.build]
cmds = ["npm run build"]

[start]
cmd = "npm start"
Nixpacks will automatically detect your project’s lock file and select the appropriate package manager during deployment. Additionally, you can specify the Node.js version used during the build by setting the NIXPACKS_NODE_VERSIONenvironment variable.

Buildpacks

If you’re using Buildpacks, you cannot modify the underlying build phases directly or control dependencies. You must rely on the runtime environment that Buildpacks detects. You can influence the build process by adjusting the build script in your package.json. Buildpacks will run whatever command you specify under the build script. For example, the standard command used to compile a Remix application is:
 "build": "remix build"
You can also add additional logic before the build runs, for example:
"build": "echo \"Hi mom!\" && remix build"

CDN

Sevalla provides a premium, Cloudflare-powered CDN for Application Hosting at no additional cost. To get the most out of Sevalla’s CDN when deploying your Remix application, we recommend the following best practices:
  • Enable the CDN for all production applications to ensure global, low-latency delivery.
  • Set appropriate Cache-Control headers on API routes to ensure proper caching behavior.
  • Purge CDN cache after critical deployments to ensure users receive updated content.
  • Rely on Remix’s versioned assets in the build/ directory, which are safe to cache indefinitely.
  • Store static files in the public/ directory, allowing the CDN to serve them efficiently.

Image optimization

// app/routes/_index.tsx
export default function Index() {
  return (
    <img
      src="/images/hero.jpg"
      alt="Hero"
      width={1200}
      height={600}
      loading="lazy"
    />
  );
}

Static assets

Place static assets in the public/ directory:
public/
├── images/
├── fonts/
└── favicon.ico
Remix automatically serves these with optimal caching headers.

Edge caching

Edge caching stores your Sevalla site cache on Cloudflare’s 260+ global data centers, delivering responses from the location nearest to each visitor for faster performance. To maximize the benefits of Sevalla’s Edge Caching for your Remix application, we recommend the following best practices:
  • Set appropriate Cache-Control headers in loaders to control caching behavior.
  • Combine edge caching with the CDN for a complete caching strategy.
  • Use Remix’s useFetcher for client-side revalidation.

Cache-Control

With Sevalla’s Cloudflare integration,Cache-Controlheaders are respected at the edge, giving you precise control over how content is cached and served globally. The following are some common directives you can use in your Remix application:
  • public, s-maxage=3600 - Caches the response on the CDN for 1 hour, improving performance for frequently accessed content.
  • public, max-age=31536000, immutable - Ideal for versioned static assets, allowing them to be cached for up to 1 year with no revalidation.
  • private - Prevents CDN caching and ensures the response is only cached by the end user’s browser, for personalized or sensitive data.
Sevalla does not yet support the stale-while-revalidate Cache-Control directive. To prevent unexpected caching behavior, we recommend not using this directive in your API or asset caching settings.

Cache-Control headers for loaders

// app/routes/api.public-data.ts
import type { LoaderFunctionArgs } from "@remix-run/node";
import { json } from "@remix-run/node";

export async function loader({ request }: LoaderFunctionArgs) {
  const data = await fetchPublicData();

  return json(data, {
    headers: {
      "Cache-Control": "public, max-age=3600, s-maxage=3600",
    },
  });
}

Loader caching with headers

// app/routes/products._index.tsx
import type { LoaderFunctionArgs } from "@remix-run/node";
import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";

export async function loader({ request }: LoaderFunctionArgs) {
  const products = await fetchProducts();

  return json(products, {
    headers: {
      "Cache-Control":
        "public, max-age=60, s-maxage=3600, stale-while-revalidate=86400",
    },
  });
}

export default function Products() {
  const products = useLoaderData<typeof loader>();

  return (
    <div>
      {products.map((product) => (
        <div key={product.id}>{product.name}</div>
      ))}
    </div>
  );
}

Resource routes with caching

// app/routes/api.products.ts
import type { LoaderFunctionArgs } from "@remix-run/node";
import { json } from "@remix-run/node";

export async function loader({ request }: LoaderFunctionArgs) {
  const products = await fetchProducts();

  return json(products, {
    headers: {
      "Cache-Control": "public, s-maxage=3600, stale-while-revalidate=86400",
    },
  });
}

Client-side revalidation

// app/routes/blog.$slug.tsx
import { useFetcher } from "@remix-run/react";
import { useEffect } from "react";

export default function BlogPost() {
  const fetcher = useFetcher();

  useEffect(() => {
    // Revalidate on focus
    const handleFocus = () => {
      fetcher.load(window.location.pathname);
    };

    window.addEventListener("focus", handleFocus);
    return () => window.removeEventListener("focus", handleFocus);
  }, [fetcher]);

  return <article>{/* ... */}</article>;
}

Health checks

Ensure your application remains available during deployments by implementing health checks:
  • Always implement health checks for production applications.
  • Keep checks lightweight; responses should complete in under 1 second.
  • Verify critical dependencies (e.g., databases, Redis) as part of the checks.
  • Return 200 for degraded states to allow deployments to continue smoothly.
  • Return 503 only for critical failures that require pod restarts.
  • Close connections cleanly (e.g., database pools, Redis) to prevent resource leaks.
  • Test deployments in staging with monitoring scripts to validate health checks.

Basic health check

// app/routes/api.health.ts
import type { LoaderFunctionArgs } from "@remix-run/node";
import { json } from "@remix-run/node";

export async function loader({ request }: LoaderFunctionArgs) {
  return json(
    { status: "ok", timestamp: new Date().toISOString() },
    { status: 200 }
  );
}

Graceful shutdown

Remix provides automatic graceful shutdown when using remix-serve, but you can add custom cleanup logic, such as closing database connections, by handling SIGTERM and SIGINT yourself. The example below demonstrates how to shut down a PostgreSQL connection pool during termination:
// app/lib/db.server.ts
import { Pool } from "pg";

export const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 20,
  idleTimeoutMillis: 30000,
});

// Graceful pool shutdown
const gracefulPoolShutdown = async () => {
  console.log("Closing database pool...");
  await pool.end();
  console.log("Database pool closed");
};

process.on("SIGTERM", async () => {
  await gracefulPoolShutdown();
  process.exit(0);
});

process.on("SIGINT", async () => {
  await gracefulPoolShutdown();
  process.exit(0);
});
This pattern ensures active connections are closed cleanly before your application stops, preventing dropped queries or pool corruption.

Multi-tenancy

Sevalla fully supports multi-tenancy. You can build multi-tenant Remix applications using wildcard domains, allowing you to efficiently and securely serve multiple tenants from separate subdomains. Use the following best practices for multi-tenancy on Sevalla with your Remix application:
  • Use wildcard domains to serve subdomain-based tenants (e.g., tenant1.app.com).
  • Add custom domains individually for tenants who have their own domains.
  • Cache tenant data to reduce database queries and improve performance.
  • Validate tenant existence before rendering pages to prevent errors or unauthorized access.
  • Isolate tenant data in the database using separate schemas or a tenant_id column.
  • Leverage free SSL certificates, which are automatically provided for both wildcard and custom domains.

Remix multi-tenant implementation

Extract tenant from subdomain in loader:
// app/routes/_index.tsx
import type { LoaderFunctionArgs } from "@remix-run/node";
import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";

export async function loader({ request }: LoaderFunctionArgs) {
  const url = new URL(request.url);
  const hostname = url.hostname;
  const subdomain = hostname.split(".")[0];

  // Skip for main domain
  if (subdomain === "www" || subdomain === "yourdomain") {
    return json({ tenant: null });
  }

  const tenant = await getTenantData(subdomain);
  return json({ tenant });
}

export default function Index() {
  const { tenant } = useLoaderData<typeof loader>();

  return (
    <div>
      <h1>Welcome to {tenant?.name || "Our Platform"}</h1>
    </div>
  );
}
Tenant-specific data:
// app/lib/tenant.ts
import { pool } from "./db";

export async function getTenantData(tenantId: string) {
  const result = await pool.query(
    "SELECT * FROM tenants WHERE subdomain = $1",
    [tenantId]
  );

  return result.rows[0] || null;
}

Custom domains per tenant

Allow tenants to use their own domains (e.g., customdomain.com → tenant data). Map custom domains to tenants:
// app/lib/tenant.ts
export async function getTenantByDomain(hostname: string) {
  // First, check if this is a custom domain
  const customDomain = await pool.query(
    "SELECT tenant_id FROM custom_domains WHERE domain = $1",
    [hostname]
  );

  if (customDomain.rows.length > 0) {
    const tenantId = customDomain.rows[0].tenant_id;
    return await getTenantById(tenantId);
  }

  // Otherwise, extract from subdomain
  const subdomain = hostname.split(".")[0];
  return await getTenantData(subdomain);
}