Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pagefind Search Not Working with Vercel Adapter in Astro Starlight #2824

Closed
1 task
faiz9068 opened this issue Jan 22, 2025 · 7 comments
Closed
1 task

Pagefind Search Not Working with Vercel Adapter in Astro Starlight #2824

faiz9068 opened this issue Jan 22, 2025 · 7 comments

Comments

@faiz9068
Copy link

What version of starlight are you using?

^0.31.0

What version of astro are you using?

^5.1.1

What package manager are you using?

npm

What operating system are you using?

windows

What browser are you using?

chrome

Describe the Bug

Issue: Pagefind Search Not Working with Vercel Adapter in Astro Starlight

Description

When using Astro Starlight with the Vercel adapter, the built-in search functionality (powered by Pagefind) fails to work in production. The Pagefind route is not properly included in the final Vercel build output, resulting in 404 errors when attempting to use the search feature.

Steps to Reproduce

  1. Create a new Astro project with Starlight
  2. Configure the project with @astrojs/vercel adapter
  3. Add content and build the site
  4. Deploy to Vercel
  5. Attempt to use the search functionality on the deployed site

Current Behavior

  • Search functionality returns 404 errors when attempting to load /pagefind/pagefind.js
  • Specific errors encountered:
    Request Method: GET
    Status Code: 404 Not Found
    Remote Address: 64.29.17.65:443
    Referrer Policy: strict-origin-when-cross-origin
    
  TypeError: Failed to fetch dynamically imported module: https://abc.com/pagefind/pagefind.js
  
  Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'options') 
  at HTMLInputElement.we (ui-core.BS99Zlb7.js:1:59515)
  • Pagefind routes are missing from the final Vercel build output
  • Search index is not accessible in production
  • The error suggests that the Pagefind JavaScript module fails to load, causing a cascade of UI errors

Expected Behavior

  • Pagefind routes should be properly included in the Vercel build output
  • Search functionality should work as expected, similar to local development
  • Search index should be accessible and queryable in production

Environment

astro: ^5.1.1
@astrojs/starlight: ^0.31.0
@astrojs/vercel: ^8.0.1

Possible Related Issues

  • Is there a known limitation with static file handling in the Vercel adapter?
  • Could there be a configuration issue with how Pagefind routes are processed during the build?

Link to Minimal Reproducible Example

as

Participation

  • I am willing to submit a pull request for this issue.
@faiz9068
Copy link
Author

👋 Wanted to share a temporary workaround for this issue that worked for me. This is similar to the sitemap fix from #445.

You can create a custom integration that copies the Pagefind files to the correct Vercel output directory after build:

// pagefind-copier.ts
import type { AstroIntegration } from "astro";
import { promises as fs } from "node:fs";
import * as path from "node:path";

export function pagefindCopier(): AstroIntegration {
  return {
    name: "pagefind-copier",
    hooks: {
      "astro:build:done": async ({ logger }) => {
        const buildLogger = logger.fork("pagefind-copier");
        buildLogger.info("Copying pagefind files from dist to Vercel output");

        try {
          const distPath = "./dist/client";
          const vercelPath = "./.vercel/output/static";
          const pagefindSourceDir = path.join(distPath, "pagefind");
          const pagefindDestDir = path.join(vercelPath, "pagefind");

          await fs.mkdir(vercelPath, { recursive: true });
          await fs.mkdir(pagefindDestDir, { recursive: true });

          async function copyDir(src: string, dest: string) {
            const entries = await fs.readdir(src, { withFileTypes: true });
            
            for (const entry of entries) {
              const srcPath = path.join(src, entry.name);
              const destPath = path.join(dest, entry.name);
              
              if (entry.isDirectory()) {
                await fs.mkdir(destPath, { recursive: true });
                await copyDir(srcPath, destPath);
              } else {
                await fs.copyFile(srcPath, destPath);
              }
            }
          }

          try {
            await fs.access(pagefindSourceDir);
          } catch (error) {
            buildLogger.warn("No pagefind directory found in dist");
            return;
          }

          await copyDir(pagefindSourceDir, pagefindDestDir);
          buildLogger.info("Successfully copied pagefind directory to Vercel output");

        } catch (error) {
          if (error instanceof Error) {
            buildLogger.error(`Error copying pagefind files: ${error.message}`);
          } else {
            buildLogger.error("An unknown error occurred while copying pagefind files");
          }
          throw error;
        }
      },
    },
  };
}

Then add it to your Astro config as the last integration:

import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
import vercel from '@astrojs/vercel/static';
import { pagefindCopier } from './pagefind-copier';

export default defineConfig({
  integrations: [
    starlight({ /* ... */ }),
    vercel(),
    // Must be last in the list
    pagefindCopier()
  ],
});

⚠️ Important notes:

  1. The integration must be placed last in the integrations list
  2. This is a temporary workaround until the issue is fixed in the Vercel adapter
  3. You may want to remove this once the issue is fixed

This workaround ensures the Pagefind files are copied to the correct location in Vercel's output directory, fixing the 404 errors for /pagefind/pagefind.js and related files.

@delucis
Copy link
Member

delucis commented Jan 22, 2025

Hi @faiz9068! I think this should be fixed by withastro/adapters#508 which was just released in @astrojs/vercel v8.0.3.

Could you try updating (you can run npx @astrojs/upgrade) and seeing if that fixes this too?

@bgentry
Copy link

bgentry commented Jan 23, 2025

@delucis I can confirm that at least for me, @astrojs/vercel v8.0.3 does not fix this issue and the pagefindCopier workaround is still required. At least that workaround takes care of the issue for me, thank you so much @faiz9068 🙏

@delucis
Copy link
Member

delucis commented Jan 23, 2025

I can confirm that at least for me, @astrojs/vercel v8.0.3 does not fix this issue

Thanks for testing — we’ll take a look

@delucis
Copy link
Member

delucis commented Jan 23, 2025

OK, we diagnosed the issue and released a fix. I just tested and upgrading to @astrojs/vercel v8.0.4 should actually work!

@delucis delucis closed this as completed Jan 23, 2025
@bgentry
Copy link

bgentry commented Jan 23, 2025

@delucis v8.0.4 works great without the workaround, thank you!

This is unrelated, but I'm still running with a local revert patch for @astrojs/vercel because of withastro/adapters#418 (comment). I narrowed it down to the specific commit that caused the issue but I'm not familiar enough with the library to determine the proper fix. If it's something in your wheelhouse or can be triaged/prioritized I'd appreciate it 🙏

@delucis
Copy link
Member

delucis commented Jan 23, 2025

This is unrelated, but I'm still running with a local revert patch for @astrojs/vercel because of withastro/adapters#418 (comment). I narrowed it down to the specific commit that caused the issue but I'm not familiar enough with the library to determine the proper fix. If it's something in your wheelhouse or can be triaged/prioritized I'd appreciate it 🙏

Very much not in my wheelhouse unfortunately, but I’ll mention to folks that this is blocking for you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants