-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
34 lines (25 loc) · 902 Bytes
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import {NextRequest, NextResponse} from "next/server";
import videos from "./videos.json";
// Match only the index path
export const config = {
matcher: "/",
};
export default function middleware(req: NextRequest) {
// Get already played videos
let playedVideos = req.cookies.get("video")?.split(",")! || [];
// If we already played all videos, reset the list and the cookie
if (playedVideos.length === videos.length - 1) {
playedVideos = [];
req.cookies.set("video", playedVideos.join(","));
}
// Get a random video from the remaining videos
const video = videos
.filter((video) => !playedVideos.includes(video.id))
.sort(() => (Math.random() >= 0.5 ? 1 : -1))[0];
// Update the url to be the video to play
req.nextUrl.pathname = `/${video.id}`;
// Get a response
const res = NextResponse.rewrite(req.nextUrl);
// Return the response
return res;
}