'Next.js: _Middleware with NextResponse blocks images from rendering
This question extends this question. The _middleware in Next.js with import { NextResponse } from "next/server"; can be used for JWT authentication but blocks all the routes including images. This means that if you have images that you want to load in the redirect route by CSS or Image, will not load. The code below blocks address bar redirect and allows image load. Access Token would probably be better
Solution 1:[1]
Update: after some debugging, this is what I've come up with. The previous code that I wrote does not let you be redirected to the home page after login. The reason being that the _Middleware seems to runs before /api/login and based on the prev conditional, just redirects them to the login again and returns void (_Middleware "includes" on redirect).
This updated code allows /api/login to be routed on without a refresh token and sends them back to login if they navigate through address bar without a token
import { NextResponse } from "next/server";
export default function (req: {
url?: any;
cookies?: any;
}): void | NextResponse {
const { cookies } = req;
const url: string = req.url;
const refreshToken: string | undefined = cookies?.refresh_token_extreme;
const baseUrl: string = "http://localhost:3000";
// vercel.svg is used in /login
const unprotectedPaths: string[] = [
`${baseUrl}/login`,
`${baseUrl}/favicon.ico`,
`${baseUrl}/vercel.svg`,
`${baseUrl}/_next/webpack-hmr`,
`${baseUrl}/attachables/campus-images/image1.jpg`,
`${baseUrl}/attachables/mnhs-images/logos/login_logo.png`,
`${baseUrl}/attachables/mnhs-images/logos/mnhs_favicon_og.ico`,
]
if (unprotectedPaths.includes(url)) {
return void 0;
} else if (!refreshToken && url === "http://localhost:3000/api/login") {
return NextResponse.next();
} else if (!refreshToken) {
return NextResponse.redirect(`${baseUrl}/login`);
} else {
return NextResponse.next();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
