From 3f684a13a54deef2497f42435aa95148a96442ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateus=20Felipe=20Gon=C3=A7alves?= Date: Sun, 15 Sep 2024 15:00:51 -0300 Subject: [PATCH] feat(blog): create middleware for rewrite post slug on runtime --- src/middleware.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/middleware.ts diff --git a/src/middleware.ts b/src/middleware.ts new file mode 100644 index 00000000..83405d9f --- /dev/null +++ b/src/middleware.ts @@ -0,0 +1,24 @@ +import { NextRequest, MiddlewareConfig, NextResponse } from 'next/server' +import { slug } from './lib/slug' + +export function middleware(request: NextRequest) { + if (request.nextUrl.pathname.startsWith('/blog/post')) { + const splittedPath = request.nextUrl.pathname + .split('/') + .filter(s => s !== '') + + if (splittedPath.length === 3) { + return NextResponse.rewrite( + new URL(`/blog/post/${slug(splittedPath[2])}`, request.url) + ) + } + } + + return NextResponse.next() +} + +export const config: MiddlewareConfig = { + matcher: [ + '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)' + ] +}