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
Asked
Active
Viewed 1,613 times
0

Nugget
- 81
- 1
- 6
- 23
2 Answers
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();
}
}

Nugget
- 81
- 1
- 6
- 23
0
Middleware will be invoked for every route in your project. The following is the execution order:
- headers from next.config.js
- redirects from next.config.js
- Middleware (rewrites, redirects, etc.)
- beforeFiles (rewrites) from next.config.js
- Filesystem routes (public/, _next/static/, Pages, etc.)
- afterFiles (rewrites) from next.config.js
- Dynamic Routes (/blog/[slug])
- fallback (rewrites) from next.config.js
There are two ways to define which paths Middleware will run on:
Custom matcher config
Conditional statements

Honorable con
- 149
- 7