Blowing up your Next.js routes with name collisions

Today I spent longer than I'd like to admit trying to figure out why some dynamic routes in my Next.js app weren't working. Inside my app/ folder, my file structure looked like this:

app/
  api/
    [slug]/
      route.ts

When I ran my build locally, everything worked fine! But when I deployed to Vercel, I got a 404 error. I was stumped. I checked my routes, my file names, my imports, everything. I couldn't figure out what was going on.

The bug

After a lot of digging, experimenting, and banging my head against the wall, I finally figured out what was going on. The problem was that in my project folder, above app/, I had another folder called api/. This was causing a name collision with the api/ folder in my app/ directory. So the project file structure looked something like this:

api/
  methods.ts
app/
  api/
    [slug]/
      route.ts

When Vercel built my app, it was looking in the wrong api/ folder for my dynamic routes.

The fix

Like many problems, the fix was simple. I just had to rename the api/ folder in the root of my project to something else. I chose to rename it to utils/, which was a more appropriate name anyways. After that, everything worked perfectly.

The lesson

When I started building the app, I didn't intend to have two folders with the same name. My orginial /api folder was meant to be a place for utility methods to access a backend server. As the app grew, I added the /app/api folder to handle some dynamic routes within the application. I didn't think that the two folders would collide, but they did.

Save yourself the hours that I spent on this, and just make sure that your routes all have distinct names, even when it seems like they're in different parts of your project. It'll save you a lot of time and frustration in the long run.