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.
Drizzle with Netlify Edge Functions and Supabase Database
This tutorial demonstrates how to use Drizzle ORM with Netlify Edge Functions and Supabase Database database.
- 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 i drizzle-orm
npm i -D drizzle-kit
- You should have installed the
dotenvpackage for managing environment variables. If you use Node.jsv20.6.0or later, there is no need to install it because Node.js natively supports.envfiles. Read more about it here.
npm i dotenv
- Optionally, you can install the
@netlify/edge-functionspackage to import the types for theContextobject which will be used later.
npm i @netlify/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.
import type { Context } from "@netlify/edge-functions";
export default async (request: Request, context: Context) => {
return new Response("User data");
};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:
{
"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:
[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:
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:
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 pushAlternatively, 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:
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));
};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 devWhen 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 initAnswer 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 .envRead more about Netlify environment variables here.
Deploy your project
Run the following command to deploy your project:
netlify deployFollow 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 --prodFinally, you can use URL of the deployed website and navigate to the route you created (e.g. /user) to access your edge function.