After reloading the page, Nuxt dynamic routes are displaying a 404 error

Hey there! I'm currently diving into a project that involves using nuxt js, and it's all new to me. I've set it up in spa mode without any modifications in the nuxt config file, just sticking with the default settings. Here's how I've organized my pages:

pages/users/index.vue - displays a list of users

pages/users/_id.vue - shows details of a specific user

I've completed the deployment by running the commands npm run build and npm run start. The dist directory is now hosted on an nginx server.

The problem arises when I try to access /user/id directly through the URL or refresh the page – I end up getting a nginx 404 error page instead of my intended content being rendered.

I've come across suggestions about using nuxt generate for pre-rendering pages, but I'm uncertain if it would be suitable for handling a large number of records efficiently. Any advice or assistance on this matter would be greatly appreciated!

Thanks in advance!

Answer №1

Before diving into Nuxt, it's important to understand how it can help solve your problems.

Nuxt allows you to create three different types of applications:

  1. Static Pages

In this mode, Nuxt generates SEO-friendly HTML files based on routing. This is great for simple websites like business cards, where you get ready-made html files such as index.html, contact.html, etc.

  1. Single Page Applications (SPA)

SPAs do not require SEO but have dynamic paths and interfaces. They do not use server-side rendering but still offer benefits like dynamic routing and customizable configurations in Nuxt.

  1. Universal Mode

This mode offers all the benefits of Nuxt.js. By utilizing dedicated methods like fetch, asyncData, nuxtServerInit, etc., you can prepare data on the server side to generate SEO-friendly content on the browser side.

When choosing between SPA and Universal mode for dynamic routing, it's essential to consider your specific needs. Refer to Nuxt's documentation for guidance on which commands to use.

Answer №2

Creating a Nuxt site with static generation and dynamic routes

If you're unsure of the dynamic routes or SEO isn't a concern, this method is for you.

To implement this approach, set up a custom SPA fallback page in the generate configuration:

export default {
  generate: {
    fallback: "custom_sap_fallbackpage.html"
  }
}

Next, configure Nginx to use the same fallback page for unknown routes:

location / {
    try_files $uri /custom_sap_fallbackpage.html;
}

When using the `universal` mode, run `nuxt generate` to create the static site and deploy the contents of the `dist` folder by default.

In version 2.13.0, Nuxt introduced the `target: static` feature. Be sure to explore more about it here.

If you enable `fallback: true`, Nuxt will use `404.html` as the fallback page unless you override nginx's default 404 page. Some services like Netlify take advantage of this behavior for SPA integration. For nginx users, setting up a custom fallback page is recommended for mixing static sites and SPAs seamlessly.

This strategy involves pre-rendering static pages while treating dynamic routes as unknown for nginx, which then uses the fallback SPA page for rendering.

Remember to handle real unknown routes appropriately.

Handling a specific set of dynamic routes

You can follow a function-based approach to generate the static site.

Opting for a pure SPA experience

If you only want a SPA site, consider using the `spa` mode and refer to the recommended nginx configurations outlined here.

Answer №3

It seems like there is some confusion here. The default mode for Nuxt.js is actually universal, not spa as mentioned. You can refer to the official documentation for more information.

In order to run a universal app, you will need to use npm run start. On the other hand, for spa mode, you simply need to have a single html file and route all requests from nginx to that file.

If you are using npm run start, it means you are running a universal app and not hosting a simple html file via nginx. Instead, you should set up a downstream source for nginx and route all requests to your node server, typically located at localhost:3000.

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

Effectively detect the 'scrollend' event on mobile devices

When implementing the -webkit-overflow-scrolling: touch; style on a mobile element, dealing with scroll events can be quite challenging as they are triggered by various actions such as 'flicking', 'panning' and when the scroll comes to ...

Steps for inserting a button within a table

Currently, I have implemented a function that dynamically adds the appropriate number of cells to the bottom of my table when a button is clicked. This is the JavaScript code for adding a row: <a href="javascript:myFunction();" title="addRow" class= ...

What is the best approach to display data in React fetched from an API request? If this is not the right method, what changes should be made to the JSX rendering to convert

As I begin my journey with React, I find myself questioning the best practices for displaying data. Should I always break down components into smaller ones rather than having one large component render everything? It seems like a good practice, but I' ...

