Hi, I'm new to building full projects with Next.js and want to understand common approaches to file structure. I'm currently building a website with create/submit/update features using Supabase. Should I create a separate api/[function]/route.ts for each action, or is it better to have a shared libs/projectServices.ts? Any advice or best practices would be appreciated.
#Next.js File Structures
1 messages · Page 1 of 1 (latest)
Hi @tiny gazelle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Great question! Next.js is flexible and unopinionated about project structure, but there are some common patterns and best practices you can follow, especially when building apps with create/submit/update features and integrating with services like Supabase.
API Route Structure
For actions like create, submit, and update, it's common to create a separate API route for each resource or logical grouping, not necessarily for each action. For example, you might have:
app/
api/
posts/
route.ts // Handles GET, POST for posts
posts/
[id]/
route.ts // Handles GET, PUT, DELETE for a specific post
Within each route.ts, you can export different handlers for HTTP methods (GET, POST, PUT, DELETE, etc.):
// app/api/posts/route.ts
export async function GET(request: Request) { /* ... */ }
export async function POST(request: Request) { /* ... */ }
This approach keeps your API organized by resource, and each file can handle multiple actions via HTTP methods. This is the recommended pattern in the Next.js documentation for the App Router (see example).
Shared Logic with lib or services
For shared logic (like interacting with Supabase), it's best practice to create a separate file (e.g., lib/projectServices.ts or lib/supabase.ts) where you encapsulate your database logic. Then, you can import and use these functions in your API route handlers. This keeps your code DRY and maintainable:
lib/
projectServices.ts // Shared functions for interacting with Supabase
app/
api/
posts/
route.ts
This pattern is explicitly mentioned as a common strategy in the docs, where folders like lib, utils, or services are used for shared logic, and their naming has no special framework significance—choose what works for your team and be consistent see examples.
Summary of Best Practices
- Group API routes by resource (not by action): Use HTTP methods within each route file.
- Encapsulate shared logic in a
lib/orservices/folder and import it into your route handlers. - Be consistent with your folder naming and structure across your project.
Next.js is unopinionated about file structure, but these patterns are widely used and recommended in the official documentation Organizing your project.