sveltekit-i18n / lib

Internationalization library built for SvelteKit.
MIT License
447 stars 28 forks source link

Build failed for adapter Cloudflare #132

Closed Scorpio3310 closed 11 months ago

Scorpio3310 commented 11 months ago

Hi, I wanted to build an app with the Cloudflare adapter. I used only this example (https://github.com/sveltekit-i18n/lib/tree/master/examples/locale-router-advanced) in my project, and when I try to build the app, the build fails. Any ideas on how can I solve this?

Full code in attachment.


Using @sveltejs/adapter-cloudflare

node:internal/event_target:1006 process.nextTick(() => { throw err; }); ^ Error: Could not create a fallback page — failed with status 500 at generate_fallback (file:///Users/nik/Sites/language-test/my-app/node_modules/@sveltejs/kit/src/core/postbuild/fallback.js:53:8) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async MessagePort. (file:///Users/nik/Sites/language-test/my-app/node_modules/@sveltejs/kit/src/utils/fork.js:22:16) Emitted 'error' event on Worker instance at: at [kOnErrorMessage] (node:internal/worker:290:10) at [kOnMessage] (node:internal/worker:301:37) at MessagePort. (node:internal/worker:202:57) at [nodejs.internal.kHybridDispatch] (node:internal/event_target:731:20) at exports.emitMessage (node:internal/per_context/messageport:23:28)

Node.js v18.12.0


my-app.zip

jarda-svoboda commented 11 months ago

Hi @Scorpio3310! You need to handle fallback routes Cloudflare adapter uses (http://sveltekit-prerender/[fallback], or http://sveltekit-prerender/de/[fallback] etc..) to prerender error pages. Optionally you could disable prerendering..

// hooks.server.js
/** @type {import('@sveltejs/kit').Handle} */
export const handle = async ({ event, resolve }) => {

  // ...

  try {
    // Fetch the redirected route
    const response = await fetch(redirectTo, request);

    // Get response body and set html headers
    const data = await response.text();

    // Serve the redirected route.
    // In this case we don't have to set the html 'lang' attribute
    // as the default locale is already included in our app.html.
    return new Response(data, {
      ...response,
      headers: {
        ...response.headers,
        'Content-Type': isDataRequest ? 'application/json' : 'text/html',
      },
    });
  } catch (error) {
    // In case of error redirect to the error page.
    return resolve({ ...event, locals: { lang: locale } }, {
      transformPageChunk: ({ html }) => html.replace('%lang%', `${locale}`),
    })
  }

}
Scorpio3310 commented 11 months ago

@jarda-svoboda thank you it's working! 💯

Another question. I have set export const defaultLocale = 'cs'; to 'cs' but it's stills redirect me to 'en'. How to change this?

jarda-svoboda commented 11 months ago

Well, because your request.headers.get('accept-language') is (or fallbacks to) en.

So update hooks.server.js to change this behavior if needed..)