With Drizzle, you can enable Row-Level Security (RLS) for any Postgres table, create policies with various options, and define and manage the roles those policies apply to.
Drizzle supports a raw representation of Postgres policies and roles that can be used in any way you want. This works with popular Postgres database providers such as Neon and Supabase.
In Drizzle, we have specific predefined RLS roles and functions for RLS with both database providers, but you can also define your own logic.
Enable RLS
IMPORTANT
How it works in 0.x versions
If you just want to enable RLS on a table without adding policies, you can use .enableRLS()
As mentioned in the PostgreSQL documentation:
If no policy exists for the table, a default-deny policy is used, meaning that no rows are visible or can be modified.
Operations that apply to the whole table, such as TRUNCATE and REFERENCES, are not subject to row security.
Starting from v1.0.0-beta.1.enableRLS() is deprecated and
if you just want to enable RLS on a table without adding policies, you can use pgTable.withRLS(...)
As mentioned in the PostgreSQL documentation:
If no policy exists for the table, a default-deny policy is used, meaning that no rows are visible or can be modified.
Operations that apply to the whole table, such as TRUNCATE and REFERENCES, are not subject to row security.
If a role already exists in your database, and you don’t want drizzle-kit to ‘see’ it or include it in migrations, you can mark the role as existing.
import { pgRole } from 'drizzle-orm/pg-core';export const admin = pgRole('admin').existing();
Policies
To fully leverage RLS, you can define policies within a Drizzle table.
info
In PostgreSQL, policies should be linked to an existing table. Since policies are always associated with a specific table, we decided that policy definitions should be defined as a parameter of pgTable
Specifies the role to which the policy applies. Possible values include public, current_role, current_user, session_user, or any other role name as a string. You can also reference a pgRole object.
for
Defines the commands this policy will be applied to. Possible values are all, select, insert, update, delete.
using
The SQL statement that will be applied to the USING part of the policy creation statement.
withCheck
An SQL statement that will be applied to the WITH CHECK part of the policy creation statement.
Link Policy to an existing table
There are situations where you need to link a policy to an existing table in your database.
The most common use case is with database providers like Neon or Supabase, where you need to add a policy
to their existing tables. In this case, you can use the .link() API
import { sql } from "drizzle-orm";import { pgPolicy } from "drizzle-orm/pg-core";import { authenticatedRole, realtimeMessages } from "drizzle-orm/supabase";export const policy = pgPolicy("authenticated role insert policy", { for: "insert", to: authenticatedRole, using: sql``,}).link(realtimeMessages);
Migrations
If you are using drizzle-kit to manage your schema and roles, there may be situations where you want to refer to roles that are not defined in your Drizzle schema. In such cases, you may want drizzle-kit to skip managing these roles without having to define each role in your drizzle schema and marking it with .existing().
In these cases, you can use entities.roles in drizzle.config.ts. For a complete reference, refer to the the drizzle.config.ts documentation.
By default, drizzle-kit does not manage roles for you, so you will need to enable this feature in drizzle.config.ts.
You may encounter situations where Drizzle is slightly outdated compared to new roles specified by your database provider.
In such cases, you can use the provider option and exclude additional roles:
With Drizzle, you can also specify RLS policies on views. For this, you need to use security_invoker in the view’s WITH options. Here is a small example:
The Neon Team helped us implement their vision of a wrapper on top of our raw policies API. We defined a specific
/neon import with the crudPolicy function that includes predefined functions and Neon’s default roles.
Here’s an example of how to use the crudPolicy function:
Neon exposes predefined authenticated and anaonymous roles and related functions. If you are using Neon for RLS, you can use these roles, which are marked as existing, and the related functions in your RLS queries.
We also have a /supabase import with a set of predefined roles marked as existing, which you can use in your schema.
This import will be extended in a future release with more functions and helpers to make using RLS and Supabase simpler.
This allows you to use it in your code, and Drizzle Kit will treat them as existing databases,
using them only as information to connect to other entities
import { foreignKey, pgPolicy, pgTable, text, uuid } from "drizzle-orm/pg-core";import { sql } from "drizzle-orm/sql";import { authenticatedRole, authUsers } from "drizzle-orm/supabase";export const profiles = pgTable( "profiles", { id: uuid().primaryKey().notNull(), email: text().notNull(), }, (table) => [ foreignKey({ columns: [table.id], // reference to the auth table from Supabase foreignColumns: [authUsers.id], name: "profiles_id_fk", }).onDelete("cascade"), pgPolicy("authenticated can view all profiles", { for: "select", // using predefined role from Supabase to: authenticatedRole, using: sql`true`, }), ]);
Let’s check an example of adding a policy to a table that exists in Supabase
import { sql } from "drizzle-orm";import { pgPolicy } from "drizzle-orm/pg-core";import { authenticatedRole, realtimeMessages } from "drizzle-orm/supabase";export const policy = pgPolicy("authenticated role insert policy", { for: "insert", to: authenticatedRole, using: sql``,}).link(realtimeMessages);
We also have a great example showcasing how to use Drizzle RLS with Supabase and how to make actual queries with it.
It also includes a great wrapper, createDrizzle, that can handle all the transactional work with Supabase for you.
In upcoming releases, it will be moved to drizzle-orm/supabase, allowing you to use it natively
// https://github.com/orgs/supabase/discussions/23224// Should be secure because we use the access token that is signed, and not the data read directly from the storageexport async function createDrizzleSupabaseClient() { const { data: { session }, } = await createClient().auth.getSession(); return createDrizzle(decode(session?.access_token ?? ""), { admin, client });}async function getRooms() { const db = await createDrizzleSupabaseClient(); return db.rls((tx) => tx.select().from(rooms));}