Skip to content

Latest commit

 

History

History
38 lines (19 loc) · 1.62 KB

DB-Fetching-Data.md

File metadata and controls

38 lines (19 loc) · 1.62 KB

Fetching Data

API layer

APIs are an intermediary layer between application code and database.
There are a few cases where you might use an API:

  • If you're using 3rd party services that provide an API.
  • If you're fetching data from the client
    • you want to have an API layer that runs on the server to avoid exposing your database secrets to the client

In Next.js, you can create API endpoints using Route Handlers. They allow you to create custom request handlers for a given route using the Web Request and Response APIs.

Good to know: Route Handlers are only available inside the app directory. They are the equivalent of API Routes inside the pages directory meaning you do not need to use API Routes and Route Handlers together.

Database queries

When you're creating a full-stack application, you'll also need to write logic to interact with your database. For relational databases like Postgres, you can do this with SQL, or an ORM like Prisma.
There are a few cases where you have to write database queries:

  • When creating your API endpoints, you need to write logic to interact with your database.
  • If you are using React Server Components (fetching data on the server),
    • you can skip the API layer, and query your database directly without risking exposing your database secrets to the client.

By default, Next.js applications use React Server Components.