Struggling to make a basic JavaScript prompt function as expected

<html> <title>UniqueTitle</title> <head> <link rel="stylesheet" type="text/css" href="style.css" > <script type="text/javascript"> function modifyDates() { var dates = pr ...

Guide on incorporating markdown in an ejs template

As I am planning to create a small blog using Express, EJS, and Markdown, I encountered an issue when trying to load Markdown on the page. Here is what I saw: Here's my code snippet: <!DOCTYPE html> <html lang="pl"> <head> &l ...

Node.js and the concept of handling null values

console.log("variable = " + JSON.stringify(result.something)); After running the code, I see that variable = null However, when I add this condition: if (result.something != null || result.something != '') { console.log('entered' ...

Unable to attach an event listener to an element fetched from an API

I'm currently in the process of developing a trivia web application using an API, and my goal is to incorporate an event listener onto the button which corresponds to the correct answer. This way, when users click on it, a message will appear confirmi ...

Guide to refining a JSON array using a pre-established list

I'm in need of assistance figuring out how to accomplish the following task: Below is the code snippet I am working with: public class Data { public string FirstName; public string LastName; public int Age; } var data = new Data { //this objec ...

When using Vue.js, the v-bind:class directive can be applied when an array is present and contains a specific

In my current project with Laravel and Vue.js, I am dealing with the task of creating multiple users. To accomplish this, I am constructing an array of users and populating all the necessary fields in order to store them in a database table. Once all field ...

Instead of using setTimeout in useEffect to wait for props, opt for an alternative

Looking for a more efficient alternative to using setTimeout in conjunction with props and the useEffect() hook. Currently, the code is functional: const sessionCookie = getCookie('_session'); const { verifiedEmail } = props.credentials; const [l ...

Utilizing the setState method within an 'async function with arguments' for handling onClick events

In my next.js app, I have a file named "temp.js" located in the /pages directory. This is the code inside temp.js: import React from 'react'; import {Button} from '@mui/material'; class SomeClass extends React.Component{ state={ ...

What is the best way to prevent the content within a div from being obscured by a sticky element affixed to the bottom of the div?

I am struggling with ensuring that the content in my wrapper does not get cut off by the "view more" div attached to the bottom. The default wrapper cuts off the children, and even when expanded, the issue persists due to CSS problems. In React, the gener ...

Remove the initial DIV element from the HTML code

I have created a unique chat interface by combining JScript, php, and jquery. The chat messages are saved in an HTML document that gets displayed in the text area. Each user input message is contained within its individual div tag: <div>Message</ ...

Enhance the current model in backbone.js by incorporating additional data

When a user selects an item on the webpage, more details need to be fetched and displayed. The API function /api/full_details has been implemented to return the additional data for that item. Challenge: How can I retrieve the additional data and append it ...

Only the initial upload file is being passed through the Apollo Express server, with the remaining files missing in action

Currently, I am utilizing the apollo-express server with GraphQL. One issue I am encountering involves a mutation where I pass files from the front-end to the back-end. Strangely, I receive the file:{} object only for the first file - for the others, I rec ...

Create a custom loading spinner for a jQuery AJAX request

How can I add a loading indicator to my Bootstrap modal that is launched from a link? Currently, there is a 3-second delay while the AJAX query fetches data from the database. Does Twitter Bootstrap have built-in functionality for this? UPDATE: Modified J ...

Access array information using AngularJS

Sorry for any language issues. I am trying to figure out how to extract an array data from AngularJS in order to save it using Node.js. This is my AngularJS script: angular.module('myAddList', []) .controller('myAddListController&apos ...

Updating the color of a v-chip in vuetify dynamically

Just starting out with vuejs and vuetify. I recently watched a tutorial on vuetify on YouTube, where the instructor set the color of v-chip in this way. <v-flex xs2 sm4 md2> <div class="right"> <v-chip ...

Using various jQuery autocomplete features on a single webpage

UPDATE I have observed that the dropdown elements following the initial one are not being populated correctly. .data( 'ui-autocomplete' )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "i ...

Retrieve the service variable in the routing file

How do I access the service variable in my routing file? I created a UserService with a variable named user and I need to use that variable in my routing file. Here is the approach I tried, but it didn't work: In the routing file, I attempted: cons ...