I'm trying to figure out the best approach for running database queries in Next.js APIs. The official docs suggest creating separate files under /api for handling requests, but that seems like a lot of overhead and requires executing raw SQL, which isn't ideal. I've seen others mentioning libraries like Drizzle, so I'm curious: what's the industry standard here? I want to learn the best practices. Is there a lightweight solution for basic fetch and post queries that avoids complex business logic?
4 Answers
Don't stress about the number of files you create; using API routes is a smart choice for lightweight tasks. Alternatively, using an ORM like Drizzle or Prisma can also be a great fit!
Check out Supabase! You can run database queries directly from your frontend safely, provided you have the right Row Level Security (RLS) configuration. For any complicated logic, you can use an edge function or a simple API route in your Next.js setup. That’s what I’m doing in my current project, and it’s working out nicely.
Honestly, just build your data layer and internal APIs as you usually would and call them in your route handlers or server actions. There's nothing particularly special about database queries in Next.js; just stick to standard practices. Choosing whether or not to use an ORM is mostly about your specific implementation needs.
For straightforward tasks, keep it simple! In Next.js, many developers lean towards using Prisma or Drizzle within their API routes. This helps you to maintain focus on each route's purpose. As your project scales, you can then think about setting up a more structured backend. Starting light is perfectly fine, just ensure you're not exposing raw SQL directly.
Related Questions
Cloudflare Origin SSL Certificate Setup Guide
How To Effectively Monetize A Site With Ads