expo build web a page path

Viewed 1160

I have make a project with expo.

It works fine and I'm very happy, but now I need to access directly to a subpage (such as https://example.com/backoffice)

In the App.js I have make this:

...
const linking = {
    prefixes: ['https:/example.com'],
    config: {
      screens: {
        Home: '',
        Backoffice: '/backoffice',
      }
    },
  };

  return (
    <NavigationContainer linking={linking}>
...

If I execute the code in develop mode and I call the site to :19006 port, I can access directly to subpages.

If I execute the code after expo build:web and npx serve web-build I can't access to subpage (I receive a 404 not found).

2 Answers

Since you are using serve then you need a serve.json to handle redirects. Expo automatically generates a serve.json through expo build:web but it does not include any redirect code. There may be a setting you can add in app.json to automatically generate the redirects code but I can't see anything in the docs. (Hoping someone may be able to enlighten me on here).

Assuming this is a single page web app with an index.html you need to add the following inside your serve.json once you've built the web app:

{
  ...
  "rewrites": [
    { "source": "/*", "destination": "/index.html" }
  ]
}

This method is not ideal as you'll have to do this every time you build the web app but at least it should allow you to access subpages while running the build locally.

If you are going to deploy on Netlify, for example, then you need to add a _redirects file. I put my _redirects file in a directory in my project root called web (i.e web/_redirects) You can find out more about redirects files in the Netlify docs but the file should look something like this:

/*    /index.html   200

Once you've created this file, if you run expo build:web you should see it in the web-build directory. This should allow you to deploy on Netlify as a single page web app.

Use expo customize:web. Then, it will give your four options to create web/index.html, web/server.json, etc. Use them as you need. When you use expo build:web, Those index.html and server.json existing files will be used. If you deleted them, expo will use default methods.

Related