codebear22
codebear22

Reputation: 1877

Not found page when refresh the page in Vite project deployed

I can navigate to all my pages after deploy my project on Vite using React, but when I refresh the page on certain path or write the path directly on the browser I got 404 page not found.

Here's my router:

<Switch>
    <Route path="/products/:id" component={ProductView}></Route>
    <Route path="/home" component={Home}></Route>
    <Route path="/contact" component={Contact}></Route>
    <Route path="/not-found" component={NotFound}></Route>
    <Redirect path="/" exact to="/home" />
    <Redirect path="" exact to="/home" />
</Switch>

vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react({
    include: "**/*.jsx",
  })]
})

I'm using

"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-router-dom": "^5.2.0",

I tried with react-router 6, adding a 200.html page, adding wildcards to the routers but none of those works at the moment. Any light in the dark? This only happens on project deployed on my server either in Vite or my LocalServer.

When I run yarn run dev everything works perfect even refreshing the page or writing the url on the browser.

UPDATE 23/2023

Maybe someone is dealing with this, specifically with VITE app. What @adsy says it's correct this require to setup wildcard routes. This happens because react router project just live there, and the server needs to be configure to work properly with react router or any other SPA. VITE doesn't have any special input to configure this specific, So what you have to do it's create a dockerfile that allows you to wrap your application instead of working with VITE default server configuration.

Here's an example of DockerFile in VITE:

FROM node:14-alpine AS builder

ARG YOUR_ENVIRONMENT_VARIABLES
ARG YOUR_ENVIRONMENT_VARIABLES

# Add a work directory
WORKDIR /app

COPY package.json .

RUN yarn install

COPY . /app/

RUN yarn build

FROM nginx:alpine

# Set working directory to nginx asset directory
WORKDIR /usr/share/nginx/html

# Remove default nginx static assets
RUN rm -rf ./*

COPY --from=builder /app/dist .

COPY .nginx/nginx.conf /etc/nginx/conf.d/default.conf

ENTRYPOINT ["nginx", "-g", "daemon off;"]

And that's the solution for this specific issue.

Upvotes: 6

Views: 9638

Answers (3)

Rudra
Rudra

Reputation: 11

Add this script in the index.js

<script type="text/javascript">
  // Single Page Apps for GitHub Pages
  // MIT License
  // https://github.com/rafgraph/spa-github-pages
  // This script checks to see if a redirect is present in the query string,
  // converts it back into the correct url and adds it to the
  // browser's history using window.history.replaceState(...),
  // which won't cause the browser to attempt to load the new url.
  // When the single page app is loaded further down in this file,
  // the correct url will be waiting in the browser's history for
  // the single page app to route accordingly.
  (function(l) {
    if (l.search[1] === '/' ) {
      var decoded = l.search.slice(1).split('&').map(function(s) { 
        return s.replace(/~and~/g, '&')
      }).join('?');
      window.history.replaceState(null, null,
          l.pathname.slice(0, -1) + decoded + l.hash
      );
    }
  }(window.location))
</script>

then add a seprate file in the public folder as 404.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Single Page Apps for GitHub Pages</title>
    <script type="text/javascript">

      var pathSegmentsToKeep = 0;

      var l = window.location;
      l.replace(
        l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
        l.pathname.split('/').slice(0, 1 + pathSegmentsToKeep).join('/') + '/?/' +
        l.pathname.slice(1).split('/').slice(pathSegmentsToKeep).join('/').replace(/&/g, '~and~') +
        (l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
        l.hash
      );

    </script>
  </head>
  <body>
  </body>
</html>

It will start working, I just had the same issue

Upvotes: 1

Emmanuel Murairi
Emmanuel Murairi

Reputation: 401

I had a similar issue deploying a react app built with vite. I solved it by editing the .htaccess to redirect all urls (except statics) to index.html deals with rendering the correct page based on the route.

A snippet of the .htaccess configuration below:

RewriteEngine On

RewriteCond %{REQUEST_URI} !\.(css|js|png|jpg|gif)$
RewriteCond %{REQUEST_URI} !^/index.html$
RewriteRule ^(.*)$ /index.html [L,QSA]

This approach was based on the following StackOverflow question: How to redirect all pages only to index.html using htaccess file and not redirect the image files

Upvotes: 3

luizjhonata
luizjhonata

Reputation: 29

I was with the same problem in a project deployed in Netlify, and i solved with those simple steps bellow.

1 - Make sure to create a public/_redirects file with the following rewrite rules:

/*  /index.html  200

Upvotes: 2

Related Questions