New Next js project on compilation gives error 404

New Next.js Project on Compilation Gives Error 404

If you are encountering an error 404 when compiling your new Next.js project, don’t worry! This issue can be easily resolved by following a few steps. In this blog post, we will explore two possible solutions to fix this problem.

Solution 1: Check Your File Structure

One common reason for the error 404 in a Next.js project is an incorrect file structure. Make sure that your pages are located inside the pages directory at the root of your project. Next.js uses this directory to determine the routing for your application.

Here is an example of a correct file structure:


- pages
  - index.js
  - about.js
  - contact.js
- node_modules
- package.json
- ...

If your file structure is correct, but you are still encountering the error, try the next solution.

Solution 2: Configure Custom Routes

Next.js allows you to configure custom routes by using the next.config.js file. By defining custom routes, you can handle specific URLs and avoid the error 404.

Create a next.config.js file in the root of your project and add the following code:


module.exports = {
  async rewrites() {
    return [
      {
        source: '/about',
        destination: '/pages/about.js',
      },
      {
        source: '/contact',
        destination: '/pages/contact.js',
      },
    ];
  },
};

In this example, we are defining custom routes for the /about and /contact URLs. Adjust the code according to your project’s needs.

After adding the custom routes, restart your Next.js development server. The error 404 should no longer occur when accessing the defined URLs.

By following these two solutions, you should be able to fix the error 404 in your new Next.js project. Make sure to double-check your file structure and configure custom routes if necessary.

Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *