Similar to this unanswered question: Browsers appear to read React JS files as HTML, not JSX
I have a project built using Next.js, React, and Typescript.
But now I'm trying to add some Javascript files like testScroll.js
:
function init() { window.scrollTo(0, 1); window.scrollTo(0, -1); console.log('scrolling') } init()
I saved this script at public/js/testScroll.js
. I try to use it on this index.tsx
component:
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 ( <>Ace-it > ); }; export default Home;
I've tried every possible strategy with the Script
tag, but nothing works.
The problem iswhen I load the page for the first time it throws the following error:
Uncaught syntax error: Unexpected token '<' at scrollTest.js:1:1
Of course, if I check the Source tab on Explorer, it looks like this:
But after reloading a few times (usually just once), it starts working and displays the correct code:
Also, I have a middleware.ts
:
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).*)', };
It seems if I delete the cookie from explorer the error appears, but still don't know why and how to fix it.
What happened and how to fix it?
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: