Migrating devtooljobs.com from Vercel to bunny.net

Posted by:

For some time now, I’ve been running a side project devtooljobs.com. It started when I was looking for a new role and decided to finally build something fun and useful that had been brewing in my mind for quite some time. In the spirit of learning, I think I ended up creating a Rube Goldberg Machine among job boards. But it’s a project that keeps on giving, and recently I decided to migrate the Next.js part of it from Vercel to bunny.net.

But Vercel makes Next.js deployment so easy, why change?

For one, as you’ll see below, I was using Edge Config for redirects, and it wasn’t really scalable for my use case. I had around 150-200 jobs deleted per day, which meant that many redirect entries per day. I also hit the 64KB limit on the Pro plan fairly quickly. Another thing was per-user pricing. Since there were two users on the project, the cost came out to $40 per month, which dropped roughly twentyfold on bunny.net. And finally, once everything is set up, deployment is just as easy.

In this post, I’ll walk through the original Vercel setup and how the system worked, the steps I took to migrate it, some of the obstacles I ran into (a few of them entirely self-inflicted), and how the architecture looks now.

Previous architecture

Before going into the explanations themselves, I think it’s worth looking at a diagram of the whole system and how the components interact with each other:

Hosting - Vercel

Rendering - Hybrid SSG + ISR (revalidate = 60) + SSR (force-dynamic on /search)

Redirects - Vercel Edge Config (@vercel/edge-config), where middleware checks a key-value store for deleted job slugs and issues 301 redirects to category pages. I explain how those end up in Edge Config in the revalidation section below.

