I'm working on a Next.js application where users can generate logos and save them to their account. When the user clicks the "Save Image" button, a POST request is made to an API route to save the image URL along with the user ID to a Prisma database.
The issue I'm facing is that when I click the "Save Image" button, I'm getting a 500 error in the browser console, and the image is not being saved. I have checked the API route implementation and the Prisma schema, but I can't seem to find the cause of the error.
Here is my code:
'use client';
import { PageWrapper } from '@/components/Page-Wrapper';
import Image from 'next/image';
import { useRouter, useSearchParams } from 'next/navigation';
import React, { useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query'; // Import the useMutation hook
import axios from 'axios';
import { toast } from '@/hooks/use-toast';
import { Button } from '@/components/ui/button';
const DisplayLogo: React.FC = () => {
const [image, setImage] = useState<string | null>(null);
const searchParams = useSearchParams();
const router = useRouter();
useEffect(() => {
const imageQueryParam = searchParams?.get('image');
if (typeof imageQueryParam === 'string') {
setImage(imageQueryParam);
}
}, [searchParams]);
// Define the mutation function to save the image
const createImageMutation = useMutation(
async ({ imageUrl }: { imageUrl: string }) => {
await axios.post('/api/save-image', { imageUrl });
},
{
onError: () => {
toast({
title: 'Something went wrong',
description: 'Could not save image. Please try again later.',
variant: 'destructive',
});
},
onSuccess: () => {
toast({
title: 'Image saved',
description: 'Your image has been saved to your account',
variant: 'default',
});
},
}
);
const handleSaveImage = () => {
if (image) {
createImageMutation.mutate({ imageUrl: image });
}
};
return (
<PageWrapper>
<main className='py-40 px-8 md:px-12 lg:px-24 flex flex-col items-center justify-center'>
<h1 className='text-3xl md:text-4xl lg:text-5xl font-bold mb-4'>
Your Generated Image
</h1>
{image ? (
<div className='mt-8'>
<Image
className='w-64 h-64 object-cover rounded-md shadow-lg'
src={image}
alt='AI Generated'
width={500}
height={500}
/>
</div>
) : (
<p className='text-center text-lg mx-auto max-w-md mb-8'>
No logo image found. Please go back and generate an image first.
</p>
)}
<div className='flex flex-col items-center mt-5'>
{image && <Button onClick={handleSaveImage}>Save Image</Button>}
<p className='text-center text-lg mx-auto max-w-md mt-5'>
Congratulations! Your ai generated has been generated using the input you
provided!
</p>
</div>
</main>
</PageWrapper>
);
};
export default DisplayLogo;
Including API:
// Import the required modules and types
import { db } from '@/lib/db';
import { getAuthSession } from '@/lib/auth';
import { ImageValidator } from '@/lib/validators/images';
import { z } from 'zod';
export async function POST(req: Request) {
try {
const session = await getAuthSession();
if (!session?.user) {
return new Response('Unauthorized', { status: 401 });
}
// Parse the request body using the ImageValidator schema
const body = await req.json();
const { imageUrl } = ImageValidator.parse(body);
// Check if the image already exists
const image = await db.image.findUnique({
where: {
id: imageUrl,
},
});
if (image) {
return new Response('Image already exists', { status: 409 });
}
// Create the image and associate it with the user
const newImage = await db.image.create({
data: {
userId: session.user.id,
url: imageUrl,
createdAt: new Date(),
},
});
// Return a success response
return new Response(JSON.stringify({ message: 'Image saved successfully' }), {
status: 201,
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
if (error instanceof z.ZodError) {
// Return a response with the validation error message
return new Response(error.message, { status: 422 });
}
// Return a generic error response
return new Response('Something went wrong', { status: 500 });
}
}
I have also defined a zod schema (ImageValidator
) to validate the request body before creating the image.
Zod Schema:
import { z } from 'zod';
export const ImageValidator = z.object({
imageUrl: z.string().url(),
userId: z.string().optional(), // Assuming userId is optional
createdAt: z.date().optional(),
updatedAt: z.date().optional(),
});
export type ImageData = z.infer<typeof ImageValidator>;
Errors:
Could you please help me identify the cause of the 500 error and why the image is not being saved to the database? Any insights or suggestions to troubleshoot and resolve this issue would be greatly appreciated.