<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Utkarsh Anand on Medium]]></title>
        <description><![CDATA[Stories by Utkarsh Anand on Medium]]></description>
        <link>https://medium.com/@growupanand?source=rss-e3e1505d1cc0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TSvkIhVpTh1jff4A4xKUbA.png</url>
            <title>Stories by Utkarsh Anand on Medium</title>
            <link>https://medium.com/@growupanand?source=rss-e3e1505d1cc0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 00:18:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@growupanand/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Comprehensive Guide to Easily Switch from Prisma to Drizzle ORM]]></title>
            <link>https://medium.com/@growupanand/a-comprehensive-guide-to-easily-switch-from-prisma-to-drizzle-orm-c290f8ed8ef3?source=rss-e3e1505d1cc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c290f8ed8ef3</guid>
            <category><![CDATA[gui̇de]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[drizzle]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[prisma]]></category>
            <dc:creator><![CDATA[Utkarsh Anand]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 19:38:27 GMT</pubDate>
            <atom:updated>2024-02-09T19:38:27.928Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_QnjJQLnFB4PZeg4KMEHw.png" /></figure><p>Hey Everyone 👋,</p><p>Building <a href="http://convoform.com/">convoform.com</a> has exposed me to new information. I started blogging about what I learned. In my previous <a href="https://medium.com/@growupanand/transitioning-from-monorepo-to-turborepo-my-development-journey-with-convoform-com-691b9d19f397">blog</a>, I explained how to set up Turborepo for your Monrepo, and now I’ll walk you through the process of switching from Prisma to Drizzle.</p><p><strong>Why I am moving to Drizzle?</strong></p><p>Because Drizzle does not require any generate step like in Prisma after every time I change something in my schema, although I don’t change very frequently in the schema still the types are not dependent upon running a command. In drizzle it all works live.</p><p>In Drizzle database queries are optimized like it will do only one database call even if you are fetching relational row items.</p><p>For more information visit their official site — <a href="https://orm.drizzle.team/benchmarks">https://orm.drizzle.team/benchmarks</a></p><p>Keep in mind I am using turborepo so I have a separate db package where I have separate package.json file, So every step here is according to my project folder structure, you need to change it according to yours, Example --filter @convoform/db is used in turborepo to install a dependency inside a package.</p><p><strong>We will do this in three steps:</strong></p><ol><li>Basic setup</li><li>Create schema, types, validators and migrations</li><li>Using Drizzle</li></ol><h3>Step 1. Basic setup</h3><p><strong>Install required packages,</strong></p><p>From the root of a project run the below command to add dependencies</p><pre>pnpm install drizzle-orm pg --filter @convoform/db</pre><p>then this command to add development dependencies</p><pre>pnpm install -D @types/pg drizzle-kit typescript ts-node tsx --filter @convoform/db</pre><p><strong>Add required scripts command into</strong></p><p>Add the below commands to your package.json</p><pre>{<br>  &quot;name&quot;: &quot;@convoform/db&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;drizzle-kit&quot;: &quot;drizzle-kit&quot;,<br>    &quot;drizzle:generate-migration&quot;: &quot;drizzle-kit generate:pg --out drizzle/migrations --schema src/schema/index.ts&quot;,<br>    &quot;drizzle:apply-migration&quot;: &quot;tsx ./src/migrate.ts&quot;<br>  }<br>}</pre><p><strong>Create file </strong><strong>drizzle.config.ts</strong></p><pre>import { defineConfig } from &quot;drizzle-kit&quot;;<br><br>export default defineConfig({<br>  schema: &quot;./src/schema/index.ts&quot;,<br>  out: &quot;./drizzle&quot;,<br>  driver: &quot;pg&quot;,<br>  dbCredentials: {<br>    connectionString: process.env.DATABASE_URL!,<br>  },<br>  verbose: true,<br>  strict: true,<br>});</pre><p><strong>Create file </strong><strong>tsconfig.json</strong></p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES2022&quot;,<br>    &quot;lib&quot;: [&quot;dom&quot;, &quot;dom.iterable&quot;, &quot;ES2022&quot;],<br>    &quot;allowJs&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;strict&quot;: true,<br>    &quot;noEmit&quot;: true,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;module&quot;: &quot;esnext&quot;,<br>    &quot;moduleResolution&quot;: &quot;Bundler&quot;,<br>    &quot;resolveJsonModule&quot;: true,<br>    &quot;isolatedModules&quot;: true,<br>    &quot;moduleDetection&quot;: &quot;force&quot;,<br>    &quot;jsx&quot;: &quot;preserve&quot;,<br>    &quot;incremental&quot;: true,<br>    &quot;noUncheckedIndexedAccess&quot;: true<br>  },<br>  &quot;include&quot;: [&quot;src&quot;, &quot;*.ts&quot;, &quot;**/*.ts&quot;],<br>  &quot;exclude&quot;: [&quot;node_modules&quot;]<br>}</pre><h3>Step 2. Create schema, types, validators and migrations</h3><p>As I have already a schema defined in Prisma and data exist in my database, I will use drizzle-kit CLI to generate a schema based on my existing data in the database.</p><p>But before running the command let&#39;s change our working directory in the terminal to the db folder</p><pre>cd packages/db/</pre><p><strong>Create schema</strong></p><p>Now run the below command</p><pre>pnpm drizzle-kit introspect:pg --config=drizzle.config.ts</pre><p>which will output something like the below</p><pre>&gt; @convoform/db@0.0.0 drizzle-kit /Users/utkarshanand/Development/personal/smart-form-wizard/packages/db<br>&gt; drizzle-kit &quot;introspect:pg&quot; &quot;--config=drizzle.config.ts&quot;</pre><pre>drizzle-kit: v0.20.14<br>drizzle-orm: v0.29.3</pre><pre>Custom config path was provided, using &#39;drizzle.config.ts&#39;<br>Reading config file &#39;/Users/utkarshanand/Development/personal/smart-form-wizard/packages/db/drizzle.config.ts&#39;<br>[✓] 8  tables fetched<br>[✓] 61 columns fetched<br>[✓] 0  enums fetched<br>[✓] 0  indexes fetched<br>[✓] 3  foreign keys fetched</pre><pre>[i] No SQL generated, you already have migrations in project<br>[✓] You schema file is ready ➜ drizzle/schema.ts 🚀</pre><p>this command will generate all schema and combine them into one file packages/db/drizzle/schema.ts</p><p>But I don’t want to define all schema into one file, instead, I will create separate schemas for each table and we will move this schema folder into src folder,</p><p>And create a index.ts file from where you are exporting all the schemas</p><pre>export * from &quot;./conversation&quot;;<br>export * from &quot;./form&quot;;<br>export * from &quot;./formField&quot;;<br>export * from &quot;./organization&quot;;<br>export * from &quot;./user&quot;;<br>export * from &quot;./workspace&quot;;</pre><p>After creating separated schemas my schema folder looks like below</p><pre>├── src<br>│   └── schema<br>│       ├── conversation.ts<br>│       ├── form.ts<br>│       ├── formField.ts<br>│       ├── index.ts<br>│       ├── organization.ts<br>│       ├── organizationMember.ts<br>│       ├── prismaMigrations.ts<br>│       ├── user.ts<br>│       └── workspace.ts<br>├── drizzle.config.ts<br>├── package.json<br>└── tsconfig.json</pre><p><strong>Validate schemas</strong></p><p>Before creating a migration file, we will ensure that our generated schemas are the same as we created on Prisma. For this, I will suggest and what I did is that validating one schema at a time.</p><p>Like I started with the workspace, Here I need to make some changes to make it work, This part may take some time for you to understand.</p><pre>import {<br>  boolean,<br>  integer,<br>  jsonb,<br>  pgTable,<br>  text,<br>  timestamp,<br>  varchar,<br>} from &quot;drizzle-orm/pg-core&quot;;<br><br>export const workspace = pgTable(&quot;Workspace&quot;, {<br>  id: text(&quot;id&quot;).primaryKey().notNull(),<br>  createdAt: timestamp(&quot;createdAt&quot;, { precision: 3, mode: &quot;string&quot; })<br>    .defaultNow()<br>    .notNull(),<br>  updatedAt: timestamp(&quot;updatedAt&quot;, { precision: 3, mode: &quot;string&quot; }).notNull(),<br>  name: text(&quot;name&quot;).notNull(),<br>  userId: text(&quot;userId&quot;).notNull(),<br>  organizationId: text(&quot;organizationId&quot;).notNull(),<br>});</pre><p>As you can see in below code, I have used @paralleldrive/cuid2 To create a unique ID, you need to add this to your package.json file.</p><pre>import { createId } from &quot;@paralleldrive/cuid2&quot;;<br>import { pgTable, text, timestamp } from &quot;drizzle-orm/pg-core&quot;;<br><br>export const workspace = pgTable(&quot;Workspace&quot;, {<br>  id: text(&quot;id&quot;)<br>    .primaryKey()<br>    .$defaultFn(() =&gt; createId())<br>    .unique(),<br>  createdAt: timestamp(&quot;createdAt&quot;).defaultNow().notNull(),<br>  updatedAt: timestamp(&quot;updatedAt&quot;).defaultNow().notNull(),<br>  name: text(&quot;name&quot;).notNull(),<br>  userId: text(&quot;userId&quot;),<br>  organizationId: text(&quot;organizationId&quot;).notNull(),<br>});</pre><p><strong>Creating types and validators</strong></p><p>We also want to create some validators and types to use in our app. For this, we will use drizzle-zod package, which you can install using the below command.</p><pre>pnpm add drizzle-zod zod</pre><p>Let&#39;s start with the workspace packages/db/src/schema/workspace.ts file,</p><pre>import { createId } from &quot;@paralleldrive/cuid2&quot;;<br>import { pgTable, text, timestamp } from &quot;drizzle-orm/pg-core&quot;;<br>import { createInsertSchema, createSelectSchema } from &quot;drizzle-zod&quot;;<br>import { z } from &quot;zod&quot;;<br><br>export const workspace = pgTable(&quot;Workspace&quot;, {<br>  id: text(&quot;id&quot;)<br>    .primaryKey()<br>    .$defaultFn(() =&gt; createId())<br>    .unique(),<br>  createdAt: timestamp(&quot;createdAt&quot;).defaultNow().notNull(),<br>  updatedAt: timestamp(&quot;updatedAt&quot;).defaultNow().notNull(),<br>  name: text(&quot;name&quot;).notNull(),<br>  userId: text(&quot;userId&quot;),<br>  organizationId: text(&quot;organizationId&quot;).notNull(),<br>});<br>export const insertWorkspaceSchema = createInsertSchema(workspace);<br>export const selectWorkspaceSchema = createSelectSchema(workspace);<br>export type Workspace = z.infer&lt;typeof selectWorkspaceSchema&gt;;</pre><p>As you can see in the above code, we have created two validators insertWorkspaceSchema , selectWorkspaceSchema and one type Workspace . so now we can use validators anywhere in the app like</p><pre>const workspace = insertWorkspaceSchema.parse(request.body);</pre><p>OR in my case, I am using a validator inside my workspace tRPC router, see in below code</p><pre>import { db } from &quot;@convoform/db&quot;;<br>import { insertWorkspaceSchema, workspace } from &quot;@convoform/db/src/schema&quot;;<br>import { createTRPCRouter, protectedProcedure } from &quot;../trpc&quot;;<br><br>export const workspaceRouter = createTRPCRouter({<br>  create: protectedProcedure<br>    .input(insertWorkspaceSchema)<br>    .mutation(async ({ input, ctx }) =&gt; {<br>      return await db<br>        .insert(workspace)<br>        .values({<br>          name: input.name,<br>          organizationId: input.organizationId,<br>          userId: ctx.userId,<br>        })<br>        .returning();<br>    }),<br>});</pre><p>We can use types like below</p><pre>import { Workspace } from &quot;@convoform/db/src/schema&quot;;<br><br>type Props = {<br>  workspace: Workspace,<br>};<br>export const WorkspaceHeader = ({ workspace }: Props) =&gt; {<br>  const currentWorkspaceId = workspace.id;<br>  // .... Rest component code<br>};</pre><p><strong>Create Migrations</strong></p><p>To generate migrations and apply the generated migrations, first, we need to create a Database client file which also will be used to make any query to the database.</p><p>Create a file db.ts inside src folder</p><pre>import { drizzle } from &quot;drizzle-orm/node-postgres&quot;;<br>import { Pool } from &quot;pg&quot;;<br>import * as schema from &quot;./schema&quot;;<br><br>const pool = new Pool({<br>  connectionString: process.env.DATABASE_URL,<br>});<br>export const db = drizzle(pool, { schema: schema });</pre><p>Now create a file migrate.ts on same src folder</p><pre>import { migrate } from &quot;drizzle-orm/node-postgres/migrator&quot;;<br>import { db } from &quot;./db&quot;;<br><br>async function main() {<br>  console.log(&quot;Running migrations&quot;);<br>  await migrate(db, { migrationsFolder: &quot;drizzle/migrations&quot; });<br>  console.log(&quot;Migrations finished&quot;);<br>}<br>main().catch((e) =&gt; {<br>  console.error(&quot;Error running migrations&quot;);<br>  console.error(e);<br>  process.exit(1);<br>});</pre><p>Now to generate the migrations, we will run the below command</p><pre>pnpm drizzle:generate-migration</pre><p>which will output something like the below 1 ↵</p><pre>&gt; @convoform/db@0.0.0 drizzle:generate-migration /Users/utkarshanand/Development/personal/smart-form-wizard/packages/db<br>&gt; drizzle-kit generate:pg --out drizzle/migrations --schema drizzle/schema/index.ts</pre><pre>drizzle-kit: v0.20.14<br>drizzle-orm: v0.29.3</pre><pre>6 tables<br>Conversation 8 columns 0 indexes 1 fks<br>Form 13 columns 0 indexes 1 fks<br>FormField 5 columns 0 indexes 1 fks<br>Organization 6 columns 0 indexes 0 fks<br>User 8 columns 0 indexes 0 fks<br>Workspace 6 columns 0 indexes 0 fks</pre><pre>[✓] Your SQL migration file ➜ drizzle/migrations/0000_demonic_ben_grimm.sql 🚀</pre><p>If you see in packages/db/drizzle/migrations folder there will be migrations files generated, Now to apply these migrations run the below command</p><pre>pnpm drizzle:apply-migration</pre><p>which will output like the below</p><pre>&gt; @convoform/db@0.0.0 drizzle:apply-migration /Users/utkarshanand/Development/personal/smart-form-wizard/packages/db<br>&gt; ts-node src/migrate</pre><pre>Running migrations<br>Migrations finished</pre><p>Your current current schema is synced with the database.</p><h3>Step 3. Using Drizzle schema</h3><p>Now we will try to query our database using Drizzle, keep in mind we have not removed any Prisma-related files yet, we can remove them only once we have tested all our schema files.</p><p>Let&#39;s start with using Drizzle for all workspace related query, So as I am using tRPC, I have a workspace router file which you can see below</p><pre>import { z } from &quot;zod&quot;;<br>import { createTRPCRouter, protectedProcedure } from &quot;../trpc&quot;;<br><br>export const workspaceRouter = createTRPCRouter({<br>  create: protectedProcedure<br>    .input(<br>      z.object({<br>        name: z.string().min(1),<br>        organizationId: z.string().min(1),<br>      }),<br>    )<br>    .mutation(async ({ input, ctx }) =&gt; {<br>      return await ctx.db.workspace.create({<br>        data: {<br>          name: input.name,<br>          organizationId: input.organizationId,<br>          userId: ctx.userId,<br>        },<br>      });<br>    }),<br>  getAll: protectedProcedure<br>    .input(<br>      z.object({<br>        organizationId: z.string().min(1),<br>      }),<br>    )<br>    .query(async ({ input, ctx }) =&gt; {<br>      console.log({ &quot;input.organizationId&quot;: input.organizationId });<br>      return await ctx.db.workspace.findMany({<br>        where: {<br>          organizationId: input.organizationId,<br>        },<br>        orderBy: {<br>          createdAt: &quot;asc&quot;,<br>        },<br>      });<br>    }),<br>  getOne: protectedProcedure<br>    .input(<br>      z.object({<br>        id: z.string().min(1),<br>      }),<br>    )<br>    .query(async ({ input, ctx }) =&gt; {<br>      return await ctx.db.workspace.findFirst({<br>        where: {<br>          id: input.id,<br>        },<br>      });<br>    }),<br>  delete: protectedProcedure<br>    .input(<br>      z.object({<br>        id: z.string().min(1),<br>      }),<br>    )<br>    .mutation(async ({ input, ctx }) =&gt; {<br>      return await ctx.db.workspace.delete({<br>        where: {<br>          id: input.id,<br>        },<br>      });<br>    }),<br>  patch: protectedProcedure<br>    .input(<br>      z.object({<br>        id: z.string().min(1),<br>        name: z.string().min(1),<br>      }),<br>    )<br>    .mutation(async ({ input, ctx }) =&gt; {<br>      return await ctx.db.workspace.update({<br>        where: {<br>          id: input.id,<br>        },<br>        data: {<br>          name: input.name,<br>        },<br>      });<br>    }),<br>});</pre><p>As you can see in the above code, I am accessing the DB client from the context provider ctx.db.workspace.create , So I will import the Drizzle db client here and use it like in the below code</p><pre>import { db, eq } from &quot;@convoform/db&quot;;<br>import { workspace } from &quot;@convoform/db/src/schema&quot;;<br>import { z } from &quot;zod&quot;;<br>import { createTRPCRouter, protectedProcedure } from &quot;../trpc&quot;;<br><br><br>export const workspaceRouter = createTRPCRouter({<br>  create: protectedProcedure<br>    .input(insertWorkspaceSchema)<br>    .mutation(async ({ input, ctx }) =&gt; {<br>      const [result] = await db<br>        .insert(workspace)<br>        .values({<br>          name: input.name,<br>          organizationId: input.organizationId,<br>          userId: ctx.userId,<br>        })<br>        .returning();<br>      if (!result) {<br>        throw new Error(&quot;Unable to create workspace&quot;);<br>      }<br>      return result;<br>    }),<br>  getAll: protectedProcedure<br>    .input(<br>      z.object({<br>        organizationId: z.string().min(1),<br>      }),<br>    )<br>    .query(async ({ input, ctx }) =&gt; {<br>      return await db.query.workspace.findMany({<br>        where: (workspace, { eq }) =&gt;<br>          eq(workspace.organizationId, input.organizationId),<br>        orderBy: (workspace, { asc }) =&gt; [asc(workspace.createdAt)],<br>      });<br>    }),<br>  getOne: protectedProcedure<br>    .input(<br>      z.object({<br>        id: z.string().min(1),<br>      }),<br>    )<br>    .query(async ({ input, ctx }) =&gt; {<br>      return await db.query.workspace.findFirst({<br>        where: eq(workspace.id, input.id),<br>      });<br>    }),<br>  delete: protectedProcedure<br>    .input(<br>      z.object({<br>        id: z.string().min(1),<br>      }),<br>    )<br>    .mutation(async ({ input, ctx }) =&gt; {<br>      return await db.delete(workspace).where(eq(workspace.id, input.id));<br>    }),<br>  patch: protectedProcedure<br>    .input(<br>      z.object({<br>        id: z.string().min(1),<br>        name: z.string().min(1),<br>      }),<br>    )<br>    .mutation(async ({ input, ctx }) =&gt; {<br>      const [updatedWorkspace] = await db<br>        .update(workspace)<br>        .set({ name: input.name })<br>        .where(eq(workspace.id, input.id))<br>        .returning();<br>      return updatedWorkspace;<br>    }),<br>});</pre><p>Now we have moved our one-entity workspace from Prisma to Drizzle, Same way we will move all the entities from Prisma to Drizzle.</p><p>Once you moved all the entities from Prisma to Drizzle, you can delete all files related to Prisma, and also remove the Prisma package from package.json .</p><p>For more details, you can see my <a href="https://github.com/growupanand/ConvoForm/pull/180">Pull request</a>.</p><p>GitHub repo — <a href="https://github.com/growupanand/ConvoForm">https://github.com/growupanand/ConvoForm</a></p><h3>Extra</h3><h3>The current timestamp is not auto-inserted in “updateAt” field!</h3><p>As we have modified the schema and added .defaultNow() in updatedAt field, But still it will not work or at least not for me. So this happened because in our database, the default value is not set yet for this field and in Prisma, it was working without setting the default value in the database, as you can see below screenshot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEQ__n0mnsHZDitQd4wgeg.png" /><figcaption>Screenshot of schema in database</figcaption></figure><p>So there are two solutions for this,</p><p>The first one is to manually add the default value for this in any database manager tool.</p><p>The second one is to just remove the .defaultNow() from the field and create a new migration, you can do this for all the tables at once. Once a new migration is generated, add this .defaultNow() again to the field and regenerate the migrations. Now you will see in the migration file it will add a default value to this field. Below is an example of that migration file</p><p>First generated migration file content after removing default value</p><pre>ALTER TABLE &quot;Workspace&quot; ALTER COLUMN &quot;updatedAt&quot; DROP DEFAULT;</pre><p>Second generated migration file content after adding back default value</p><pre>ALTER TABLE &quot;Workspace&quot; ALTER COLUMN &quot;updatedAt&quot; SET DEFAULT now();</pre><p>Now just apply the migration by running the below command</p><pre>pnpm drizzle:apply-migration</pre><p>and you will see that the default value for the “updatedAt” field is set for the current timestamp, as you can see in the below screenshot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ShtU0Ich7tBcyuBq15OD3g.png" /><figcaption>Screenshot of schema after adding default value for updatedAt</figcaption></figure><p><strong>How to use a database’s non-pool connection (or may be “localhost”) string?</strong></p><p>“Don’t connect”, Ya that’s what Drizzle said when I asked 🤣</p><p><a href="https://x.com/DrizzleORM/status/1755530959473045862?s=20">https://x.com/DrizzleORM/status/1755530959473045862?s=20</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//twitter.com/DrizzleORM/status/1755530959473045862%3Fs%3D20&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/b52cab16c04e8492eea8b8e5c4015556/href">https://medium.com/media/b52cab16c04e8492eea8b8e5c4015556/href</a></iframe><p>Finally, If you enjoyed this article, you can support ❤️ me by giving a star ⭐ to my <a href="https://github.com/growupanand/ConvoForm">ConvoForm</a> project on GitHub.</p><p><strong>Useful links</strong></p><ul><li><a href="https://tone-row.com/blog/drizzle-orm-quickstart-tutorial-first-impressions">https://tone-row.com/blog/drizzle-orm-quickstart-tutorial-first-impressions</a></li><li><a href="https://www.answeroverflow.com/m/1093225882879017080">https://www.answeroverflow.com/m/1093225882879017080</a></li><li><a href="https://github.com/t3-oss/create-t3-turbo">https://github.com/t3-oss/create-t3-turbo</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c290f8ed8ef3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transitioning from Monorepo to Turborepo: My Development Journey with ConvoForm.com]]></title>
            <link>https://medium.com/@growupanand/transitioning-from-monorepo-to-turborepo-my-development-journey-with-convoform-com-691b9d19f397?source=rss-e3e1505d1cc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/691b9d19f397</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[monorepo]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[turborepo]]></category>
            <dc:creator><![CDATA[Utkarsh Anand]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 15:22:20 GMT</pubDate>
            <atom:updated>2024-02-06T15:30:25.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CnFNBVn92xnUtF-op5MqsQ.png" /></figure><p>Hi, I am <a href="https://www.linkedin.com/in/utkarshanand93/">Utkarsh Anand</a>, This is the first article I am posting here. In this article, I am sharing my experience and some solutions to problems I faced while converting my Monorepo into Turborepo.</p><h3>About my project</h3><p>So recently I started an open-source side project ConvoForm (<a href="https://www.convoform.com/">convoform.com</a>), I started this to learn how to build a modern SaaS web app.</p><ul><li>Frontend — <strong>Next.js 14 (App Router)</strong></li><li>UI — <strong>shadcn/ui</strong></li><li>Backend — <strong>tRPC</strong></li><li>Database — <strong>Prisma</strong> with <strong>PostgreSQL</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsjc2JlKxinPVEm17jLlaA.png" /><figcaption>Screenshot of form editor</figcaption></figure><p>So this is just a simple form like Google Forms, While creating the form tell form fields of data you want to collect from the user, it could be one word like — name, email, or more descriptive like — “name of user”, “what is his contact number and email?”. Once you publish the form you will get a unique form submission link which you can share with anyone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4umnuUbhLwW1KwpyQa-rQ.png" /><figcaption>Screenshot of form submission page</figcaption></figure><p>Now come to the exciting part of this project, When the user visits the form submission link, Instead of just displaying all form fields on one page, It will do a conversation with the user by asking questions one by one for all the fields you provided, This improves the user experience throughout the entire form-filling process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nFHtt6slVQ8rPfbTvVHzcw.png" /><figcaption>Screenshot of form responses</figcaption></figure><p>After the user completes the submission of the form, you can see the data in table form and also with the transcript of the whole conversation.</p><p>Github repo link — <a href="https://github.com/growupanand/ConvoForm">https://github.com/growupanand/ConvoForm</a></p><p>Please use my product once, all kinds of feedback are welcome, whether it is positive or something I can improve.</p><h3>Why Turborepo?</h3><p>In my two years of working experience, I understood the value of Monorepo, and how it allows every commit change to be worked on the whole app, because the test cases, linting, and type checks can be performed on the whole repo for each commit.</p><p>So why do we need Turborepo, First of all, it can cache the pipeline tasks results like linting and type checks, and if you rerun the same tasks, it will replay the results if there is no change in the code.</p><p>For example, if you have already run linting successfully for the whole app, and then you work on a bug fix. So you make some changes inside the code in Frontend folder, now when you commit these changes you don’t want to run linting for the backend folder again. So Turborepo will skip linting on Backend folder. It is a very small example, but think how much time it will save if your whole process is taking a long time.</p><p>Another benefit of Turborepo is that you can split your codebase into small packages, which you can use in your main app by importing</p><pre>import { Button } from &quot;@convoform/ui/components/ui/button&quot;;</pre><p>In above @convoform/ui is a separate package folder in the same repo which have all the code related to design system components, like in my case I am using <a href="https://ui.shadcn.com/"><strong>shadcn/ui</strong></a><strong>.</strong> It will give you benefits if you have multiple frontend apps for your project example one is a marketing app, and the second is the main app. So you are using the same UI elements for both apps to make your design system sync with each other.</p><p>More benefits can be seen on their official site — <a href="https://turbo.build/repo">https://turbo.build/repo</a></p><h3>Project folder structure</h3><p><strong>Before Turborepo</strong></p><pre>├── prisma<br>│   └── migrations<br>├── public<br>├── src<br>│   ├── app<br>│   │   ├── (privatePage)<br>│   │   │   ├── (formEditorPage)<br>│   │   │   │   └── forms<br>│   │   │   │       └── [formId]<br>│   │   │   │           └── conversations<br>│   │   │   │               └── [conversationId]<br>│   │   │   └── (mainPage)<br>│   │   │       ├── dashboard<br>│   │   │       └── workspaces<br>│   │   │           └── [workspaceId]<br>│   │   ├── (publicPage)<br>│   │   │   ├── (formSubmissionPage)<br>│   │   │   │   └── view<br>│   │   │   │       └── [formId]<br>│   │   │   ├── (landingPage)<br>│   │   │   └── changelog<br>│   │   ├── api<br>│   │   │   ├── conversation<br>│   │   │   │   └── [conversationId]<br>│   │   │   ├── dashboard<br>│   │   │   ├── form<br>│   │   │   │   └── [formId]<br>│   │   │   │       ├── conversation<br>│   │   │   │       ├── conversations<br>│   │   │   │       ├── formFields<br>│   │   │   │       └── getNextFormField<br>│   │   │   ├── revalidate<br>│   │   │   ├── serverActions<br>│   │   │   ├── webhook<br>│   │   │   └── workspaces<br>│   │   │       └── [workspaceId]<br>│   │   │           └── forms<br>│   │   └── auth<br>│   │       ├── register<br>│   │       │   └── [[...sign-up]]<br>│   │       └── sign-in<br>│   │           └── [[...sign-in]]<br>│   ├── components<br>│   │   ├── changeLogPage<br>│   │   ├── common<br>│   │   ├── formEditorPage<br>│   │   │   ├── conversations<br>│   │   │   └── formEditor<br>│   │   ├── formSubmissionPage<br>│   │   ├── landingPage<br>│   │   ├── mainPage<br>│   │   │   ├── dashboard<br>│   │   │   ├── mainNavigation<br>│   │   │   └── workspace<br>│   │   ├── ui<br>│   │   └── wrappers<br>│   └── lib<br>│       ├── atoms<br>│       ├── config<br>│       ├── controllers<br>│       ├── data<br>│       ├── services<br>│       ├── types<br>│       └── validations<br>└── templates</pre><p><strong>After Turborepo</strong></p><pre>├── apps<br>│   └── web<br>│       ├── public<br>│       │   └── screenshots<br>│       └── src<br>│           ├── app<br>│           │   ├── (privatePage)<br>│           │   │   ├── (formEditorPage)<br>│           │   │   │   └── forms<br>│           │   │   │       └── [formId]<br>│           │   │   │           └── conversations<br>│           │   │   │               └── [conversationId]<br>│           │   │   ├── (mainPage)<br>│           │   │   │   ├── dashboard<br>│           │   │   │   └── workspaces<br>│           │   │   │       └── [workspaceId]<br>│           │   │   └── organizations<br>│           │   ├── (publicPage)<br>│           │   │   ├── (formSubmissionPage)<br>│           │   │   │   └── view<br>│           │   │   │       └── [formId]<br>│           │   │   ├── (landingPage)<br>│           │   │   └── changelog<br>│           │   ├── api<br>│           │   │   ├── form<br>│           │   │   │   └── [formId]<br>│           │   │   │       ├── conversation<br>│           │   │   │       └── getNextFormField<br>│           │   │   ├── og<br>│           │   │   │   └── _components<br>│           │   │   ├── revalidate<br>│           │   │   ├── trpc<br>│           │   │   │   └── [trpc]<br>│           │   │   └── webhook<br>│           │   └── auth<br>│           │       ├── register<br>│           │       │   └── [[...sign-up]]<br>│           │       └── sign-in<br>│           │           └── [[...sign-in]]<br>│           ├── components<br>│           │   ├── changeLogPage<br>│           │   ├── common<br>│           │   ├── formEditorPage<br>│           │   │   ├── conversations<br>│           │   │   └── formEditor<br>│           │   ├── formSubmissionPage<br>│           │   ├── landingPage<br>│           │   ├── mainPage<br>│           │   │   ├── dashboard<br>│           │   │   ├── mainNavigation<br>│           │   │   └── workspace<br>│           │   └── providers<br>│           ├── lib<br>│           │   ├── config<br>│           │   ├── controllers<br>│           │   ├── data<br>│           │   ├── services<br>│           │   ├── types<br>│           │   └── validations<br>│           └── trpc<br>├── packages<br>│   ├── api<br>│   │   └── src<br>│   │       ├── lib<br>│   │       ├── router<br>│   │       └── validators<br>│   ├── db<br>│   │   ├── prisma<br>│   │   │   └── migratio<br>│   │   └── src<br>│   ├── eslint-config<br>│   ├── tsconfig<br>│   └── ui<br>│       └── src<br>│           ├── components<br>│           │   └── ui<br>│           └── lib<br>└── templates</pre><h3>What challenges did I face while converting Monorepo into Turborepo?</h3><p>so if you are starting a new project from scratch you can create Turborepo easily, but if you have already developed your project you will get some errors while in this process. This is the <a href="https://github.com/growupanand/ConvoForm/pull/168">Pull request</a> where I made my Monorepo into Turborepo. I am not giving any tutorial here for this, you can find many good articles on the internet. I will tell you some of the challenges I faced which takes my large time.</p><p><strong>1. Next.js build error for prisma in turborepo</strong></p><pre>Type error: The inferred type of &#39;api&#39; cannot be named without a reference to<br>&#39;../../../../packages/db/node_modules/@prisma/client/runtime/library&#39;. This is likely not portable. A type annotation is necessary.</pre><p>This error took my whole day, I have searched it everywhere but nothing worked for me, So I will tell you how to get rid of this.</p><p>As you know we can create separate packages that can be used in apps, so when you create a db package where you put all the database schema and database ORM client-related code. So when you run it locally using dev there will be no problem. But once you try to build Next.js app it will throw this build error.</p><p>As you can see <a href="https://github.com/growupanand/ConvoForm/pull/171/files#diff-81a53351ab600445046df7eeb485a160a0a85090a7461055b02f42456d825790">here</a>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tp2tTx6UH8xqS1BmL6cHaQ.png" /></figure><p>You just need to use the generated client with a relative path, and if you noticed this client is generated inside the db package folder but not inside node_modules folder -packages/db/lib/generated/client . So to make Prisma generate this folder you need some changes inside your packages/db/prisma/schema.prisma , you can see <a href="https://github.com/growupanand/ConvoForm/pull/171/files#diff-1ea43e8384340cee4620b54fef2a3e78381bc63b2c4c228ef03b165ece17fe19">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jI2cWsh0Hpig-fPzcHP1jQ.png" /></figure><p>And don’t forget to make changes in packages/db/package.json too, see <a href="https://github.com/growupanand/ConvoForm/pull/171/files#diff-c89735ad606b83e822d493ca765a37afb7fcd2e5621f828a2cfc984ed5e67367">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XFiOETP0HQ8wlKVA-lMu2w.png" /></figure><p><strong>2. Prisma client not working on production</strong></p><p>After building success on Vercel when you open your website, It will throw an error at runtime in the browser, Prisma Client could not locate the Query Engine for runtime &quot;debian-openssl-3.0.x&quot;</p><p>As you can see <a href="https://github.com/growupanand/ConvoForm/pull/174">here</a>, you just need to use PrismaPlugin inside apps/web/next.config.mjs,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gwy-nAeW6reXoSqjH0fOzw.png" /></figure><p><strong>3. Vercel build not working</strong></p><p>So for your existing project on vercel, if you try to deploy changes the build will failed because now all the folder structure is changed and vercel is not able to find build folder. You can easily fix it by modify your vercel build command in either apps/web/vercel.json file located in your project repo or in vercel web UI page setting for the project.</p><pre>{<br>  &quot;buildCommand&quot;: &quot;cd ../.. &amp;&amp; pnpm build&quot;,<br>  &quot;outputDirectory&quot;: &quot;.next&quot;<br>}</pre><p>Don’t forget to tell vercel where your Next.js app can be found, for this just give apps/web your root directory like in below screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jrWGwVF_KT3HPgjDV-ww6A.png" /></figure><p>Please comment if you found any more errors because I have put here only those that take my much time.</p><p>Finally <a href="https://www.youtube.com/watch?v=SDQ87x14atM">here</a> is a video of visualization which represents my contribution and my project structure. As you can see at the end of the video how the structure looks better.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSDQ87x14atM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSDQ87x14atM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSDQ87x14atM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c24426ccb95848593ae1d2631bb794f/href">https://medium.com/media/5c24426ccb95848593ae1d2631bb794f/href</a></iframe><p><strong>Some useful links and repos which helped me:</strong></p><ul><li><a href="https://github.com/openstatusHQ/openstatus">https://github.com/openstatusHQ/openstatus</a> — A very good open-source repo for Next.js</li><li><a href="https://gist.github.com/mkcode/a590d1c8f7b0a37b8299965de7f7e958">https://gist.github.com/mkcode/a590d1c8f7b0a37b8299965de7f7e958</a> — Nice gist which has all the code for Next App Router + Clerk + tRPC</li></ul><p><strong>What’s next?</strong></p><p>So now I am working on moving<strong> from Prisma to Drizzle</strong>, I will post a new article for this also.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=691b9d19f397" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>