'Nextjs returns 404 on reload but works on localhost hosted on Vercel

I have a nextjs project hosted on the vercel, and I am facing issue that when I reload some path (ex. /blogs) it returns 404. But, when I first access to the path, there is no problem and just show exactly what I want.

Path that I want to access is /blogs and directory structure is simply as below.

pages
     - blogs.tsx

and my blogs.tsx are using getStaticPros to get all blog mdx files.

import { GetStaticProps } from 'next'
import React from 'react'
import { Blogs } from '@component/blogs'
import BlogsType from '@src/types/blog'
import { getAllBlogs } from '@utils/blog/getAllPosts'

type BlogStaticInputs = {
    blogs: BlogsType[]
}

export const Index = ({ blogs }: BlogStaticInputs) => {
    return <Blogs blogs={blogs} />
}

// get all blogs data from './blogs'
export const getStaticProps: GetStaticProps = async () => {
    const blogs = getAllBlogs([
        'date',
        'description',
        'slug',
        'title',
        'author',
        'image',
        'sns',
        'username'
    ])

    return {
        props: { blogs },
        revalidate: 10
    }
}

export default Index

As I explained, it perfectly works on the first visit, but it fails on reload or after first visit on refresh.

I did some research and I found I should add trailingSlash:true on the next.config.js config file but it didn't solve my problem.

The error message is simpley Failed to load resource: the server responded with a status of 404 (). I am wondering why this happens since it just works locally (localhost) but suddenly fails on vercel preview url.



Solution 1:[1]

I think you should try building the app first on local environment via npm run build and check for blog.json file response in network tab because sometimes it does get 404 on .json file and still works that becomes problem on vercel later on.

Solution 2:[2]

I had a very similar issue. Removing the revalidate has solved it for me. For me i had revalidate every 36000 seconds, and i noticed my site was failing after exactly 10hours (36000s). For you it seems is 10 seconds, so you visit once, you get the cached files, and the second time nextjs tries to get the new data from the api.

Unfortunately I don't know why it fails, i just know that it will fix it. But you wont have ISR anymore you'll have just SSG.

I'll edit my answer once i find the culprit. Hope it helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aitreya Verma
Solution 2 Constantin Chirila