Skip to content

Commit 335274f

Browse files
author
misostack
committed
update lession 03 login demo
1 parent e559318 commit 335274f

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

content/post/khoa-hoc-nextjs-bai-03-advanced-routing.md

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,4 +233,35 @@ export const config = {
233233
export const ProtectedRoutes = ["/my-account"];
234234
```
235235

236-
Giờ chúng ta thử thực hiện login
236+
Giờ chúng ta sẽ giả sử nếu user truy cập trang chủ, xem như đã login thành công.
237+
Để kiểm thử auth middleware này.
238+
239+
```ts
240+
import { NextResponse } from "next/server";
241+
import type { NextRequest } from "next/server";
242+
import { authMiddleware } from "./app/middlewares/auth.middleware";
243+
import { AppCookie, ProtectedRoutes } from "./shared/constant";
244+
import _db from "../_db";
245+
246+
// This function can be marked `async` if using `await` inside
247+
export function middleware(req: NextRequest) {
248+
console.log("[Middleware Demo] : " + req.url);
249+
250+
const path = req.nextUrl.pathname;
251+
252+
// fake login
253+
if (path == "/") {
254+
const response = NextResponse.next();
255+
response.cookies.set(AppCookie.UserToken, _db.tokens[0].token);
256+
return response;
257+
}
258+
259+
// ...
260+
261+
return NextResponse.next();
262+
}
263+
264+
// ...
265+
```
266+
267+
![image](https://gist.github.com/assets/31009750/6e56425c-4743-4c81-917a-212004e10a2a)

0 commit comments

Comments
 (0)