TopAppDevelopers.net

A site with useful information for app developers


Fix Cloudflare Pages Time Out When Using SvelteKit with enhanced-img

This is a fix for a pipeline build error caused when you deploy a SvelteKit app that has @sveltejs/enhanced-img to Cloudflare Pages

SvelteKit Cloudflare Pages Cache
blog-post

You just completed your work for the day, commit your code, and find out to your surprise that the Cloudflare Pages pipeline timed out while building your SvelteKit project that uses @sveltejs/enhanced-img

Segmentation fault

Failed: Error while executing user command. Exited with error code: 139

Failed: build command exited with code: 1

Failed: error occurred while running build command

In order to fix this we need to stop running the build pipeline in Cloudflare, and instead move it to Github Actions or a similar service.

1. Turn off automatic Cloudflare deployments.

In Cloudflare Pages go to Settings and then Builds & deployments. Click Configure Production deployments, and disable automatic deployments.

2. Add a Github Action

name: Deploy to Cloudflare Pages

on:
  push:
    branches: [main]

jobs:
  publish:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      deployments: write
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - run: npm ci

      - name: Restore Cached Enhanced Images
        uses: actions/cache/restore@v4
        with:
          path: 'node_modules/.cache/imagetools'
          key: ${{ runner.os }}-enhanced-images-${{ hashFiles('src/lib/images/**/*') }}

      - run: npm run build

      - name: Cache Enhanced Images
        uses: actions/cache/save@v4
        with:
          path: 'node_modules/.cache/imagetools'
          key: ${{ runner.os }}-enhanced-images-${{ hashFiles('src/lib/images/**/*') }}

      - name: Publish to Cloudflare Pages
        uses: cloudflare/pages-action@v1
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: youraccountid
          projectName: yourprojectname
          directory: .svelte-kit/cloudflare
          branch: main

3. Replace Sample Text

Replace youraccountid, yourprojectname with your Cloudflare account id and project name. If your images that are used by @sveltejs/enhanced-img are not located in src/lib/images, you need to replace that with the folder path for your images. If you have more than one images directory you can add them all to hashFiles.

Now push your code, and let the build pipeline run. The first time you run it will take a while. Every time after that will be much faster since you're caching images. If you add, modify, or delete an image it will take as long as the first time since it won't be cached.