DEV Community

Cover image for How To Fix the "Source Parse Failed For Route" Error in Next.js
Antonello Zanini for Writech

Posted on • Originally published at writech.run

How To Fix the "Source Parse Failed For Route" Error in Next.js

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, the invalid custom route source error occurs when a pattern cannot be parsed in custom routes, a middleware matcher, next.config.js headers' source field.

One of the most common reasons behind it is to use the normal RegExp syntax instead of the path-to-regexp syntax.

Take a look at the example below:

// 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: '*',
}
Enter fullscreen mode Exit fullscreen mode

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

// 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
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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 /

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

  3. 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")

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

Explore the path-to-regexp documentation 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" appeared first on Writech.

Top comments (0)