How do I connect PostgreSQL database to Express.js API in Vercel?

I have an Express.js API running on Vercel with a PostgreSQL storage, but I can’t get them to connect. My pool configuration in the API is as follows:

const { Pool } = require('pg');

const pool = new Pool({
    user: process.env.DB_USER,
    host: process.env.DB_HOST,
    database: process.env.DB_NAME,
    password: process.env.DB_PASSWORD,
    port: process.env.DB_PORT
});
module.exports = pool;

Do I need more pool configurations and I don’t know about them? This is my first complete project, it’s a real estate website using SvelteKit, Express.js, and PostgreSQL. I’m new to hosting.

Hi, @kaianguedes!

Thank you for your question!

When you create a Vercel Postgres database, Vercel automatically adds environment variables to your project. These are different from the ones in your current configuration, they are:

  • POSTGRES_URL: The connection string for your database
  • POSTGRES_PRISMA_URL: The connection string with connection pooling (for use with Prisma)
  • POSTGRES_URL_NON_POOLING: The connection string without connection pooling
  • POSTGRES_USER
  • POSTGRES_HOST
  • POSTGRES_PASSWORD
  • POSTGRES_DATABASE

You can update your pool configuration to use these Vercel-provided variables:

const { Pool } = require('pg');

const pool = new Pool({
  connectionString: process.env.POSTGRES_URL,
});

module.exports = pool;

You mentioned using SvelteKit along with Express.js and PostgreSQL. Typically, SvelteKit can handle both frontend and API routes, so a separate Express.js backend might not be necessary. If you’re using both, ensure your Vercel deployment is configured correctly to handle this setup.

Here are some helpful information in case you need it:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.