Unable to get middleware to work
Opened this issue · 2 comments
I just through to the Middleware Edge section and I still cannot figure out why it's not redirecting me to the login page. I even just cloned the repo from main, updated my .env.local to my PostgreSQL I was using before, ran the migrations and can see everything in prisma studio but I still get a 401 from the fetcher.ts lib too. There is no cookies that match to token which should be right since I haven't logged in. Not sure even where to start.
export default function fetcher(url: string, data = undefined) {
return fetch(`${window.location.origin}/api${url}`, {
method: data ? 'POST' : 'GET',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}).then((res) => {
if (res.status > 399 && res.status < 200) {
throw new Error()
}
return res.json()
})
}
I did update to middleware.ts
and to do the response
import { NextResponse } from 'next/server'
const signedinPages = ['/', '/playlist', '/library']
export default function middleware(req) {
if (signedinPages.find((p) => p === req.nextUrl.pathname)) {
const token = req.cookies.TRAX_ACCESS_TOKEN
if (!token) {
return NextResponse.rewrite(new URL('/signin', req.url))
}
}
}
This should fix it: https://stackoverflow.com/questions/73040090/nextjs-middleware-does-not-seem-to-be-triggered
Also, you're gonna have to change the redirect url from relative to an absolute path : https://nextjs.org/docs/messages/middleware-relative-urls
{root}/middleware.ts
import { NextResponse } from "next/server";
const signedinPages = ["/", "/playlist", "/library"];
export default function middleware(req) {
if (signedinPages.find((p) => p === req.nextUrl.pathname)) {
const token = req.cookies.JAMMLY_ACCESS_TOKEN;
if (!token) {
return NextResponse.redirect(new URL("/signin", req.url));
}
}
}
with next 13.3.1
export default function middleware(req: NextRequest) {
if (signedInPages.find((page) => page === req.nextUrl.pathname)) {
const token = req.cookies.get('TRAX_ACCESS_TOKEN')?.value;
if (!token) {
return NextResponse.rewrite(new URL('/signin', req.url))
}
}
}