How To Fix the "Source Parse Failed For Route" Error in Next.js
Tags: javascript, nextjs, programming, softwaredevelopment
Published: 2024-01-19 21:35:46

When dealing with Next.js middleware or headers in the `next.config.js`, you might stumble across the "source parse failed for route" error message. That is a common issue that occurs when you are not defining `matcher` or `source` values correctly.

Let's dig into this Next.js error, learning when it occurs and how to fix it!

## When Does the Invalid Custom Route Source Error Occur?

As explained in the [official documentation](https://nextjs.org/docs/messages/invalid-route-source), the invalid custom route `source` error occurs when a pattern cannot be parsed in custom routes, a middleware [`matcher`](https://nextjs.org/docs/pages/building-your-application/routing/middleware#matcher), `next.config.js` `headers'` [`source`](https://nextjs.org/docs/pages/api-reference/next-config-js/headers) field.

One of the most common reasons behind it is to use the normal [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) syntax instead of the [`path-to-regexp`](https://github.com/pillarjs/path-to-regexp) syntax.

Take a look at the example below:

```javascript
// src/middleware.js

import { NextResponse } from 'next/server'
 
export function middleware(request: NextRequest) {
  return NextResponse.redirect(new URL('/home', request.url))
}

export const config = {
  // invalid first carachter (it should be "/")
  matcher: '*',
}
```

When adding this middleware to your Next.js app, the compilation will fail with "Error: Invalid middleware found". In detail, the reason behind the error would be "Error parsing \*."

Similarly, consider the `next.config.js` file below:// next.config.js

```javascript
// next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
    async headers() {
        return [
            {
                // invalid double *
                source: "/api/:path**",
                headers: [
                    { key: "Access-Control-Allow-Credentials", value: "true" },
                    { key: "Access-Control-Allow-Origin", value: "https://example.com" },
                    { key: "Access-Control-Allow-Methods", value: "GET,DELETE,PATCH,POST,PUT" },
                    { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
                ]
            }
        ]
    }
}

module.exports = nextConfig
```

Again, this will fail with the "Error: Invalid header found" message. The reason? Here it is:

```
source parse failed for route {"source":"/api/:path**","headers":[{"key":"Access-Control-Allow-Credentials","value":"true"},{"key":"Access-Control-Allow-Origin","value":"https://example.com"},{"key":"Access-Control-All ow-Methods","value":"GET,DELETE,PATCH,POST,PUT"},{"key":"Access-Control-Allow-Headers","value":"X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version"}] Good to know: The `matcher` values need to be constants so they can be statically analyzed at build-time. Dynamic values such as variables will be ignored.
```

What do these two examples have in common? Both `matcher` and `source` do not comply with the `path-to-regexp` syntax! That is why Next.js raises that error.

## Addressing the Invalid Source Syntax Error

To avoid the error, all you have to do is make sure that `matcher` and `source` follow the `path-to-regexp` syntax. The most important rules to keep in mind are that values assigned to those fields:

1. Must start with `/`

3. Can include named parameters (e.g., `/blog/:path` matches `/blog/article-1` and `/blog/article-1` but not `/blog/article-3/draft`)

5. Can have modifiers on named parameters starting with `:` (e.g., `/blog/:path*` matches `/blog/a/b/c` because `*` means "zero or more." Specifically, `?` is "zero or one" and `+` is "one or more")

7. Can use regular expressions enclosed in parentheses (e.g., `/blog/(.*)` is the same as `/blog/:path*`)

Explore the [`path-to-regexp`](https://github.com/pillarjs/path-to-regexp#path-to-regexp-1) [documentation](https://github.com/pillarjs/path-to-regexp#path-to-regexp-1) to learn about this syntax!

## Conclusion

In this article, you learned what the "source parse failed for route" Next.js error is, why it occurs, and how to fix it. In detail, you realized that it is raised when you do not follow the `path-to-regexp` syntax. Thus, fixing it is quite simple and quick!

Thanks for reading! I hope you found this article helpful.
  
***
_The post "[How To Fix the "Source Parse Failed For Route" Error in Next.js](https://writech.run/blog/how-to-fix-the-source-parse-failed-for-route-error-in-next-js-c6a3484b0b1b/)" appeared first on [Writech](https://writech.run)._