I have an issue nearly identical to https://github.com/vercel/next.js/issues/59971, however, I am trying to solve this with next.js middleware.
We already use middleware to help with authenticated routes so this is the preferred solution.
To Reproduce
- Create a Next.js app that uses a basePath (for example ‘/g/`) and the app router (or look at example repo from the github issue)
- Create and load a page in the application (/path/testing-page in example repo)
- Inspect the page and find the script with self.__next_f.push(….
Find the initialCanonicalUrl and it will be missing the base path (path).
This is causing issues with SEO because crawlers see the URL and think it’s a valid URL. From what I gather, there is currently no way to properly set it. We are getting 404s from this in the Google Search Console.
My initial thought was to add the basePath manually to the url.pathname
and then pass in the url into NextResponse.rewrite, however, when I do this, the url is rewritten with an additional basePath
if (
!url.pathname.startsWith(basePath) &&
!request.nextUrl.pathname.startsWith(basePath) &&
basePath !== '/'
) {
url.pathname = `${basePath}${url.pathname}`;
return NextResponse.rewrite(url);
}
Removing the basePath
from the url.pathname corrects the issue, but the initialCanonicalUrl
remains without the basePath
Scott Divelbiss is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.