error TypeError: Cannot read properties of undefined (reading 'headers')
Answered
Upland Sandpiper posted this in #help-forum
Upland SandpiperOP
Hi everyone, I'm trying to create a function like this one :
import { prisma } from "@/config/db";
import { NextResponse } from "next/server";
// function wich will check if the slug exists in the table
export async function checkSlug(paramTable: string, paramSlug: string) {
const result = await (prisma as any)[paramTable].findUnique({
where: { slug: paramSlug },
select: { slug: true, name: true },
});
// if this slug is not found, we send a response with a 404 status
if (!result) {
let error_response = {
status: "fail",
message: "This " + paramSlug + " is not found",
};
return new NextResponse(JSON.stringify(error_response), {
status: 404,
headers: { "Content-Type": "application/json" },
});
}
// if this slug is found, we send a response with a 200 status
let json_response = {
status: "success",
data: {
result,
},
};
return new NextResponse(JSON.stringify(json_response), {
headers: { "Content-Type": "application/json" },
});
}
I got this error :
error TypeError: Cannot read properties of undefined (reading 'headers')
Can you help me please ?
import { prisma } from "@/config/db";
import { NextResponse } from "next/server";
// function wich will check if the slug exists in the table
export async function checkSlug(paramTable: string, paramSlug: string) {
const result = await (prisma as any)[paramTable].findUnique({
where: { slug: paramSlug },
select: { slug: true, name: true },
});
// if this slug is not found, we send a response with a 404 status
if (!result) {
let error_response = {
status: "fail",
message: "This " + paramSlug + " is not found",
};
return new NextResponse(JSON.stringify(error_response), {
status: 404,
headers: { "Content-Type": "application/json" },
});
}
// if this slug is found, we send a response with a 200 status
let json_response = {
status: "success",
data: {
result,
},
};
return new NextResponse(JSON.stringify(json_response), {
headers: { "Content-Type": "application/json" },
});
}
I got this error :
error TypeError: Cannot read properties of undefined (reading 'headers')
Can you help me please ?
Answered by Upland Sandpiper
OK i just forgot to make export default async function :
export default async function getProductsBySubModeleSlug({
export default async function getProductsBySubModeleSlug({
42 Replies
Upland SandpiperOP
I use it inside a API get
example :
as in, the code in which you use this function
Upland SandpiperOP
// API GET
export async function GET(_request: Request, { params }: { params: Props }) {
const { marqueSlug, gammeSlug, modeleSlug, subModeleSlug } = params;
checkSlug("marque", marqueSlug);
//checkSlug("gamme", gammeSlug);
//checkSlug("modele", modeleSlug);
//checkSlug("subModele", subModeleSlug);
}
export async function GET(_request: Request, { params }: { params: Props }) {
const { marqueSlug, gammeSlug, modeleSlug, subModeleSlug } = params;
checkSlug("marque", marqueSlug);
//checkSlug("gamme", gammeSlug);
//checkSlug("modele", modeleSlug);
//checkSlug("subModele", subModeleSlug);
}
there it is
checkSlug return the response yes
but that response is only returned to the route handler
the route handler never returns that response again
export async function GET(_request: Request, { params }: { params: Props }) {
const { marqueSlug, gammeSlug, modeleSlug, subModeleSlug } = params;
return await checkSlug("marque", marqueSlug);
//checkSlug("gamme", gammeSlug);
//checkSlug("modele", modeleSlug);
//checkSlug("subModele", subModeleSlug);
}should work i think
Upland SandpiperOP
oh I see !
it works like a charm !
thanks 🙂
sorry I'm new 🙂
nw you're welcome
Upland SandpiperOP
but
how can I re-use this function
// API GET
export async function GET(_request: Request, { params }: { params: Props }) {
const { marqueSlug, gammeSlug, modeleSlug, subModeleSlug } = params;
return await checkSlug("marque", marqueSlug);
return await checkSlug("gamme", gammeSlug);
return await checkSlug("modele", modeleSlug);
return await checkSlug("subModele", subModeleSlug);
}
It return only the first function
export async function GET(_request: Request, { params }: { params: Props }) {
const { marqueSlug, gammeSlug, modeleSlug, subModeleSlug } = params;
return await checkSlug("marque", marqueSlug);
return await checkSlug("gamme", gammeSlug);
return await checkSlug("modele", modeleSlug);
return await checkSlug("subModele", subModeleSlug);
}
It return only the first function
@Upland Sandpiper how can I re-use this function
then you need to refactor. instead of returning the response you only return the data from checkSlug
instead of
you do
instead of
you do
instead of
return new NextResponse(JSON.stringify(error_response), {
status: 404,
headers: { "Content-Type": "application/json" },
});you do
notFound()instead of
return new NextResponse(JSON.stringify(json_response), {
headers: { "Content-Type": "application/json" },
});you do
return json_responseUpland SandpiperOP
notFounf will work inside an API
?
then in the route handler you can do like
// API GET
export async function GET(_request: Request, { params }: { params: Props }) {
const { marqueSlug, gammeSlug, modeleSlug, subModeleSlug } = params;
const [marque, gamme, modele, subModele] =
await Promise.all([
checkSlug("marque", marqueSlug),
checkSlug("gamme", gammeSlug),
checkSlug("modele", modeleSlug),
checkSlug("subModele", subModeleSlug),
]);
return NextResponse.json([marque, gamme, modele, subModele]);
}it will return an empty 404 response
Upland SandpiperOP
wow I wouldn't find it myself
ðŸ‘
@joulev the cause is that the route handler does not return a response
Selkirk Rex
I'm facing the same error, my api route handler is returning a response no matter what, but still I'm getting the error.
My try block code is working all the way till the end, I'm adding stuff to my database etc, but finally I'm getting the error.
Any ideas? Thanks in advance!
//api/post/route.js
export async function POST(request) {
try {
...
return new NextResponse(JSON.stringify(allGoodResponse), { headers: {"Content-Type": "application/json"} });
}
catch {
return new NextResponse(JSON.stringify(errorResponse), {headers: {"Content-Type":"application/json"}});
}
}My try block code is working all the way till the end, I'm adding stuff to my database etc, but finally I'm getting the error.
Any ideas? Thanks in advance!
@Selkirk Rex I'm facing the same error, my api route handler is returning a response no matter what, but still I'm getting the error.
//api/post/route.js
export async function POST(request) {
try {
...
return new NextResponse(JSON.stringify(allGoodResponse), { headers: {"Content-Type": "application/json"} });
}
catch {
return new NextResponse(JSON.stringify(errorResponse), {headers: {"Content-Type":"application/json"}});
}
}
My try block code is working all the way till the end, I'm adding stuff to my database etc, but finally I'm getting the error.
Any ideas? Thanks in advance!
nothing wrong with this POST (except perhaps you should've used
NextResponse.json for cleaner syntax), i think the problem is in a different route/method?if not, make a minimal repro repository
Upland SandpiperOP
@joulev : what do you think about it :
Upland SandpiperOP
import { prisma } from "@/config/db";
import { notFound } from "next/navigation";
import { NextResponse } from "next/server";
// function wich will check if the slug exist in the table
export async function checkSlug(paramTable: string, paramSlug: string) {
const result = await (prisma as any)[paramTable].findUnique({
where: { slug: paramSlug },
select: { id: true, slug: true, name: true },
});
// if this slug is not found, we send a response with a 404 status
if (!result) {
return null; // Return null instead of calling `notFound()`
}
return result;
}
// Props : /api/sao/[marqueSlug]/[gammeSlug]/[modeleSlug]/[subModeleSlug]
type Props = {
marqueSlug: string;
gammeSlug: string;
modeleSlug: string;
subModeleSlug: string;
};
// API GET
export async function GET(_request: Request, { params }: { params: Props }) {
const { marqueSlug, gammeSlug, modeleSlug, subModeleSlug } = params;
const [marque, gamme, modele, subModele] = await Promise.all([
checkSlug("marque", marqueSlug),
checkSlug("gamme", gammeSlug),
checkSlug("modele", modeleSlug),
checkSlug("subModele", subModeleSlug),
]);
// Check if any of the slugs are invalid
if (!marque || !gamme || !modele || !subModele) {
return notFound(); // Return a 404 response
}
// on retourne la liste des produits si tous les slugs sont valides
const products = await prisma.produit.findMany({
where: {
submodeleId: subModele.id,
},
});
return NextResponse.json([marque, gamme, modele, subModele, products]);
}@Upland Sandpiper <@484037068239142956> : what do you think about it :
nothing wrong with this, looks good to me
Upland SandpiperOP
ðŸ‘
Upland SandpiperOP
I need your help because finally I changed my code to execute it on the server side rather the client side.
So here is my code :
part 1/2
So here is my code :
part 1/2
/ get the products by submodel slug
import Breadcrumb from "@/components/server/Breadcrumb";
import Link from "next/link";
import checkSlug from "@/lib/checkSlug";
import { notFound } from "next/navigation";
import { prisma } from "@/config/db";
type Props = {
params: {
marqueSlug: string;
gammeSlug: string;
modeleSlug: string;
subModeleSlug: string;
};
};
// Dynamic route to get a list of products by submodele slug
export async function getProductsBySubModeleSlug({
params: { marqueSlug, gammeSlug, modeleSlug, subModeleSlug },
}: Props) {
const [marque, gamme, modele, subModele] = await Promise.all([
checkSlug("marque", marqueSlug),
checkSlug("gamme", gammeSlug),
checkSlug("modele", modeleSlug),
checkSlug("subModele", subModeleSlug),
]);
// Check if any of the slugs are invalid
if (!marque || !gamme || !modele || !subModele) {
return notFound(); // Return a 404 response
}
// if all slug are correct, return the products list
const products = await prisma.produit.findMany({
where: {
submodeleId: subModele.id,
},
});`part 2/2
return (
<>
<div className="container">
{products ? (
<>
<h1 className="title">
All products from {" "}
<Link
href={`/shop/${marqueSlug}`}
className="hover:underline font-bold"
>
{marque.name}
</Link>{" "}
<Link
href={`/shop/${marqueSlug}/${gammeSlug}`}
className="hover:underline font-bold"
>
{gamme.name}
</Link>{" "}
<Link
href={`/shop/${marqueSlug}/${gammeSlug}/${modeleSlug}`}
className="hover:underline font-bold"
>
{modele.name}
</Link>{" "}
<span className="text-red-500">{subModele.name}</span>
</h1>
{products.length > 0 ? (
<div className="product-list py-5">
{products.map((product) => (
<div key={product.id} className="product-card">
<h2>
<Link
href={`/shop/${marqueSlug}/${gammeSlug}/${modeleSlug}/${subModeleSlug}/${product.slug}`}
className="text-red-500"
>
{product.name}
</Link>
</h2>
</div>
))}
</div>
) : (
<p>SOrry no product available !</p>
)}
</>
) : (
notFound()
)}
</div>
</>
);
}and here is the checkSlug function :
import { prisma } from "@/config/db";
// function wich will check if the slug exist in the table
export default async function checkSlug(paramTable: string, paramSlug: string) {
const result = await (prisma as any)[paramTable].findUnique({
where: { slug: paramSlug },
select: { id: true, slug: true, name: true },
});
// if this slug is not found, we send a response with a 404 status
if (!result) {
return null; // Return null instead of calling `notFound()`
}
return result;
}and here is the error I got :
Unhandled Runtime Error
Error: The default export is not a React Component in page: "() => Promise.resolve(/*! import() eager /).then(webpack_require.bind(webpack_require, /! ./app/shop/[marqueSlug]/[gammeSlug]/[modeleSlug]/[subModeleSlug]/page.tsx */ "(sc_server)/./app/shop/[marqueSlug]/[gammeSlug]/[modeleSlug]/[subModeleSlug]/page.tsx")),D:\DEV\abbas\app\shop[marqueSlug][gammeSlug][modeleSlug][subModeleSlug]\page.tsx"
Unhandled Runtime Error
Error: The default export is not a React Component in page: "() => Promise.resolve(/*! import() eager /).then(webpack_require.bind(webpack_require, /! ./app/shop/[marqueSlug]/[gammeSlug]/[modeleSlug]/[subModeleSlug]/page.tsx */ "(sc_server)/./app/shop/[marqueSlug]/[gammeSlug]/[modeleSlug]/[subModeleSlug]/page.tsx")),D:\DEV\abbas\app\shop[marqueSlug][gammeSlug][modeleSlug][subModeleSlug]\page.tsx"
Upland SandpiperOP
OK i just forgot to make export default async function :
export default async function getProductsBySubModeleSlug({
export default async function getProductsBySubModeleSlug({
Answer
Upland SandpiperOP
it works now
thanks