|
| 1 | +import { access, readFile } from "node:fs/promises"; |
| 2 | +import { join } from "node:path"; |
| 3 | +import { type NextRequest, NextResponse } from "next/server"; |
| 4 | + |
| 5 | +export const dynamic = "force-dynamic"; |
| 6 | + |
| 7 | +// Regex pattern for removing .md extension |
| 8 | +const MD_EXTENSION_REGEX = /\.md$/; |
| 9 | + |
| 10 | +export async function GET( |
| 11 | + request: NextRequest, |
| 12 | + _context: { params: Promise<{ slug?: string[] }> } |
| 13 | +) { |
| 14 | + try { |
| 15 | + // Get the original pathname from the request |
| 16 | + const url = new URL(request.url); |
| 17 | + // Remove /api/markdown prefix to get the original path |
| 18 | + const originalPath = url.pathname.replace("/api/markdown", ""); |
| 19 | + |
| 20 | + // Remove .md extension |
| 21 | + const pathWithoutMd = originalPath.replace(MD_EXTENSION_REGEX, ""); |
| 22 | + |
| 23 | + // Map URL to file path |
| 24 | + // e.g., /en/home/quickstart -> app/en/home/quickstart/page.mdx |
| 25 | + const filePath = join(process.cwd(), "app", `${pathWithoutMd}/page.mdx`); |
| 26 | + |
| 27 | + // Check if file exists |
| 28 | + try { |
| 29 | + await access(filePath); |
| 30 | + } catch { |
| 31 | + return new NextResponse("Markdown file not found", { status: 404 }); |
| 32 | + } |
| 33 | + |
| 34 | + const content = await readFile(filePath, "utf-8"); |
| 35 | + |
| 36 | + // Return the raw markdown with proper headers |
| 37 | + return new NextResponse(content, { |
| 38 | + status: 200, |
| 39 | + headers: { |
| 40 | + "Content-Type": "text/plain; charset=utf-8", |
| 41 | + "Content-Disposition": "inline", |
| 42 | + }, |
| 43 | + }); |
| 44 | + } catch (error) { |
| 45 | + return new NextResponse(`Internal server error: ${error}`, { |
| 46 | + status: 500, |
| 47 | + }); |
| 48 | + } |
| 49 | +} |
0 commit comments