deployment-docs

Advanced Front End | React (PP5) : Redirect / Rewrite rules

Configuring Redirect/Rewrite rules for a React application.


Due to the nature of React, without any redirect/rewrite rules written, navigating directly to anything other than the home page will result in a 404 error. Your deployed site has no actual files in the directories targeted by such a URL. Instead, we need to configure Render to accept all URLs with the same root and redirect them to a specific file, in most cases, index.html.

Process

  1. At the top of the page, copy the url for your deployed site

    an example deployed url with a copy icon beside it

  2. Go to your Render dashboard for your API project and click “Environment” to open your environment variables

    an application dashboard with the environment tab highlighted on the left

  3. Add/Update the variable for CLIENT_ORIGIN with the URL for your React application

    If using an env.py file, in “Secret Files”, click the eye icon to open your env.py file:

    • Create an environment variable, just like the others, with a key of CLIENT_ORIGIN and a value of the URL for your React application

      a secret file with updated contents

    • Click “Save Changes

      save changes button

    If using individual environment variables, click “Add Environment Variable

    • Add a key: CLIENT_ORIGIN and a value: your React application URL

      an environment variable key value pair input

    Make sure you do NOT put a trailing slash ( / ) here. If you do, your front end will not be able to connect to the API.

  4. Return to the Render dashboard for your React application. To enable our users to share links directly to our posts, we will need to add a Redirect/Rewrite rule

    an application dashboard with the redirects/rewrites tab highlighted on the left

  5. Click on “Add Rule” and add the values /*, /index.html and Rewrite, like so

    a rewrite rule with a source of ./* and a destination of /index.html

  6. Save your changes.

Up Next

You are nearly there. All the steps are completed, so have a read about the deployments on the next page.