Redirect CRUD - Vercel REST API (https://api.vercel.com/v1/edge-config/{id}/items) called from src/lib/redirects.ts using VERCEL_ACCESS_TOKEN and EDGE_CONFIG_ID.

Vercel speed insights - @vercel/speed-insights component in root layout. This was a nice-to-have from the start, so I don’t feel that bad about dropping it later.

OG images - next/og ImageResponse with export const runtime = "edge" on both job posting and category pages.

Revalidation webhook - POST /api/revalidate validated via x-vercel-revalidation-key header. This API route does a bit more than just revalidation. It receives a webhook and, based on whether it’s an update or unpublish, it:

  • revalidates the page
  • adds a redirect entry to Edge Config if post is unpublished or removes it if it’s re-published
  • sends a new job message to Slack
  • submits the URL to Google’s Indexing API

Note: I don’t use publish because Strapi sends both publish and update on publish, so for one published post it would send a webhook twice.

Static generation - At the time of writing, ~5000 pages pre-rendered at build time using generateStaticParams

Self-referencing fetches - Homepage components and pretty much all content are fetched from their own /api/* routes (e.g. /api/jobs/total-count, /api/jobs/categories-with-top). Vercel resolves these internally during build, which is no longer an option with the new system.

Vercel-specific dependencies

{
  "@vercel/edge-config": "^1.4.3",
  "@vercel/speed-insights": "^1.2.0"
}

Vercel-specific environment variables

  • VERCEL_ACCESS_TOKEN - edge config API auth
  • EDGE_CONFIG_ID - edge config store identifier
  • VERCEL_URL - fallback base URL in the revalidation route

The migration

Next config

I added output: "standalone" for Docker deployment and set staticPageGenerationTimeout: 180.

Setting up redirects

Moving the redirects to a database could theoretically add some latency, but so far it’s looking good. To get the Bunny Database up and running, you can follow this guide.

The first thing I had to do here was replace @vercel/edge-config import with @libsql/client. I also switched to a lazy getDb() pattern because @libsql/client createClient() call was at module scope. During next build, the module gets imported but BUNNY_DB_URL and BUNNY_DB_TOKEN are not set, which causes Cannot read properties of undefined (reading 'replace') crash.

Before:

import { get } from '@vercel/edge-config';
const redirectTo = await get<string>(key);

After:

import { createClient, type Client } from '@libsql/client';

let _db: Client | null = null;
function getDb(): Client {
  if (!_db) {
    _db = createClient({
      url: process.env.BUNNY_DB_URL!,
      authToken: process.env.BUNNY_DB_TOKEN!,
    });
  }
  return _db;
}

const result = await getDb().execute({
  sql: 'SELECT target FROM redirects WHERE key = ?',
  args: [key],
});

From there I had to rewrite all CRUD operations from the Vercel Edge Config REST API to libSQL queries. When I initially set this up, edge config was not allowing me to have / in the key so I would transform / to __ and I decided to leave it as it is.

OG Image generation

All I had to do here is to remove export const runtime = "edge" from:

  • src/app/[category]/opengraph-image.tsx
  • src/app/[category]/[slug]/opengraph-image.tsx

These now run on the default Node.js runtime.

Revalidation

I changed the webhook auth header from x-vercel-revalidation-key to x-revalidate-key and updated the Strapi webhook configuration to send the new header name.

package.json tweaks:

  • Removed: @vercel/edge-config, @vercel/speed-insights
  • Added: @libsql/client

Removing all API routes

This is quite specific to my situation, but I had a number of API routes in Next.js through which I was collecting content from Strapi. Since these wouldn’t be available during the Docker build the way they are on Vercel, I had to change the implementation to fetch data directly from Strapi. To be fair, this somehow completely skipped my mind at first, and I had to learn it the hard way.

Dockerfile

FROM node:20-alpine AS base

FROM base AS deps
WORKDIR /app
RUN corepack enable && corepack prepare pnpm@8.11.0 --activate
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile

FROM base AS builder
WORKDIR /app
RUN corepack enable && corepack prepare pnpm@8.11.0 --activate
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1

ARG NEXT_PUBLIC_STRAPI_URL
ARG NEXT_PUBLIC_SITE_URL
ARG MEILI_URL

RUN --mount=type=secret,id=STRAPI_TOKEN \
    --mount=type=secret,id=MEILI_MASTER_KEY \
    STRAPI_TOKEN=$(cat /run/secrets/STRAPI_TOKEN) \
    MEILI_MASTER_KEY=$(cat /run/secrets/MEILI_MASTER_KEY) \
    pnpm build

FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]

The reason I added ARG declarations in the Dockerfile and passed values via --build-arg was because STRAPI_URL was not available inside the Docker build context. As a result, the Strapi client initialization called STRAPI_URL.replace(...) which threw an undefined.

Another issue was that STRAPI_TOKEN, when passed as a --build-arg, leaked into Docker layer cache and history. Initially, I tried passing it as a plain ARG, but couldn’t get authentication working that way. Eventually, for secrets, I used Docker BuildKit secrets, which are mounted at build time via a RUN --mount=type=secret instruction and are not persisted in the image layers or build history.

GitHub Actions workflow

I created .github/workflows/docker-build.yml for the GitHub Actions workflow that builds and pushes to ghcr.io on every push to main. It uses docker/build-push-action@v6 with GitHub Actions caching, passes non-sensitive env vars as build-args, and sensitive tokens as Docker secrets.

The important stuff:

  • Triggers on push to main and workflow_dispatch
  • Non-sensitive build args sourced from GitHub repository variables (vars.*)
  • Sensitive values sourced from GitHub repository secrets (secrets.*)
  • Tags images with both Git SHA and latest

Environment variables

Build-time variables (passed as Docker build args or secrets and stored in the GitHub repository)

Variable Type Purpose
NEXT_PUBLIC_STRAPI_URL build-arg Strapi CMS URL (inlined into client JS)
NEXT_PUBLIC_SITE_URL build-arg Canonical site URL (inlined into client JS)
MEILI_URL build-arg Meilisearch URL for search index
STRAPI_TOKEN secret Bearer token for Strapi API (used during static page generation)
MEILI_MASTER_KEY secret Meilisearch API key

Runtime (set on the Bunny Magic Containers)

Variable Purpose
STRAPI_URL Strapi URL (also needed at runtime for ISR)
STRAPI_TOKEN Bearer token for Strapi API
NEXT_PUBLIC_SITE_URL Canonical site URL
MEILI_URL Meilisearch URL
MEILI_MASTER_KEY Meilisearch API key
BUNNY_DB_URL Bunny Database libSQL endpoint
BUNNY_DB_TOKEN Bunny Database auth token
REVALIDATE_SECRET Shared secret for ISR webhook
SLACK_CLIENT_ID Slack app client ID
SLACK_CLIENT_SECRET Slack app client secret
GOOGLE_SERVICE_ACCOUNT_JSON Google Indexing API credentials

Side quest to migrate existing redirects to Bunny Database

Schema

CREATE TABLE IF NOT EXISTS redirects (
  key TEXT PRIMARY KEY,
  target TEXT NOT NULL
);

As I mentioned above, Edge Config did not allow storing paths containing / so I replaced / with double underscores. For example, /sales/job-slug becomes sales__job-slug,and the target is /${categorySlug}.

Export from Vercel Edge Config

curl -s "https://api.vercel.com/v1/edge-config/${EDGE_CONFIG_ID}/items" \
  -H "Authorization: Bearer ${VERCEL_ACCESS_TOKEN}" \
  | jq '.' > redirects.json

Import into Bunny Database

This was just a one-off migration script that I used inside the project and removed afterward:

import { createClient } from '@libsql/client';

const db = createClient({
  url: 'libsql://your-bunny-db-url.bunnydb.net',
  authToken: 'access-token',
});

await db.execute(
  'CREATE TABLE IF NOT EXISTS redirects (key TEXT PRIMARY KEY, target TEXT NOT NULL)'
);

const items = JSON.parse(fs.readFileSync('redirects.json', 'utf-8'));
for (const item of items) {
  await db.execute({
    sql: 'INSERT OR REPLACE INTO redirects (key, target) VALUES (?, ?)',
    args: [item.key, item.value],
  });
}

Post-migration architecture

Here’s the new diagram:

New dependencies

{
  "@libsql/client": "^0.14.0"
}

New environment variables

  • BUNNY_DB_URL - Bunny Database libSQL endpoint (runtime)
  • BUNNY_DB_TOKEN - Bunny Database auth token (runtime)

Final thoughts and other minor things

To point a root domain to bunny.net’s pull zone, I moved the DNS from Namecheap to Bunny DNS because it allowed me to use a CNAME record for the root domain.

The SEO in me wasn’t comfortable with having CDN domains available to search engines. Even though it likely wouldn’t cause any real problems, I decided to use an Edge Rule to block traffic to any request URL that starts with that domain.

And finally, given that we now have persistent volumes, I am planning to migrate Strapi, Meili, and Umami to Magic Containers as well.

Comments require cookies. to view and post.