Encountering a 404 error when trying to reload the page?

My React Router is functioning properly in the development environment. Here's what I implemented in Webpack Dev Server:

historyApiFallback: {  
  index: 'index.html',
}

Now, when transitioning to production mode, I wanted to replicate the same behavior using Express. This is how I set it up:

const indexPath = path.join(__dirname, '../public/index.html')
const publicPath = express.static(path.join(__dirname, '../public'))

  app.use('/public', publicPath)
  app.use('/graphql', graphQLHTTP(async (req) => {
    let { user } = await getUser(req.headers.authorization); 
    if(!user) {
      user = 'guest'
    }
    return { 
      schema, 
      pretty: true,
      graphiql: true,
      context: {
        user,
      }
    }
  }); 

app.get('/', function (_, res) { res.sendFile(indexPath) });

I haven't made any changes to react-router-dom, so I suspect the issue lies within my Express configuration. What would be the equivalent of historyApiFallback in production mode? Below is a snippet from my webpack bundle configuration:

output: {
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js',
    publicPath: '/public/'
  },

In my HTML file, I reference the bundle like this:

<script type="text/javascript" src="/public/bundle.js"></script>

Despite having what seems to be the correct configuration, I encounter a "cannot GET Error 404" upon reloading. Any insights on this issue?

Answer №1

Make sure to include the following line in your application:

app.get('*', function (_, res) { res.sendFile(indexPath) });

Alternatively, you could consider utilizing this package for better functionality: https://github.com/bripkens/connect-history-api-fallback

Take some time to learn more about the history mode:

To eliminate the hash from your URLs and provide a seamless navigation experience, utilize the router's history mode with the history.pushState API:

With history mode enabled, your URLs will appear clean and straightforward, like . Isn't that beautiful?

However, there is a potential issue to address: When users directly access a URL such as without proper server configuration, they may encounter a 404 error. That's not ideal.

No need to fret though! To resolve this, simply add a fallback route on your server that serves the index.html page when no static assets match the requested URL. Problem solved, yet again!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we reduce the size of a JSON object in Typescript before sending it to the client?

Currently, I am faced with a common challenge. I have a database object that is a standard JS object originating from a document database, and my goal is to transmit this object to the client. However, certain fields contain sensitive information that shou ...

Incorporating HTML elements into a Jade template

Can HTML elements be passed into a jade file? For example, I want to insert text into the p element and nest some content inside the code element within the p element. JSON with string data var news = { one : { title : "Using JSON", body : "Us ...

How can I extract data from [Object object] in Node.js?

Can someone help me figure out how to extract data from [Object object]? Let's consider the following scenario for clarity. // Fetching data using dirty method var info = database.get('/htmltest') // Contents of test.db file {"key":"foo", ...

Is there a way to access the body html element within a template in vue.js?

I'm struggling to add styles to the body element of my HTML page. It seems like I can't access it directly from the template because there's another body element nested inside the main body. Even when I try to change the style using JavaScri ...

Navigating race conditions within Node.js++]= can be challenging, but there are strategies

In the process of developing a MERN full stack application, I encountered a scenario where the frontend initiates an api call to "/createDeckOfCards" on my NodeJS backend. The main objective is to generate a new deck of cards upon clicking a button and the ...

Fetching data from a server using React's axios library

I've been working on a personal project and ran into an issue. I'm trying to fetch all the car data from my database using Reactjs and Axios. While I can see all the data in the console, my page remains blank. It's worth mentioning that I&ap ...

What is the best way to transfer the text from an input field into a paragraph when a button is

For a school project, I am developing a website focused on time management. My goal is to create an input text box that, when the "add task" button is clicked, transfers the text inside it to a paragraph or p2 element and then moves the input field down. ...

Storing socket.io data in an array

Having trouble getting the desired array of arrays from my socket.io emitter. The structure I need is: [ [{...},{...},{...}] , [{...},{...}] , [{...}] ] But instead, I am receiving a different format. https://i.stack.imgur.com/3PY0u.jpg I require all t ...

Ensure that the form is submitted only after confirming it in the modal with react-hook-form

**I am facing an issue with submitting react-hook-form on confirm in a modal component. Whenever the user selects confirm, I need the form to be submitted directly. I have tried writing the modal inside FormSubmitButton. Also, I have tried placing it insi ...

Is the × symbol added from JavaScript not able to be clicked on?

In my javascript code, I have added HTML content dynamically using the following method: var response = { message: "sample messsage" }; $('#main-content').append( '<div class="alert alert-danger alert-dismissable">'+ & ...

I encounter difficulty utilizing assets within my React application

Currently, I am in the process of developing a React application for practice purposes. However, I have encountered an issue with using images and audio files stored in the assets folder. Despite my attempts to import them into the project, I have been uns ...

Creating Eye-Catching Images by Incorporating Image Overlays Using Just One Image

I'm facing a bit of a challenge here. I need to figure out how to overlay an image onto another image using just a single image tag. Specifically, I want to add a resize icon to the bottom right corner of an image to let users know they can resize it ...

Is it possible for me to customize the default angular filter in order to prioritize displaying strings that begin with the search term?

In my current project, we are dealing with a massive list of strings (17,000+ at times) and have implemented an input box for filtering the list. Initially, I used Angular's default filter, but then a request came in to sort the list so that strings s ...

What is the best way to insert a new row into a table upon clicking a button with Javascript?

Hi everyone, I'm facing an issue with my code. Whenever I click on "Add Product", I want a new row with the same fields to be added. However, it's not working as expected when I run the code. Below is the HTML: <table class="table" id="conci ...

Executing PHP code from a list item

On one of my website pages, I have a list that functions as a delete button. However, I am interested in making it so that when a user clicks on the delete option, a php script is triggered - similar to how a submit button works. Below is the list structu ...

Tips for creating a responsive Youtube embedded video

Check out this website for a good example: If you take a look, you'll notice that the header youtube video is responsive - it automatically resizes when the window size changes. Here are the <iframe> codes: <iframe id="bluetube-player-1" fr ...

Changes in query parameters on NextJS navigation within the same page do not activate hooks

When utilizing NextJS without SSR, I encountered an issue with basic navigation using different query parameters. Upon the initial arrival on the page/component, everything seems fine as the component gets mounted and URL params change accordingly. However ...

What is the reason for the lack of user data being saved in studio3t?

I'm struggling to identify the issue in my app development process. I'm creating an application that collects user email and password, storing them in a database. The problem lies in the fact that while user passwords are successfully stored, the ...

An issue encountered with getServerSideProps in NextJS 12 is causing a HttpError stating that cookies are not iterable, leading

Currently, I have an application running smoothly on my localhost. However, when it comes to production, an unexpected error has popped up: Error: HttpError: cookies is not iterable at handleError (/usr/src/.next/server/chunks/6830.js:163:11) at sendReques ...

I am receiving an undefined value when using document.getElementsByClassName

<canvas id="can" height="500px" width="1200px"></canvas> <div class="name"> <h1>LEONARDO</h1> </div> <script> var name=['WATSON','LEONARDO',"SMITH","EMILY"] var counter=0 var dat ...