Home  Prisma   Should we u ...

Should we use prisma generated types in frontend code

Using Prisma-generated types directly in your frontend can be convenient, but it comes with some caveats.Here are some points to consider:

When to Use Prisma Types in the Frontend:

  1. Simplicity: If your application is relatively simple and you have a strong consistency between the frontend and backend data models, using Prisma types can reduce redundancy and simplify type management.

  2. Consistency: Using the same types across both frontend and backend ensures that any changes in the database schema are automatically reflected in the types used in your frontend, reducing the risk of mismatches.

  3. Small Projects: For small projects or internal tools, using Prisma types directly can speed up development and reduce the overhead of maintaining separate types.

When to Create Separate Types for the Frontend:

  1. Separation of Concerns: The backend and frontend might have different concerns. Backend models often include fields like password, createdAt, updatedAt, etc., which are not needed or should not be exposed in the frontend. Creating separate types for the frontend allows you to tailor the data structure to your frontend's needs.

  2. Security: If Prisma types include sensitive information (e.g., passwords, tokens, internal IDs), exposing them directly to the frontend can be risky. By creating separate types, you can ensure only the necessary and safe data is exposed.

  3. Different Data Shapes: The frontend might need data in a different shape or with additional computed properties (e.g., formatted dates, combined fields). In such cases, having separate types ensures that the frontend data structure is optimized for UI/UX needs.

  4. Large or Growing Projects: As projects grow, maintaining a strict separation between frontend and backend concerns becomes more critical. Separate types allow for more flexibility in evolving the frontend independently from the backend.

Recommended Approach:

Example:

// Backend (Prisma model)
type PrismaUser = {
  id: number;
  email: string;
  password: string;
  createdAt: Date;
  updatedAt: Date;
};

// Frontend (DTO or Interface)
interface FrontendUser {
  id: number;
  email: string;
  username?: string;
}

// Mapper function
function mapPrismaUserToFrontendUser(prismaUser: PrismaUser): FrontendUser {
  return {
    id: prismaUser.id,
    email: prismaUser.email,
    // username can be added or formatted differently
  };
}
Published on: Aug 17, 2024, 09:32 PM  
 

Comments

Add your comment