gatsbyjs / themes

This is a repo for Gatsby's official themes.
138 stars 77 forks source link

[gatsby-theme-i18n] Create language detection page "/" for prefixDefault=true #104

Closed javiertury closed 3 years ago

javiertury commented 3 years ago

prefixDefault=true prepends the locale to all URLs. This is nice feature but breaks the / page, trying to access http://localhost:8000/ returns a 404.

There's not a page yet at /

The page src/pages/index.tsx is working as intended, it's served at /<locale>. My objective is to create a language agnostic index page (/) that detects the browser locale and redirect the user to http://localhost:8000/<locale>/. However I'm not sure what is the right approach.

I digged into the code of this theme and implemented a workaround. A page for language detection is added in gatsby-node.js and tricks gatsby-theme-i18n to ignore it.

// gatsby-node.js

exports.createPages = async ({ actions: { createPage } }) => {
  createPage({
    path: '/index.html',
    matchPath: '/',
    component: require.resolve('./src/templates/LangDetectionPage.js'),
    context: {
      // Important!!! This makes gatsby-theme-i18n ignore this page
      originalPath: '/index.html',
      // Need to hardcode them, themeOptions is not yet defined
      locale: 'en',
      hrefLang: 'en-US',
      dateFormat: 'MM/DD/YYYY'
    }
  });
};

This is clearly not a good long term solution, and neither is to hardcode a createRedirect.

Could theme options be extended to specify a unprefixed index page?

prefixDefault: boolean | { unprefixedIndexPath: string }

EDIT: with gatsby 3 the workaround is not as effective. The client side router still loads the page, but there is no public/index.html page being generated and a 404 page is served instead which is visible for about 1-2 seconds.