Next.js Discord

Discord Forum

can i use 2 Dynamic Segment in a api route?

Answered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
I have this api path app/api/downloads/[userId]/[userId]/route.tsx.
The problem it dosen't work
Answered by Transvaal lion
aparently i needed to restart next js
View full answer

9 Replies

Transvaal lionOP
Full code
import { promises as fs } from 'fs';
import path from 'path';
import { NextResponse } from 'next/server';
import { getClientId } from '@/app/upload/server';
import { FileMetadata } from '@/app/uploads/server';

interface RouteParams {
    params: Promise<{
        userId: string;
        fileId: string;
    }>;
}

export async function GET(req: Request, { params }: RouteParams) {
    const { fileId, userId } = await params;

    if (!fileId || userId) {
        return new NextResponse("ID-ul fișierului sau ID-ul utilizatorului lipsește.", { status: 400 });
    }

    try {
        const clientId = await getClientId();

        if (!clientId) {
            return new NextResponse("Autentificare eșuată. ID client lipsă.", { status: 401 });
        }

        const userStoragePath = path.join(process.env.FILESSTORAGEPATH!, clientId);
        const fileDestDir = path.join(userStoragePath, fileId);

        const metadataFilePath = path.join(fileDestDir, 'metadata.json');

        const metadataContent = await fs.readFile(metadataFilePath, 'utf-8');
        const metadata = JSON.parse(metadataContent) as FileMetadata;

        if (userId !== clientId && !metadata.shared && !(metadata.shares || []).some((s: any) => s.recipientId === clientId)) {
            console.warn("Acces Interzis")
            return new NextResponse("Acces interzis.", { status: 403 });
        }

        const metadataPath = path.join(metadata.storagePath, 'metadata.json');
        const fileContent = await fs.readFile(metadataPath);

        console.log("Path ul gasit: ", metadata.storagePath)
        return new NextResponse(fileContent, {
            headers: {
                'Content-Type': metadata.mimeType || 'application/octet-stream',
                'Content-Disposition': `attachment; filename="${metadata.originalName}"`,
                'Content-Length': fileContent.length.toString()
            },
        });
    } catch (error) {
        console.log(error)
        return new NextResponse("Fișierul nu a fost găsit sau accesul este interzis.", { status: 405 });
    }
}
yes this is possible
Transvaal lionOP
but why does it return 404
every time
if i remove the [userId] segment it works. but otherwise with both of them i get 404
GET /api/download/a2af6204-21d6-468d-83a1-8f19efefacf9/f8bb5828-9690-4c39-95b3-d952e43e68f9 404 in 148ms (compile: 85ms, render: 63ms)
Transvaal lionOP
aparently i needed to restart next js
Answer