Drizzle with Netlify Edge Functions and Supabase Database

This tutorial demonstrates how to use Drizzle ORM with Netlify Edge Functions and Supabase Database database.

This guide assumes familiarity with:
  • You should have the latest version of Netlify CLI installed.
  • You should have installed Drizzle ORM and Drizzle kit. You can do this by running the following command:
npm
yarn
pnpm
bun
npm i drizzle-orm
npm i -D drizzle-kit
  • You should have installed the dotenv package for managing environment variables. If you use Node.js v20.6.0 or later, there is no need to install it because Node.js natively supports .env files. Read more about it here.
npm
yarn
pnpm
bun
npm i dotenv
  • Optionally, you can install the @netlify/edge-functions package to import the types for the Context object which will be used later.
npm
yarn
pnpm
bun
npm i @netlify/edge-functions
IMPORTANT

These installed packages are used only to create table in the database in Create a table, Setup Drizzle config file and Apply changes to the database steps. These packages do not affect the code running inside Netlify Edge Functions. We will use import_map.json to import the necessary packages for the Edge Functions.

Create a new Supabase project

You can create new Supabase project in the dashboard or by following this link.

Setup connection string variable

You can find Project connect details by clicking Connect in the top bar of the dashboard and copy the URI from the Transaction pooler section. Remember to replace the password placeholder with your actual database password.

Add DATABASE_URL variable to your .env file.

DATABASE_URL=<YOUR_DATABASE_URL>

Read more about connecting to Supabase Database in the documentation.

Setup Netlify Edge Functions

Create netlify/edge-functions directory in the root of your project. This is where you’ll store your Edge Functions.

Create a function user.ts in the netlify/edge-functions directory.

netlify/edge-functions/user.ts
import type { Context } from "@netlify/edge-functions";

export default async (request: Request, context: Context) => {
  return new Response("User data");
};
IMPORTANT

The types for the Request and Response objects are in the global scope.

Setup imports

Create a import_map.json file in the root of your project and add the following content:

import_map.json
{
  "imports": {
    "drizzle-orm/": "https://esm.sh/drizzle-orm/",
    "postgres": "https://esm.sh/postgres"
  }
}

Read more about import_map.json in Netlify Edge Functions here.

Create a Netlify configuration file

Create a netlify.toml file in the root of your project and add the following content:

netlify.toml
[functions]
  deno_import_map = "./import_map.json"

[[edge_functions]]
  path = "/user"
  function = "user"

This configuration tells Netlify to use the import_map.json file for Deno imports and to route requests to the /user path to the user.ts function. Read more about netlify.toml here.

Create a table

Create a schema.ts file in the netlify/edge-functions/common directory and declare a table schema:

netlify/edge-functions/common/schema.ts
import { pgTable, serial, text, integer } from "drizzle-orm/pg-core";

export const usersTable = pgTable('users_table', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
  age: integer('age').notNull(),
  email: text('email').notNull().unique(),
})

Setup Drizzle config file

Drizzle config - a configuration file that is used by Drizzle Kit and contains all the information about your database connection, migration folder and schema files.

Create a drizzle.config.ts file in the root of your project and add the following content:

drizzle.config.ts
import 'dotenv/config'; // remove this line if you use Node.js v20.6.0 or later
import type { Config } from "drizzle-kit";

export default {
  schema: './netlify/edge-functions/common/schema.ts',
  out: './drizzle',
  dialect: 'postgresql',
  dbCredentials: {
    url: process.env.DATABASE_URL!,
  },
} satisfies Config;

In this tutorial we will use Drizzle kit to push changes to the Neon database.

Apply changes to the database

npx drizzle-kit push
IMPORTANT
Push command is good for situations where you need to quickly test new schema designs or changes in a local development environment, allowing for fast iterations without the overhead of managing migration files.

Alternatively, you can use migrations workflow. Read about it here: Migrations.

Connect Drizzle ORM to your database

Update your netlify/edge-functions/user.ts file and set up your database configuration:

netlify/edge-functions/user.ts
import type { Context } from "@netlify/edge-functions";
import { usersTable } from "./common/schema.ts";
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';

export default async (request: Request, context: Context) => {
  const queryClient = postgres(Netlify.env.get("DATABASE_URL")!);
  const db = drizzle({ client: queryClient });

  const users = await db.select().from(usersTable);

  return new Response(JSON.stringify(users));
};
IMPORTANT

You might see a red underline under the imports if you’re using VS Code. The Edge Function will still execute. To get rid of the red underline, you can configure VS Code to use Edge Functions in the next step.

Test your code locally

Run the following command to start the Netlify dev server:

netlify dev

When you first run the command it will suggest to configure VS Code to use Edge Functions. Click Yes to configure it. settings.json file will be created in the .vscode directory. If you still see red underlines, you can restart the Deno Language Server.

Open your browser and navigate to the route /user. You should see the user data returned from the Neon database:

[]

It could be an empty array if you haven’t added any data to the users_table table.

Initialize a new Netlify project

Run the following command to initialize a new Netlify project:

netlify init

Answer the questions in the CLI to create a new Netlify project. In this tutorial, we will choose Yes, create and deploy site manually -> <YOUR_TEAM> -> <SITE_NAME>.

Setup Netlify environment variables

Run the following command to import your environment variables into Netlify:

netlify env:import .env

Read more about Netlify environment variables here.

Deploy your project

Run the following command to deploy your project:

netlify deploy

Follow the instructions in the CLI to deploy your project to Netlify. In this tutorial our publish directory is '.'.

It is a draft deployment by default. To do a production deployment, run the following command:

netlify deploy --prod

Finally, you can use URL of the deployed website and navigate to the route you created (e.g. /user) to access your edge function.