react-components
Prisma

Prisma Database Setup in Next.js

In this guide, we'll set up a database using Prisma in a Next.js app.

Define Prisma Model

In your schema.prisma file, define the Prisma model for the database table you want to create:

generator client {
  provider = "prisma-client-js"
}
 
datasource db {
  provider = "postgresql"
  url = env("POSTGRES_PRISMA_URL") // Use your database URL
}
 
model CustomTable {
  id       Int     @id @default(autoincrement())
  name     String
  field1   String?
  field2   Int?
  field3   Boolean @default(false)
  // Add more fields as needed
}

Create a Page for Data Entry

Create a new page for data entry, for example, pages/new-data/page.tsx:

import React, { useState } from 'react'
import { useRouter } from 'next/router'
 
export default function NewData() {
  const router = useRouter()
  const [name, setName] = useState('')
  const [field1, setField1] = useState('')
  const [field2, setField2] = useState('')
  const [field3, setField3] = useState(false)
 
  const submitData = async (e: React.SyntheticEvent) => {
    e.preventDefault()
    try {
      const body = { name, field1, field2, field3 }
      await fetch(`/api/customtable`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      })
      router.push('/')
      console.log('Success', body)
    } catch (error) {
      console.error(error)
    }
  }
 
  return (
    <div>
      <form onSubmit={submitData}>
        <h1>Create New Data</h1>
        <input
          autoFocus
          onChange={(e) => setName(e.target.value)}
          placeholder="Name"
          type="text"
        />
        <input
          onChange={(e) => setField1(e.target.value)}
          placeholder="Field 1"
          type="text"
        />
        <input
          onChange={(e) => setField2(e.target.value)}
          placeholder="Field 2"
          type="number"
        />
        <label>
          <input
            type="checkbox"
            checked={field3}
            onChange={(e) => setField3(e.target.checked)}
          />
          Field 3
        </label>
        <input type="submit" value="Create" />
        <a href="/">or Cancel</a>
      </form>
    </div>
  )
}

Create API Route

Create an API route to handle data creation, for example, pages/api/customtable.ts:

import type { NextApiRequest, NextApiResponse } from 'next'
import prisma from '../../lib/prisma'
 
// POST /api/customtable
// Required fields in body: name, field1, field2, field3
export default async function handle(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  const result = await prisma.customTable.create({
    data: {
      ...req.body,
    },
  })
  return res.status(201).json(result)
}

Prisma Client Setup

Set up Prisma Client in your project. Create a file, for example, lib/prisma.ts:

lib/prisma.ts
import { PrismaClient } from '@prisma/client'
 
const globalForPrisma = global as unknown as { prisma: PrismaClient }
 
export const prisma = globalForPrisma.prisma || new PrismaClient()
 
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma