Course Content
Next.js 14
Next.js 14
How to Fetch Data
Let's discuss the different methods of retrieving data in Next.js.
API Layer
An API layer acts as a bridge between your application code and the database. You might consider using an API in the following situations:
- Third-party Services: If you're integrating 3rd party services that offer an API;
- Client-Side Data Fetching: When fetching data from the client, it's crucial to have an API layer on the server. This helps in keeping your database secrets secure, preventing exposure to the client.
Database Queries
In a full-stack application, you'll also need to handle interactions with your database. For relational databases like Postgres, you can accomplish this using SQL or an ORM like Prisma. Cases where you need to write database queries include:
- API Endpoint Creation: When developing your API endpoints, you must write logic to interact with the database;
- React Server Components: If you're using React Server Components and fetching data on the server, you can bypass the API layer. This allows you to query your database directly without risk exposing sensitive information to the client.
In our Project
We will use SQL with the Vercel Postgres SDK for a few reasons:
- SQL is the standard for querying relational databases;
- Learning SQL helps you understand the basics of databases, applicable to various tools;
- SQL is versatile for fetching and manipulating specific data;
- The Vercel Postgres SDK protects against SQL injections, ensuring secure queries.
Thanks for your feedback!