The browser appears to read the JavaScript file as HTML and receives "Uncaught SyntaxError: Unexpected token '<'"
P粉520545753
2023-09-05 13:59:44
<p>Similar to this unanswered question: Browsers appear to read React JS files as HTML, not JSX</p>
<p>I have a project built using Next.js, React, and Typescript. </p>
<p>But now I'm trying to add some Javascript files like <code>testScroll.js</code>: </p>
<pre class="brush:php;toolbar:false;">function init() {
window.scrollTo(0, 1);
window.scrollTo(0, -1);
console.log('scrolling')
}
init()</pre>
<p>I saved this script at <code>public/js/testScroll.js</code>. I try to use it on this <code>index.tsx</code> component: </p>
<pre class="brush:php;toolbar:false;">import { type NextPage } from "next";
import { Footer, Header, HomePageWrapper } from "~/componentsFromWebflow/homeComponents";
import Script from "next/script";
import Head from "next/head";
const Home: NextPage = () => {
return (
<>
<Head>
<meta charSet="utf-8" />
<title>Ace-it</title>
<meta name="description" content="content" />
<meta content="width=device-width, initial-scale=1" name="viewport" />
<link href="https://fonts.googleapis.com" rel="preconnect" />
<link href="https://fonts.gstatic.com" rel="preconnect" crossOrigin="anonymous" />
<link href="https://uploads-ssl.webflow.com/64296e49c388ed7c157635f0/64296e49c388eda6b076360c_Faivcon 32.svg" rel="shortcut icon" type="image/x-icon" />
<link href="https://uploads-ssl.webflow.com/64296e49c388ed7c157635f0/64296e49c388edc81976360d_Faivcon 256.svg" rel="apple-touch-icon" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Header />
<HomePageWrapper />
<Footer />
<Script src="./js/scrollTest.js"
type="text/javascript"
strategy="beforeInteractive" />
</>
);
};
export default Home;</pre>
<p>I've tried every possible strategy with the <code>Script</code> tag, but nothing works.</p>
<p>The problem is<strong>when I load the page for the first time it throws the following error</strong>: </p>
<blockquote>
<p>Uncaught syntax error: Unexpected token '<' at scrollTest.js:1:1</p>
</blockquote>
<p>Of course, if I check the Source tab on Explorer, it looks like this: </p>
<p><strong>But after reloading a few times</strong> (usually just once), it <strong>starts working</strong> and displays the correct code:
</p>
<p>Also, I have a <code>middleware.ts</code>: </p>
<pre class="brush:php;toolbar:false;">import { getAuth, withClerkMiddleware } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import type { NextRequest } from 'next/server'
// Set the paths that don't require the user to be signed in
const publicPaths = ['/', '/api/stripe-webhook*', '/api/clerk-webhook*']
const isPublic = (path: string) => {
return publicPaths.find(x =>
path.match(new RegExp(`^${x}$`.replace('*$', '($|/)')))
)
}
export default withClerkMiddleware((req: NextRequest) => {
if (isPublic(req.nextUrl.pathname)) {
return NextResponse.next()
}
console.log("middleware running");
const { userId } = getAuth(req);
if (!userId) {
console.log('userId is null, undefined or empty');
const indexUrl = new URL('/', req.url)
indexUrl.searchParams.set('redirect_url', req.url)
return NextResponse.redirect(indexUrl)
}
return NextResponse.next();
});
// Stop Middleware running on static files
export const config = { matcher: '/((?!_next/image|_next/static|favicon.ico).*)', };</pre>
<p>It seems if I delete the cookie from explorer the error appears, but still don't know why and how to fix it. </p>
<p>What happened and how to fix it? </p>
You are getting this error because
"/js/scrollTest.js"
(the path marked byScript
) is not part of the ignored path. So when you enter the middleware you will get back HTML withNextResponse.redirect(indexUrl)
and the browser requires a JavaScript file.You can simply add
js/scrollTest.js
to your configuration: