Next.js File Based Routing (Part-1)

Posted by Ashutosh on April 03, 2021

  • In traditional React apps, we need to install the React-Router first, and we need to write a code at least a few lines to set up the routes and navigation. However, in Next.js, routing is the core feature. 

    During the setup of the Next.js application (visit here if you are new to this page), the page folder is created by default. If we add a new file under the page folder, Next.js identifies it as a route. 

    Take a look at the below illustration.

    It shows the page folder under the application. Under the page folder, there are few javascript files and a blog directory. 

    And the blog directory has two javascript files Index.js and another file with a weird name. We will discuss this strange file name later. 

    • Index.js file under the page folder refers to the home ('/') page of the application 
    • About.js refers to /about page of the application
    • Contact.js refers to the '/contact' page of the application
    • index.js under the blog folder refers to the '/blog' page of the application
    • [id].js under the blog folder indicates the dynamic routing. "id" implies the blog_id of the application (For ex- '/blog/1', where 1 is the blog id). 

    Adding our First Route

    Open the app in your favorite IDE and, don't forget to start the app (using yarn dev or npm).

    Delete the "api" and index.js file under the page folder. Refresh your home page you'll see a 404 page not found request. It is the expected result index.js under the page folder refers to the home page of our application. By deleting that file results in a custom 404 error.

    Recreate the file (index.js) with the following content

    function HomePage() {
      return (
        <div>This is the root of the application </div>
    export default HomePage;

    If you are familiar with the "React" Code looks similar to the library. Next.js is the extension of react library. It is fair to assume the similarity in the code. 

    Add Another Route

    Let's add another router '/contact'.

    Add a new file contact.js under the page folder and update it with the following:

    function ContactPage() {
      return (
          Send me an email at
    export default ContactPage;

    Visit http://localhost:3000/contact and, you will see "Send me an email at".

    In this article, we learn

    • How routing works in Next.js
    • Adding routes(Static) to Next.js app

    See you in the next article.