Go back

pageExtensions in Next.js

It's been a long while since I set up a new Next.js project with create-next-app and I guess there are some new features that I'm oblivious to.

Some days ago, I had a chat with Tola. Our conversation was about how he created a page in a Next.js project by going into the /pages directory and making a new file otp.js.

That should work, right? I mean yes. That's what we've all been used to. Only for me to experience a huge shock! Whenever we navigate to localhost:3000/otp we get a 404 error, page not found.

"page not found" how. shey you wan dey whine me nii!! 😏

The sentence above, when translated from Nigerian pidgin to english becomes "page not found" how. Are you kidding me!!. Yes. Is Next kidding me?

But, that's the truth. We ended up not being able to solve the issue, BTW.


Fast forward to yesterday. I tried using an API route, and the request kept on failing with a 404 status code.

To be sure, I tried visiting localhost:3000/api/hello to test the default API route example, and a 404 page was returned. This time around I knew that "something fishy is going on".

Enter, Next.js pageExtensions

After prancing around in the codebase for some minutes, opened next.config.ts and found this:

const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  images: {
    domains: ['images.unsplash.com'],
  },
  pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'],
}
 
module.exports = nextConfig

I spotted the difference immediately — pageExtensions. What exactly is this? I pondered.

While I pondered, I recalled that almost all the files in the pages directory were named in this format — home.page.tsx

So that's it? "Aaaarrrgggh!", I bellowed.

From there on, all I needed to do was include '.ts', and '.tsx' in the page extensions array, because I cannot have an API route with a page extension. But, that's left for you to decide, if you encounter this issue, in the future.

You can learn more about the pageExtension option here