Database Connection
In this chapter, we'll learn how to connect Next.js apps to databases. By understanding database integration in this chapter, you'll complete the knowledge needed for building professional dashboards.
Database Connection Overview
To connect a dashboard built with Next.js to an actual database, you need to send queries to the database using database connection information. However, if you write connection information (secret keys or connection strings) directly in source code, it could be committed to Git and cause leaks.
Therefore, we use a mechanism called environment variables. Environment variables allow you to inject information you don't want to write directly in source code at runtime.
Environment Variable Configuration
In development environments, environment variables are set using a .env
file. The format is [ENVIRONMENT_VARIABLE_NAME]=[VALUE]
as follows:
DATABASE_URL=postgresql://user:password@host:5432/database
In the template we're using, the .env file is configured not to be committed to Git.
PostgreSQL Connection
PostgreSQL is the most widely used open-source database. For example, Supabase and Neon are services that provide cloud-based PostgreSQL. Learning how to connect to PostgreSQL allows you to integrate with these popular database services.
There are various ways to connect PostgreSQL with Next.js, but we'll introduce the method using Connection String.
First, let's set environment variables. Set the Connection String provided by your PostgreSQL service (Supabase or Neon) as an environment variable.
DATABASE_URL=postgresql://user:password@host:5432/database
Once this is done, give Claude Code instructions like this (the customers table
in the prompt is an example - replace it with your actual database table name):
Please create a page that displays a list of the PostgreSQL customers table in table format.
Connection information is described in the .env file.
PostgreSQL queries should be executed in api routes, and the frontend should call the api routes.
Please add a page link to the sidebar.
Has a page like this been created?
This implementation is somewhat complex, so you might get errors initially. When that happens, copy and paste the error message to Claude Code and report it - you should be able to resolve it through several exchanges.
Review
In this chapter, we learned how to connect Next.js apps to databases. Even if the type of database you connect to changes, the basic approach and implementation flow remain the same. Try setting up database connections according to your or your organization's needs.