Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Page works on initial page load, but if i refresh the page I get an 404 error with Zeit, Nextjs & now

I have recently upgraded from now v1 to v2.

Everything works locally with now dev and all pages reload without any problems. However when I push to prod with now --prod and navigate to a page everything works as expected, however if I reload the page I will take to the error page with an error of 404

I must admit i am finding the lines a little blurry on how I should setup my project since the move to v2. I am so sure its to do with my routing... but I always thought it took the routes directly from my folder structure?

To add to the confusion, if you reload, you will get a 404, however from that 404 error page, if you use the navigation the site will render without any problems.

According to the Docs, it should pick up the name from the filesystem, which i believe it does, as it navigates there initially.

By default, routing is defined by the filesystem of your deployment. For example, if a user makes a request to /123.png, and your now.json file does not contain any routes with a valid src matching that path, it will fallback to the filesystem and serve /123.png if it exists.

now.json

{
  "version": 2,
  "builds": [
    { "src": "next.config.js", "use": "@now/next" }
  ],
}

Folder structure

enter image description here

next.config.json

const webpack = require('webpack')
const withCSS = require('@zeit/next-css')

module.exports = withCSS({
  webpack: (config, {}) => {
    const originalEntry = config.entry

    config.entry = async () => {
      const entries = await originalEntry()

      if (entries['main.js'] && !entries['main.js'].includes('./polyfills.js')) {
        entries['main.js'].unshift('./polyfills.js')
      }

      return entries
    }
    return config
  },
  env: {
    env: process.env.NODE_ENV,
  },
})

But yes, I am stuck and would be eternally grateful for some help :)

Package.json

I am unsure if this is helpful to know for the problem, but here is my scripts.

  "scripts": {
    "build": "next build",
    "dev:inspect": "NODE_ENV=development nodemon --inspect server.js",
    "start": "now dev",
    "test": "echo \"Error: no test specified\" && exit 0",
    "lint-scripts": "eslint './{Frontend/**,test/**,config/**,.}/*.js'",
    "lint-styles": "stylelint './Frontend/**/*.css'",
    "eslint": "eslint . --fix",
    "lint": "npm run lint-scripts && npm run lint-styles",
    "commit": "npx git-cz"
  },

[Edit]

  "routes": [
    {"src": "/index", "dest": "/" },
    {"src": "/charts", "dest": "/charts" }
  ]
like image 396
Jamie Hutber Avatar asked Nov 15 '22 22:11

Jamie Hutber


1 Answers

Make a vercel.json and paste the redirect rules code. Save the file in your root directory, then redeploy.

{
  "routes": [{ "src": "/[^.]+", "dest": "/", "status": 200 }]
}
like image 73
Ru Ru Avatar answered Nov 30 '22 22:11

Ru Ru