Next.js TypeScript Prisma setup following the MVC pattern.

Jun 04, 202410 mins read

First, let's define the MVC structure:


Model: Represents the data and business logic.
View: Represents the user interface.
Controller: Handles the user input and interaction with the model and view.
For our Next.js TypeScript Prisma setup, we'll organize our code as follows:

├── components/
│   └── // React components
├── controllers/
│   └── // Controllers for handling requests
├── models/
│   └── // Prisma models
├── pages/
│   └── // Next.js pages
├── services/
│   └── // Services for interacting with the database
└── prisma/
    └── schema.prisma // Prisma schema definition

Now let's create the corresponding files and write the code:

Model (Prisma): Define the CustomerProduct model in the schema.prisma file inside the prisma directory:

model CustomerProduct {
  id        Int       @id @default(autoincrement())
  name      String
  // Add other fields as needed

Controller: Create a controller to handle the destroy action. Inside the controllers directory, create a file named CustomerProductController.ts:

import { NextApiRequest, NextApiResponse } from 'next';
import prisma from '../../prisma/client';

export default async function destroy(req: NextApiRequest, res: NextApiResponse) {
  const { id } = req.query;

  try {
    const product = await prisma.customerProduct.findUnique({
      where: { id: Number(id) },

    if (!product) {
      return res.status(404).json({ message: 'Product not found' });

    await prisma.customerProductTranslation.deleteMany({
      where: { customerProductId: Number(id) },

    await prisma.customerProduct.delete({ where: { id: Number(id) } });

    return res.status(200).json({ message: 'Product has been deleted successfully' });
  } catch (error) {
    console.error('Error deleting product:', error);
    return res.status(500).json({ message: 'Internal server error' });

Service: We'll directly use Prisma in the controller, so no separate service is needed.

View: In Next.js, views are typically React components placed in the pages directory.

This setup should handle the deletion of a CustomerProduct entity in your Next.js application using TypeScript and Prisma, following the MVC pattern. Adjustments may be needed based on your specific project structure and requirements.

Inside the pages/api directory, create a file named customerProducts/[id].ts.
Write the following code in the file:

import type { NextApiRequest, NextApiResponse } from 'next';
import destroy from '../../../controllers/CustomerProductController';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'DELETE') {
    await destroy(req, res);
  } else {
    res.setHeader('Allow', ['DELETE']);
    res.status(405).end(`Method ${req.method} Not Allowed`);

This route will handle DELETE requests to /api/customerProducts/[id], where [id] is the ID of the product to be deleted.


Subscribe our newsletter