I'd like get query params from request in API call. How can I retreive it in server side?
import prisma from "@/app/lib/prisma";
import { NextApiRequest, NextApiResponse } from 'next'
import { Context } from "vm";
export async function getServerSideProps(ctx: Context) {
const { igenykod } = ctx.params;
return {
props: {
igenykod
},
};
};
export async function GET(
req: NextApiRequest,
res: NextApiResponse
) {
const kod = req.query.igenykod as string
const igenystatusz = await prisma.igenystatusz.findMany({
where: {
igenykod: "CK1"
}
});
return new Response(JSON.stringify(igenystatusz));
}
In this code req.query is undefined. I readed about getServerSideProps but I dont want to make page for request. Can I make as simply as ExpressJS routing?
In the app
directory (router), you can get query strings (aka the ?search=value
) in an API route this way:
import { NextRequest, NextResponse } from "next/server";
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
console.log(searchParams.get("igenykod"));
return new Response("...");
}
The API route handler only gets passed only the request, and its type is NextRequest
not NextApiRequest
which is for the pages
router (only where getServerSideProps
works).