Tutorial
1 min read

Getting Started with Vercel Postgres

You can get started with writing to and reading data from Vercel Postgres by following this quickstart guide.
Table of Contents

Vercel Postgres is available on Hobby and Pro plans

This page will walk you through setting up basic API routes that use Vercel Postgres.

If you'd prefer to deploy a template, head to the Templates section.

To follow this quickstart, you'll need the following:

  • An existing Vercel Project
  • The Vercel Postgres package
    pnpm
    yarn
    npm
    pnpm i @vercel/postgres
  • The latest version of Vercel CLI
    pnpm
    yarn
    npm
    pnpm i -g vercel@latest

In this quickstart, you'll use Vercel Postgres SDK to create a database of you and your friends' pets.

You'll learn to:

  • Create a Postgres database that's connected to one of your projects
  • Create and manage the database in your dashboard on Vercel
  • Populate the database using Vercel's Postgres SDK
  • Send the contents of a PostgreSQL table as a response when someone visits one of your API routes

To get started, let's create a database.

  1. In your dashboard on Vercel, create or select the project you want to work with
  2. Select the Storage tab, then select the Connect Store button
  3. Select Postgres
  4. Enter a database name. It can only contain alphanumeric letters (including "_" and "-") and can't exceed 32 characters. We'll choose pets_postgres_db
  5. Select a region. If your project has Edge or Serverless Functions, choose an option near their regions for faster responses
  6. Select Create and Continue
  7. In the next view, change nothing and select Connect

You now have an empty PostgreSQL database in your selected region!

To connect to your database with Vercel Postgres SDK, you need a few credentials. By connecting your database to a project, those credentials are generated and made available as environment variables:

  • POSTGRES_URL
  • POSTGRES_PRISMA_URL
  • POSTGRES_URL_NON_POOLING
  • POSTGRES_USER
  • POSTGRES_HOST
  • POSTGRES_PASSWORD
  • POSTGRES_DATABASE

You can see them by navigating to the Settings tab in your project and selecting the Environment Variables panel.

When you created your Postgres database and connected it to your project, your API URL and credentials were added to the project as environment variables automatically. You'll need to pull them into your local environment to access your Postgres database.

In your terminal, run:

vercel env pull .env.development.local

Next, let's create an API route that, when visited, creates a Pets table in your database. It will hold very basic information about your pets.

In the app/api directory, create create-pets-table/route.ts, and add the following contents to the route file:

Next.js (/app)
Next.js (/pages)
Other frameworks
app/api/create-pets-table/route.ts
import { sql } from '@vercel/postgres';
import { NextResponse } from 'next/server';
 
export async function GET(request: Request) {
  try {
    const result =
      await sql`CREATE TABLE Pets ( Name varchar(255), Owner varchar(255) );`;
    return NextResponse.json({ result }, { status: 200 });
  } catch (error) {
    return NextResponse.json({ error }, { status: 500 });
  }
}

Then, create your Pets table by visiting the API route we've just created:

  1. Run next dev to start your app locally
  1. Visit the route's path in your app: http://localhost:3000/api/create-pets-table

You should see something like this in your browser:

{
  "result": {
  "command": "CREATE",
  "fields": [],
  "rowAsArray": false,
  "rowCount": null,
  "rows": [],
  "viaNeonFetch": true
  }
};

You can see the table in your Vercel dashboard as well. In your project's Storage tab, select your database, then select Data on the next page. Search for your table name and select it in the dropdown list. It should be empty.

Now that our table exists, let's add some data.

The following API route:

  1. Adds a new row to your PostgreSQL database with both the ownerName and petName fields taken from the query string in the URL when the route is visited
  2. Returns the contents of the entire table

Add this file to your project:

Next.js (/app)
Next.js (/pages)
Other frameworks
app/api/add-pet/route.ts
import { sql } from '@vercel/postgres';
import { NextResponse } from 'next/server';
 
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const petName = searchParams.get('petName');
  const ownerName = searchParams.get('ownerName');
 
  try {
    if (!petName || !ownerName) throw new Error('Pet and owner names required');
    await sql`INSERT INTO Pets (Name, Owner) VALUES (${petName}, ${ownerName});`;
  } catch (error) {
    return NextResponse.json({ error }, { status: 500 });
  }
 
  const pets = await sql`SELECT * FROM Pets;`;
  return NextResponse.json({ pets }, { status: 200 });
}

Isn't it a security risk to embed text into SQL queries? – Not in this case. Vercel sanitizes all queries sent to your Vercel Postgres database before executing them. The above code does not expose you to SQL injections.

To send data to your database, you must visit the route:

  1. Run next dev to start your app locally
  1. Add data to the query params when you visit your route. Here's an example URL that adds a pet named Fluffy with an owner named John to your database:

You should see something like this in your browser:

{
  pets: {
    command: "SELECT",
    fields: [
      {
        columnID: 1,
        dataTypeID: 1043,
        dataTypeModifier: 259,
        dataTypeSize: -1,
        format: "text",
        name: "name",
        tableID: 12345,
      },
      {
        columnID: 2,
        dataTypeID: 1043,
        dataTypeModifier: 259,
        dataTypeSize: -1,
        format: "text",
        name: "owner",
        tableID: 12345,
      },
    ],
    rowCount: 1,
    rows: [
      {
        name: "Fluffy",
        owner: "John",
      },
    ],
    viaNeonFetch: true,
  },
};

And in your dashboard, under the Data tab when you view your database, you can search for the Pets table to see the pets and owners you've added.

You now have API routes that create a table in your PostgreSQL database and add data to it!

To learn more about using Vercel Postgres in your projects, read our SDK reference.

Last updated on April 24, 2024