Connect a Next.js application to Neon
Set up a Neon project in seconds and connect from a Next.js application
Next.js by Vercel is an open-source web development framework that enables React-based web applications. This topic describes how to create a Neon project and access it from a Next.js application.
To create a Neon project and access it from a Next.js application:
- Create a Neon project
- Create a Next.js project and add dependencies
- Configure a Postgres client
- Run the app
Create a Neon project
If you do not have one already, create a Neon project. Save your connection details including your password. They are required when defining connection settings.
- Navigate to the Projects page in the Neon Console.
- Click New Project.
- Specify your project settings and click Create Project.
Create a Next.js project and add dependencies
-
Create a Next.js project if you do not have one. For instructions, see Create a Next.js App, in the Vercel documentation.
-
Add project dependencies using one of the following commands:
Store your Neon credentials
Add a .env
file to your project directory and add your Neon connection string to it. You can find the connection string for your database in the Connection Details widget on the Neon Dashboard. For more information, see Connect from any application.
DATABASE_URL=postgres://[user]:[password]@[neon_hostname]/[dbname]
Configure the Postgres client
There a multiple ways to make server side requests with Next.js. See below for the different implementations.
App Router
There are two methods for fetching and mutating data using server-side requests in Next.js App Router, they are:
Server Components
fetches data at runtime on the server.Server Actions
functions executed on the server to perform data mutations.
Server Components
In your server components using the App Router, add the following code snippet to connect to your Neon database:
import { neon } from '@neondatabase/serverless';
async function getData() {
const sql = neon(process.env.DATABASE_URL);
const response = await sql`SELECT version()`;
console.log(response);
return response;
}
export default async function Page() {
const data = await getData();
}
Server Actions
In your server actions using the App Router, add the following code snippet to connect to your Neon database:
import { neon } from '@neondatabase/serverless';
export default async function Page() {
async function create(formData: FormData) {
"use server";
const sql = neon(process.env.DATABASE_URL);
await sql`CREATE TABLE IF NOT EXISTS comments (comment TEXT)`;
const comment = formData.get("comment");
await sql("INSERT INTO comments (comment) VALUES ($1)", [comment]);
}
return (
<form action={create}>
<input type="text" placeholder="write a comment" name="comment" />
<button type="submit">Submit</button>
</form>
);
}
Pages Router
There are two methods for fetching data using server-side requests in Next.js Pages Router, they are:
getServerSideProps
fetches data at runtime so that content is always fresh.getStaticProps
pre-renders pages at build time for data that is static or changes infrequently.
getServerSideProps
From getServerSideProps
using the Pages Router, add the following code snippet to connect to your Neon database:
import { neon } from '@neondatabase/serverless';
export async function getServerSideProps() {
const sql = neon(process.env.DATABASE_URL);
const response = await sql`SELECT version()`;
console.log(response);
return { props: { data: response } };
}
export default function Page({ data }) {}
getStaticProps
From getStaticProps
using the Pages Router, add the following code snippet to connect to your Neon database:
import { neon } from '@neondatabase/serverless';
export async function getServerSideProps() {
const sql = neon(process.env.DATABASE_URL);
const response = await sql`SELECT version()`;
console.log(response);
return { props: { data: response } };
}
export default function Page({ data }) {}
Serverless Functions
From your Serverless Functions, add the following code snippet to connect to your Neon database:
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL);
export default async function handler(req, res) {
const response = await sql`SELECT version()`;
console.log(response);
res.status(200).json({
data: response,
});
}
Edge Functions
From your Edge Functions, add the following code snippet and connect to your Neon database using the Neon serverless driver:
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL);
export default async function handler(req, res) {
const response = await sql`SELECT version()`;
console.log(response);
return Response.json({
data: response,
});
}
export const config = {
runtime: 'edge',
};
Run the app
When you run npm run dev
you can expect to see one of the following in your terminal output:
# node-postgres & Neon serverless driver
{
version: 'PostgreSQL 16.0 on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit'
}
# postgres.js
Result(1) [
{
version: 'PostgreSQL 16.0 on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit'
}
]
Need help?
Join our Discord Server to ask questions or see what others are doing with Neon. Users on paid plans can open a support ticket from the console. For more detail, see Getting Support.
Last updated on