NeonN
Neon5mo ago
2 replies
wet-aqua

Transactions in nextjs 15 + Vercel with neon serverless driver

Ohio,

We use neon (paid) and drizzle in our deployed next 15 app deployed on vercel. Ive read the other posts pertaining to transactions and want some clarification:
In the following docs: https://github.com/neondatabase/serverless?tab=readme-ov-file#transaction it explains to either use the Pool or Client when you want interactive transactions. My question is simply, do the Pool or Client methods have to be used from an vercel fn (what the examples in GitHub show)? Or can it also be used from a server action or API route as long as you manage the connection properly? We tend to use server actions for any mutations we perform in our APP that we don't need in our API. So when I say server action I mean just a fn:

And also, is this how a connection should look via drizzle-orm for transactions local to the server action/api route? For example if we're in a nextjs api route, do we need to give it any websocket configuration?

"use server"

import { Pool } from '@neondatabase/serverless';
import { drizzle } from 'drizzle-orm/neon-serverless';

export async function do_something_with_transaction(args): Promise<void> {
  // is this db creation correct for drizzle when we want transactions
  const pool = new Pool({ connectionString: env.DATABASE_URL });
  const db = drizzle({ client: pool });

  try {
    await db.transaction(async tx => {
      // do thing 1:
      // await tx.insert(...).values({...})

      // update thing 2:
      // await tx.update(...).values({...})
    });
  } finally {
    await pool.end();
  }
}


// SomeComponent.tsx
// client side would happen via event handler:
const onSubmit = async () {
 return do_something_with_transaction().
     then(() => toast('success', "thing done!!").
     catch(() => toast('failure', "thing failed!")
}


Any insight is greatly appreciated!!
GitHub
Connect to Neon PostgreSQL from serverless/worker/edge functions - neondatabase/serverless
GitHub - neondatabase/serverless: Connect to Neon PostgreSQL from s...
Was this page helpful?