[Solved] Next.js routing not working – Pages not loading correctly – Next.js

by
Alexei Petrov
next.js node.js react-typescript reactjs

Quick Fix: To fix the routing issue, ensure that you have not nested the app and pages folders. Verify that you have chosen the correct folder structure while creating your project. If you want to use the pages router, create a new project and answer the prompts accordingly.

The Problem:

In a Next.js application, a page named about.tsx is set up within the "pages" directory. However, when accessing the page through its URL (localhost:3000/about), it fails to load and displays a 404 error message. Double-checking the code and directory structure shows everything seems to be in order. Troubleshooting is required to determine the cause of the issue and find a solution to make the page load correctly.

The Solutions:

Solution 1: Incorrect folder structure

The app and pages folders have a special significance in Next.js. They should not be nested within each other.

The structure you have created, with app nesting pages, is incorrect. This is likely causing the 404 error when trying to access the about page.

To fix this issue, you should create the about page within the pages directory. This means the correct structure would be pages/about/index.tsx.

If you are following a tutorial that uses the app folder for routing, the easiest solution is to create a new project and answer the terminal question accordingly during project creation.

Q&A

What could be causing the 404 error when trying to access a page in a Next.js application?

Incorrect folder structure and nesting files in app and pages folders

How to fix the 404 error in Next.js when trying to access a page?

Create a folder named about in app with a page.tsx in it

What should be done if following a tutorial and want to use the pages router?

Create a new project and answer the terminal accordingly

Video Explanation:

The following video, titled "Next.js 14 Full Course 2024 | Build and Deploy a Full Stack App ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

... Next.js 14 App Folder Structure - Next.js 14 Client Components vs Server Components - Next.js 14 File-based Routing (including dynamic and ...