<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: SYED SHAAMEER Ali</title>
    <description>The latest articles on DEV Community by SYED SHAAMEER Ali (@syed_shaameerali_52c39bf).</description>
    <link>https://dev.to/syed_shaameerali_52c39bf</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4233300%2Fbdd97fef-e539-42ee-bf06-9aa2c15fd1f6.png</url>
      <title>DEV Community: SYED SHAAMEER Ali</title>
      <link>https://dev.to/syed_shaameerali_52c39bf</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/syed_shaameerali_52c39bf"/>
    <language>en</language>
    <item>
      <title>Express behind a proxy: fixing express-rate-limit when every user shares one limit</title>
      <dc:creator>SYED SHAAMEER Ali</dc:creator>
      <pubDate>Thu, 19 Nov 2026 13:34:48 +0000</pubDate>
      <link>https://dev.to/syed_shaameerali_52c39bf/express-behind-a-proxy-fixing-express-rate-limit-when-every-user-shares-one-limit-4ene</link>
      <guid>https://dev.to/syed_shaameerali_52c39bf/express-behind-a-proxy-fixing-express-rate-limit-when-every-user-shares-one-limit-4ene</guid>
      <description>&lt;p&gt;You add express-rate-limit, test it locally, and everything works.&lt;/p&gt;

&lt;p&gt;Then you deploy to Render, Railway, Fly.io, or behind Nginx.&lt;/p&gt;

&lt;p&gt;Suddenly, one of two things happens:&lt;/p&gt;

&lt;p&gt;Your logs show ERR_ERL_UNEXPECTED_X_FORWARDED_FOR.&lt;/p&gt;

&lt;p&gt;Your rate limiter starts treating multiple users as the same client, causing everyone to share one request limit.&lt;/p&gt;

&lt;p&gt;The problem is often your Express proxy configuration.&lt;/p&gt;

&lt;p&gt;When Express cannot identify the original client IP correctly, an IP-based rate limiter can end up counting requests against the proxy's address instead.&lt;/p&gt;

&lt;p&gt;Here's why it happens, how to configure it, and what to check before deploying the fix.&lt;/p&gt;

&lt;p&gt;Why it happens&lt;/p&gt;

&lt;p&gt;When your Express application sits behind a reverse proxy, it doesn't communicate directly with the original client. The proxy forwards the request to your application.&lt;/p&gt;

&lt;p&gt;The proxy may include the original client's IP address in the X-Forwarded-For header.&lt;/p&gt;

&lt;p&gt;However, Express does not trust forwarded headers by default.&lt;/p&gt;

&lt;p&gt;With trust proxy disabled:&lt;/p&gt;

&lt;p&gt;req.ip is generally derived from the address of the immediate connection.&lt;/p&gt;

&lt;p&gt;Multiple users connecting through the same proxy can appear to share the same IP.&lt;/p&gt;

&lt;p&gt;An IP-based rate limiter may count those requests in one shared bucket.&lt;/p&gt;

&lt;p&gt;Newer versions of express-rate-limit also check for common proxy misconfigurations.&lt;/p&gt;

&lt;p&gt;For example, ERR_ERL_UNEXPECTED_X_FORWARDED_FOR can appear when the request contains an X-Forwarded-For header but Express has not been configured to trust the proxy.&lt;/p&gt;

&lt;p&gt;The library is warning you that your IP-based rate limiting may not be working as intended.&lt;/p&gt;

&lt;p&gt;The fix: configure trust proxy correctly&lt;/p&gt;

&lt;p&gt;Express provides the trust proxy setting to determine which proxy addresses or hops it should trust.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;p&gt;import express from 'express';&lt;br&gt;
import rateLimit from 'express-rate-limit';&lt;/p&gt;

&lt;p&gt;const app = express();&lt;/p&gt;

&lt;p&gt;// Example ONLY: use 1 when your verified proxy topology&lt;br&gt;
// has exactly one trusted hop between the client and Express.&lt;br&gt;
app.set('trust proxy', 1);&lt;/p&gt;

&lt;p&gt;const limiter = rateLimit({&lt;br&gt;
  windowMs: 15 * 60 * 1000,&lt;br&gt;
  limit: 300,&lt;br&gt;
  standardHeaders: true,&lt;br&gt;
  legacyHeaders: false,&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;app.use(limiter);&lt;/p&gt;

&lt;p&gt;The important part is:&lt;/p&gt;

&lt;p&gt;app.set('trust proxy', 1);&lt;/p&gt;

&lt;p&gt;This tells Express to trust one proxy hop when determining the client IP.&lt;/p&gt;

&lt;p&gt;Set it before registering middleware that depends on req.ip, including your rate limiter.&lt;/p&gt;

&lt;p&gt;Important: 1 is an example, not a universal setting for every hosting provider.&lt;/p&gt;

&lt;p&gt;How many proxies should you trust?&lt;/p&gt;

&lt;p&gt;Don't guess.&lt;/p&gt;

&lt;p&gt;The correct value depends on your actual network topology.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;p&gt;Client → Express: no reverse proxy.&lt;/p&gt;

&lt;p&gt;Client → Platform proxy → Express: one proxy hop.&lt;/p&gt;

&lt;p&gt;Client → CDN → Load balancer → Express: potentially multiple proxy hops.&lt;/p&gt;

&lt;p&gt;However, counting hops alone isn't always sufficient.&lt;/p&gt;

&lt;p&gt;Express specifically warns that numeric hop-based trust can be unsafe when different network paths have different numbers of proxies. A client might be able to influence the address Express identifies if the topology isn't consistent.&lt;/p&gt;

&lt;p&gt;Where possible, use known trusted proxy IP addresses or subnets instead of blindly trusting a hop count.&lt;/p&gt;

&lt;p&gt;If you use a numeric setting, verify that every path to your application has the expected number of trusted hops and that your ingress proxy handles forwarded headers correctly.&lt;/p&gt;

&lt;p&gt;Official documentation:&lt;/p&gt;

&lt;p&gt;Express: Behind Proxies&lt;/p&gt;

&lt;p&gt;Verify the client IP&lt;/p&gt;

&lt;p&gt;You can temporarily add a diagnostic endpoint:&lt;/p&gt;

&lt;p&gt;app.get('/debug-ip', (req, res) =&amp;gt; {&lt;br&gt;
  res.json({&lt;br&gt;
    ip: req.ip,&lt;br&gt;
    forwardedFor: req.headers['x-forwarded-for'],&lt;br&gt;
  });&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;Use it to inspect what Express sees when requests pass through your actual deployment infrastructure.&lt;/p&gt;

&lt;p&gt;But don't rely on one successful request.&lt;/p&gt;

&lt;p&gt;Check:&lt;/p&gt;

&lt;p&gt;Whether req.ip represents the expected client address.&lt;/p&gt;

&lt;p&gt;Whether your proxy overwrites or sanitizes forwarded headers.&lt;/p&gt;

&lt;p&gt;Whether requests arriving through different network paths produce the expected result.&lt;/p&gt;

&lt;p&gt;Whether a client can change the apparent IP by supplying a forged X-Forwarded-For header.&lt;/p&gt;

&lt;p&gt;A single mobile-data test cannot prove that your configuration is secure.&lt;/p&gt;

&lt;p&gt;Keep this endpoint temporary, restrict access while testing, and remove it before public release.&lt;/p&gt;

&lt;p&gt;Don't blindly set trust proxy to true&lt;/p&gt;

&lt;p&gt;You might see examples using:&lt;/p&gt;

&lt;p&gt;app.set('trust proxy', true);&lt;/p&gt;

&lt;p&gt;Avoid treating this as a universal solution.&lt;/p&gt;

&lt;p&gt;With this setting, Express trusts the leftmost address in X-Forwarded-For.&lt;/p&gt;

&lt;p&gt;If the last trusted proxy doesn't properly overwrite or sanitize forwarded headers, a client may be able to supply a fake address.&lt;/p&gt;

&lt;p&gt;That can allow someone to rotate their apparent IP and bypass IP-based rate limits.&lt;/p&gt;

&lt;p&gt;Use a configuration that matches your actual trusted infrastructure instead.&lt;/p&gt;

&lt;p&gt;express-rate-limit also has a validation warning for permissive proxy configurations.&lt;/p&gt;

&lt;p&gt;Making it configurable&lt;/p&gt;

&lt;p&gt;Your local environment and deployed environment might have different proxy configurations.&lt;/p&gt;

&lt;p&gt;An environment variable lets you configure the number of trusted hops without changing the application code.&lt;/p&gt;

&lt;p&gt;For a numeric-hop configuration:&lt;/p&gt;

&lt;p&gt;const rawTrustProxy = process.env.TRUST_PROXY;&lt;/p&gt;

&lt;p&gt;if (rawTrustProxy === undefined || rawTrustProxy === '') {&lt;br&gt;
  app.set('trust proxy', false);&lt;br&gt;
} else if (/^\d+$/.test(rawTrustProxy)) {&lt;br&gt;
  app.set('trust proxy', Number(rawTrustProxy));&lt;br&gt;
} else {&lt;br&gt;
  throw new Error(&lt;br&gt;
    'TRUST_PROXY must be a non-negative integer'&lt;br&gt;
  );&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;TRUST_PROXY=1&lt;/p&gt;

&lt;p&gt;Use the value that matches your verified deployment topology.&lt;/p&gt;

&lt;p&gt;For local development without a reverse proxy, leave the variable empty.&lt;/p&gt;

&lt;p&gt;This example deliberately supports numeric hop counts only. If your infrastructure requires trusted IP addresses or CIDR ranges, configure and validate those separately.&lt;/p&gt;

&lt;p&gt;Never set the value just because a hosting tutorial uses it.&lt;/p&gt;

&lt;p&gt;Add a stricter limit for authentication routes&lt;/p&gt;

&lt;p&gt;A general API rate limit may not be enough for sensitive endpoints.&lt;/p&gt;

&lt;p&gt;Login and password-reset routes often need their own, stricter limits.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;p&gt;const authLimiter = rateLimit({&lt;br&gt;
  windowMs: 15 * 60 * 1000,&lt;br&gt;
  limit: 20,&lt;br&gt;
  standardHeaders: true,&lt;br&gt;
  legacyHeaders: false,&lt;br&gt;
  message: {&lt;br&gt;
    error: 'Too many attempts. Try again later.',&lt;br&gt;
  },&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;app.use('/auth', authLimiter);&lt;/p&gt;

&lt;p&gt;This example assumes your authentication routes are mounted under /auth.&lt;/p&gt;

&lt;p&gt;Adjust the limits to your application's needs. A rate limit is an additional abuse-prevention measure, not a replacement for proper authentication and authorization.&lt;/p&gt;

&lt;p&gt;One more thing: multiple server instances&lt;/p&gt;

&lt;p&gt;There's another issue worth knowing about.&lt;/p&gt;

&lt;p&gt;express-rate-limit uses an in-memory store by default.&lt;/p&gt;

&lt;p&gt;That works for simple deployments, but its counters aren't shared between separate server instances.&lt;/p&gt;

&lt;p&gt;For example, if your application runs on two instances, each instance can maintain its own rate-limit counter.&lt;/p&gt;

&lt;p&gt;This means the effective limit can be inconsistent depending on which instance receives a request.&lt;/p&gt;

&lt;p&gt;For deployments that need consistent rate limiting across multiple instances, use a shared external store such as Redis.&lt;/p&gt;

&lt;p&gt;See the express-rate-limit store documentation.&lt;/p&gt;

&lt;p&gt;Deployment checklist&lt;/p&gt;

&lt;p&gt;Before deploying, check these things:&lt;/p&gt;

&lt;p&gt;Configure trust proxy according to your actual infrastructure.&lt;/p&gt;

&lt;p&gt;Don't blindly use true.&lt;/p&gt;

&lt;p&gt;Set the proxy configuration before your rate limiter.&lt;/p&gt;

&lt;p&gt;Verify that forwarded headers are handled correctly by your ingress proxy.&lt;/p&gt;

&lt;p&gt;Test requests through your real deployment path.&lt;/p&gt;

&lt;p&gt;Test whether forged forwarding headers can change the apparent client IP.&lt;/p&gt;

&lt;p&gt;Use stricter limits for sensitive authentication endpoints.&lt;/p&gt;

&lt;p&gt;Consider a shared store when running multiple application instances.&lt;/p&gt;

&lt;p&gt;Want this already handled?&lt;/p&gt;

&lt;p&gt;My Express + Supabase starter includes rate limiting on authentication routes and configurable TRUST_PROXY handling.&lt;/p&gt;

&lt;p&gt;Disclosure: I'm the author. It's a paid starter, not a security audit. Check the deployment configuration against your own hosting infrastructure before using it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://shaameer.gumroad.com/l/SupabaseExpressjsBackend" rel="noopener noreferrer"&gt;https://shaameer.gumroad.com/l/SupabaseExpressjsBackend&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The configuration examples above are free to use.&lt;/p&gt;

&lt;p&gt;If you've run into a different proxy setup, share the details in the comments. It might help another Express developer avoid the same problem.&lt;/p&gt;

</description>
      <category>supabase</category>
      <category>webdev</category>
      <category>security</category>
      <category>express</category>
    </item>
    <item>
      <title>Supabase 42501: Your RLS policy might be fine. You're missing a GRANT.</title>
      <dc:creator>SYED SHAAMEER Ali</dc:creator>
      <pubDate>Wed, 18 Nov 2026 14:13:17 +0000</pubDate>
      <link>https://dev.to/syed_shaameerali_52c39bf/supabase-42501-your-rls-policy-might-be-fine-youre-missing-a-grant-104k</link>
      <guid>https://dev.to/syed_shaameerali_52c39bf/supabase-42501-your-rls-policy-might-be-fine-youre-missing-a-grant-104k</guid>
      <description>&lt;p&gt;You create a new table, add RLS policies that look perfect, and your API calls fail with:&lt;/p&gt;

&lt;p&gt;error code 42501: permission denied for table profiles&lt;/p&gt;

&lt;p&gt;Your RLS policies might be perfectly fine. The problem could be one layer below RLS: PostgreSQL privileges.&lt;/p&gt;

&lt;p&gt;Supabase's recent default change makes this especially important. Here's what changed, the SQL that fixes it, and a two-user test to check that your policies still hold.&lt;/p&gt;

&lt;p&gt;What changed&lt;/p&gt;

&lt;p&gt;Supabase no longer automatically grants the API roles (anon, authenticated, and service_role) access to newly created tables in the public schema by default.&lt;/p&gt;

&lt;p&gt;Here's the timeline:&lt;/p&gt;

&lt;p&gt;April 28, 2026: Supabase introduced the option to create projects without automatically exposing new tables.&lt;/p&gt;

&lt;p&gt;May 30, 2026: The new behavior began rolling out as the default for new projects.&lt;/p&gt;

&lt;p&gt;October 30, 2026: The change was applied to existing projects.&lt;/p&gt;

&lt;p&gt;Once this change reaches your project, newly created tables in the public schema require explicit grants before the Data API can access them.&lt;/p&gt;

&lt;p&gt;Existing tables keep their current grants. The change affects newly created tables, not existing table permissions.&lt;/p&gt;

&lt;p&gt;This applies to the Supabase Data API, including requests made through supabase-js, REST, and GraphQL. Direct PostgreSQL connections are not affected.&lt;/p&gt;

&lt;p&gt;Read the official announcement: Supabase changelog: Tables not exposed to Data API automatically.&lt;/p&gt;

&lt;p&gt;The important thing to understand is that there are two separate layers:&lt;/p&gt;

&lt;p&gt;Grants decide whether a database role can access a table or perform an operation.&lt;/p&gt;

&lt;p&gt;RLS policies decide which rows that role can see or modify.&lt;/p&gt;

&lt;p&gt;You need both.&lt;/p&gt;

&lt;p&gt;A policy without the required grant cannot provide access. A grant without appropriate RLS policies can expose rows to roles that shouldn't see them.&lt;/p&gt;

&lt;p&gt;The fix&lt;/p&gt;

&lt;p&gt;Grant only what each role needs, and nothing more.&lt;/p&gt;

&lt;p&gt;For this example, let's assume users can read their own profile and update only their full_name and avatar_url.&lt;/p&gt;

&lt;p&gt;First, remove existing table privileges from the API roles and PUBLIC:&lt;/p&gt;

&lt;p&gt;revoke all on table public.profiles&lt;br&gt;
from PUBLIC, anon, authenticated, service_role;&lt;/p&gt;

&lt;p&gt;Then grant the required permissions:&lt;/p&gt;

&lt;p&gt;-- Logged-in users can read profiles.&lt;br&gt;
grant select on table public.profiles&lt;br&gt;
to authenticated;&lt;/p&gt;

&lt;p&gt;-- Logged-in users can update only these columns.&lt;br&gt;
grant update (full_name, avatar_url)&lt;br&gt;
on table public.profiles&lt;br&gt;
to authenticated;&lt;/p&gt;

&lt;p&gt;-- Server-side service role gets the required table access.&lt;br&gt;
grant select, insert, update, delete&lt;br&gt;
on table public.profiles&lt;br&gt;
to service_role;&lt;/p&gt;

&lt;p&gt;Notice what's missing:&lt;/p&gt;

&lt;p&gt;anon has no table privileges.&lt;/p&gt;

&lt;p&gt;authenticated has no insert or delete permission.&lt;/p&gt;

&lt;p&gt;Authenticated users cannot update every column.&lt;/p&gt;

&lt;p&gt;That's intentional.&lt;/p&gt;

&lt;p&gt;The column-level UPDATE grant matters because RLS restricts rows, not individual columns. Without column-level restrictions, a user might be able to modify sensitive fields on their own profile.&lt;/p&gt;

&lt;p&gt;Add owner-only RLS policies&lt;/p&gt;

&lt;p&gt;Enable RLS, then write policies so users can only access their own profile:&lt;/p&gt;

&lt;p&gt;alter table public.profiles&lt;br&gt;
enable row level security;&lt;/p&gt;

&lt;p&gt;create policy "Users can view own profile"&lt;br&gt;
on public.profiles&lt;br&gt;
for select&lt;br&gt;
to authenticated&lt;br&gt;
using (auth.uid() = id);&lt;/p&gt;

&lt;p&gt;create policy "Users can update own profile"&lt;br&gt;
on public.profiles&lt;br&gt;
for update&lt;br&gt;
to authenticated&lt;br&gt;
using (auth.uid() = id)&lt;br&gt;
with check (auth.uid() = id);&lt;/p&gt;

&lt;p&gt;The WITH CHECK on the update policy matters.&lt;/p&gt;

&lt;p&gt;USING determines which existing rows can be targeted.&lt;/p&gt;

&lt;p&gt;WITH CHECK validates the resulting row after the update.&lt;/p&gt;

&lt;p&gt;Without the appropriate check, a user could potentially change their profile's id and attempt to associate it with another user's identity.&lt;/p&gt;

&lt;p&gt;Create profiles with a trigger, not from the client&lt;/p&gt;

&lt;p&gt;There is no INSERT policy above. Clients cannot create profile rows directly.&lt;/p&gt;

&lt;p&gt;Instead, a database trigger creates the profile when a user signs up.&lt;/p&gt;

&lt;p&gt;create or replace function public.handle_new_user()&lt;br&gt;
returns trigger&lt;br&gt;
language plpgsql&lt;br&gt;
security definer&lt;br&gt;
set search_path = ''&lt;br&gt;
as $$&lt;br&gt;
begin&lt;br&gt;
  insert into public.profiles (&lt;br&gt;
    id,&lt;br&gt;
    email,&lt;br&gt;
    full_name,&lt;br&gt;
    avatar_url&lt;br&gt;
  )&lt;br&gt;
  values (&lt;br&gt;
    new.id,&lt;br&gt;
    new.email,&lt;br&gt;
    new.raw_user_meta_data-&amp;gt;&amp;gt;'full_name',&lt;br&gt;
    new.raw_user_meta_data-&amp;gt;&amp;gt;'avatar_url'&lt;br&gt;
  );&lt;/p&gt;

&lt;p&gt;return new;&lt;br&gt;
end;&lt;br&gt;
$$;&lt;/p&gt;

&lt;p&gt;create trigger on_auth_user_created&lt;br&gt;
after insert on auth.users&lt;br&gt;
for each row&lt;br&gt;
execute function public.handle_new_user();&lt;/p&gt;

&lt;p&gt;Why use SECURITY DEFINER?&lt;/p&gt;

&lt;p&gt;It runs the function with its owner's permissions, allowing the trigger to insert the profile even though authenticated users don't have direct INSERT permission.&lt;/p&gt;

&lt;p&gt;Notice SET search_path = '' and the explicitly qualified public.profiles table name. This avoids relying on an implicit search path inside a privileged function.&lt;/p&gt;

&lt;p&gt;Test it with two users&lt;/p&gt;

&lt;p&gt;Don't trust a policy just because it looks right.&lt;/p&gt;

&lt;p&gt;Create two test users, sign in as each, and try to access another user's profile.&lt;/p&gt;

&lt;p&gt;Assume userA and userB are separate Supabase clients, each authenticated as the corresponding user.&lt;/p&gt;

&lt;p&gt;// User B tries to read User A's profile.&lt;br&gt;
const { data: read, error: readError } = await userB&lt;br&gt;
  .from('profiles')&lt;br&gt;
  .select('*')&lt;br&gt;
  .eq('id', userA.id);&lt;/p&gt;

&lt;p&gt;// A real request error should not be mistaken for a successful test.&lt;br&gt;
if (readError) {&lt;br&gt;
  throw readError;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;if (read.length !== 0) {&lt;br&gt;
  throw new Error('FAIL: User B can read User A profile');&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;console.log('PASS: User B cannot read User A profile');&lt;/p&gt;

&lt;p&gt;// User B tries to update User A's profile.&lt;br&gt;
const { data: write, error: writeError } = await userB&lt;br&gt;
  .from('profiles')&lt;br&gt;
  .update({ full_name: 'hacked' })&lt;br&gt;
  .eq('id', userA.id)&lt;br&gt;
  .select();&lt;/p&gt;

&lt;p&gt;if (writeError) {&lt;br&gt;
  throw writeError;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;if (write.length !== 0) {&lt;br&gt;
  throw new Error('FAIL: User B can update User A profile');&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;console.log('PASS: User B cannot update User A profile');&lt;/p&gt;

&lt;p&gt;Expected result:&lt;/p&gt;

&lt;p&gt;Reading another user's profile returns an empty array.&lt;/p&gt;

&lt;p&gt;Updating another user's profile affects zero rows and returns an empty array.&lt;/p&gt;

&lt;p&gt;Actual request errors are reported separately rather than being mistaken for successful RLS checks.&lt;/p&gt;

&lt;p&gt;If either operation returns User A's row, investigate your policies.&lt;/p&gt;

&lt;p&gt;If User B cannot access their own profile either, check your grants, policies, and authentication setup.&lt;/p&gt;

&lt;p&gt;These two checks are useful, but they don't prove every permission or policy in your application is correct. Test your own rows, allowed updates, protected columns, and anonymous access separately too.&lt;/p&gt;

&lt;p&gt;Common mistakes&lt;/p&gt;

&lt;p&gt;Granting access to anon just to make the error disappear. This can expose data if your RLS configuration is missing or too permissive.&lt;/p&gt;

&lt;p&gt;Using USING (true) for authenticated users. That allows every authenticated user to access every matching row.&lt;/p&gt;

&lt;p&gt;Forgetting WITH CHECK on UPDATE policies. Always validate the resulting row.&lt;/p&gt;

&lt;p&gt;Giving users unrestricted UPDATE privileges. RLS controls rows, not columns. Use column-level grants when certain fields must remain protected.&lt;/p&gt;

&lt;p&gt;Putting the service role key in client-side code. It bypasses RLS. Keep it on the server and restrict its use.&lt;/p&gt;

&lt;p&gt;Want the setup already done?&lt;/p&gt;

&lt;p&gt;I built an Express + Supabase starter that includes explicit grants, owner-only RLS, a signup trigger, and a two-user test that checks access between users.&lt;/p&gt;

&lt;p&gt;It also includes additional authentication and server-side hardening.&lt;/p&gt;

&lt;p&gt;Disclosure: I'm the author. It's a paid starter, not a security audit. The included RLS setup and test cover the profiles table. If you add your own tables, you'll need to write and test their policies and grants too.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://shaameer.gumroad.com/l/SupabaseExpressjsProductionBackend" rel="noopener noreferrer"&gt;https://shaameer.gumroad.com/l/SupabaseExpressjsProductionBackend&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Either way, the SQL above is free to copy.&lt;/p&gt;

&lt;p&gt;If it saved you some debugging time, share it with someone staring at a 42501 error. IF something doesnt work ask me and i will reply.&lt;/p&gt;

</description>
      <category>supabase</category>
      <category>webdev</category>
      <category>express</category>
      <category>security</category>
    </item>
    <item>
      <title>Supabase + Express: stop using the service role key for every request</title>
      <dc:creator>SYED SHAAMEER Ali</dc:creator>
      <pubDate>Tue, 17 Nov 2026 14:27:20 +0000</pubDate>
      <link>https://dev.to/syed_shaameerali_52c39bf/supabase-express-stop-using-the-service-role-key-for-every-request-1p4c</link>
      <guid>https://dev.to/syed_shaameerali_52c39bf/supabase-express-stop-using-the-service-role-key-for-every-request-1p4c</guid>
      <description>&lt;p&gt;Most Express + Supabase tutorials start the same way: create one Supabase client at the top of the file with the service role key, and use it everywhere. It works on the first try, which is why so many projects do it.&lt;br&gt;
It also quietly turns off the main security feature of Supabase. This post explains why, and shows the pattern I use instead: a small client created per request, using the caller’s own token.&lt;br&gt;
The common setup&lt;br&gt;
// supabase.js&lt;br&gt;
import { createClient } from '@supabase/supabase-js';&lt;/p&gt;

&lt;p&gt;export const supabase = createClient(&lt;br&gt;
  process.env.SUPABASE_URL,&lt;br&gt;
  process.env.SUPABASE_SERVICE_ROLE_KEY&lt;br&gt;
);&lt;br&gt;
// a route&lt;br&gt;
router.get('/todos', requireAuth, async (req, res) =&amp;gt; {&lt;br&gt;
  const { data } = await supabase&lt;br&gt;
    .from('todos')&lt;br&gt;
    .select('*')&lt;br&gt;
    .eq('user_id', req.user.id); // you must remember this line, every time&lt;br&gt;
  res.json(data);&lt;br&gt;
});&lt;br&gt;
The service role key bypasses Row-Level Security completely. Your policies exist, but they never run for these queries. The only thing standing between one user and everyone else’s data is that .eq('user_id', ...) line, written by hand in every route. Miss it once, in one route, and that route returns everyone’s rows.&lt;br&gt;
The pattern: one client per request, using the user’s token&lt;br&gt;
Instead of a shared all-powerful client, build a client for each request from the anon key plus the caller’s JWT. Postgres then sees the real user, and RLS applies to every query automatically.&lt;br&gt;
// middleware/auth.js&lt;br&gt;
import { createClient } from '@supabase/supabase-js';&lt;/p&gt;

&lt;p&gt;export async function requireAuth(req, res, next) {&lt;br&gt;
  const header = req.headers.authorization || '';&lt;br&gt;
  const token = header.startsWith('Bearer ') ? header.slice(7) : null;&lt;br&gt;
  if (!token) return res.status(401).json({ error: 'Missing token' });&lt;/p&gt;

&lt;p&gt;// Anon key + the user's JWT, so RLS applies to every query on this client&lt;br&gt;
  const supabase = createClient(&lt;br&gt;
    process.env.SUPABASE_URL,&lt;br&gt;
    process.env.SUPABASE_ANON_KEY,&lt;br&gt;
    {&lt;br&gt;
      global: { headers: { Authorization: &lt;code&gt;Bearer ${token}&lt;/code&gt; } },&lt;br&gt;
      auth: { persistSession: false, autoRefreshToken: false },&lt;br&gt;
    }&lt;br&gt;
  );&lt;/p&gt;

&lt;p&gt;// Verify the token with Supabase Auth&lt;br&gt;
  const { data, error } = await supabase.auth.getUser(token);&lt;br&gt;
  if (error || !data?.user) {&lt;br&gt;
    return res.status(401).json({ error: 'Invalid or expired token' });&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;req.user = data.user;&lt;br&gt;
  req.supabase = supabase; // use this in your routes&lt;br&gt;
  next();&lt;br&gt;
}&lt;br&gt;
Now a route looks like this:&lt;br&gt;
router.get('/todos', requireAuth, async (req, res) =&amp;gt; {&lt;br&gt;
  const { data, error } = await req.supabase.from('todos').select('*');&lt;br&gt;
  if (error) return res.status(400).json({ error: error.message });&lt;br&gt;
  res.json(data);&lt;br&gt;
});&lt;br&gt;
No .eq('user_id', ...) needed for safety. If a route forgets to filter, the policy still limits the result to that user’s rows. A mistake in your code now returns fewer rows instead of leaking them. (You can still filter for clarity or performance. It just isn’t what protects you anymore.)&lt;br&gt;
Why create a client per request?&lt;br&gt;
A client built from the caller’s token carries that one user’s identity. If you share a single client and swap sessions on it (for example by calling setSession), concurrent requests can step on each other. Building a fresh client per request, with persistSession: false, keeps each request isolated. It’s cheap: creating a client is just object setup, not a network call.&lt;br&gt;
Where the service role key still belongs&lt;br&gt;
Some things really do need to bypass RLS: admin tasks, background jobs, creating users from your server, test setup. Keep that in a separate, clearly named file and don’t hand it to ordinary routes:&lt;br&gt;
// admin-client.js, used only by admin-only code&lt;br&gt;
import { createClient } from '@supabase/supabase-js';&lt;/p&gt;

&lt;p&gt;export const supabaseAdmin = createClient(&lt;br&gt;
  process.env.SUPABASE_URL,&lt;br&gt;
  process.env.SUPABASE_SERVICE_ROLE_KEY,&lt;br&gt;
  { auth: { persistSession: false } }&lt;br&gt;
);&lt;br&gt;
Rules of thumb:&lt;br&gt;
• The service role key lives in server environment variables only. Never in a browser, a mobile app, or a repo.&lt;br&gt;
• If a route uses supabaseAdmin, treat it like a loaded tool: write the ownership checks by hand and review them.&lt;br&gt;
• Ordinary user-facing routes use req.supabase.&lt;br&gt;
RLS and grants still have to be set up&lt;br&gt;
This pattern only protects you if the database side exists: RLS enabled on the table, policies that check auth.uid(), and the right grants for the authenticated role. Supabase no longer auto-grants API access to new tables, so a table with a policy but no grant will return 42501 permission denied. If that bites you, [LINK TO ARTICLE 1] covers the grants.&lt;br&gt;
A 2-minute check&lt;br&gt;
Call your route with two different users’ tokens. Each should see only their own rows. If either one sees everything, the route is using the wrong client or the table has no working policy. [LINK TO ARTICLE 2] has a script that automates this.&lt;br&gt;
Summary&lt;br&gt;
• One global client with the service role key means RLS never runs, and every route has to filter by hand.&lt;br&gt;
• A per-request client with the anon key and the user’s JWT makes Postgres enforce your policies for every query.&lt;br&gt;
• Keep the service role key in a separate admin client for the few places that truly need it.&lt;br&gt;
Want it already set up?&lt;br&gt;
My Express + Supabase starter uses this per-request pattern: auth routes, a JWT middleware that attaches req.supabase, rate limiting, and a signup trigger that creates profiles. Disclosure: I’m the author, and it’s a paid starter, not a security audit. It covers the profiles table, so any tables you add need their own policies and grants.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://shaameer.gumroad.com/l/SupabaseExpressjsProductionBackend/Launch10" rel="noopener noreferrer"&gt;https://shaameer.gumroad.com/l/SupabaseExpressjsProductionBackend/Launch10&lt;/a&gt;&lt;br&gt;
The code above is free to copy either way. If you spot something I got wrong, tell me in the comments and I’ll fix it.&lt;/p&gt;

</description>
      <category>security</category>
      <category>supabase</category>
      <category>express</category>
      <category>webdev</category>
    </item>
    <item>
      <title>How to test Supabase RLS with two users (script included) By Shaameer</title>
      <dc:creator>SYED SHAAMEER Ali</dc:creator>
      <pubDate>Sun, 15 Nov 2026 08:17:03 +0000</pubDate>
      <link>https://dev.to/syed_shaameerali_52c39bf/how-to-test-supabase-rls-with-two-users-script-includedby-shaameer-312o</link>
      <guid>https://dev.to/syed_shaameerali_52c39bf/how-to-test-supabase-rls-with-two-users-script-includedby-shaameer-312o</guid>
      <description>&lt;p&gt;Update: thanks to [@sunnatullah] for catching two gaps in the first version of this script. (1) Checks 2 and 3 could pass even if User B never got a profile row, so they proved nothing. (2) Owner-only RLS filters rows, not columns, so with a table-wide UPDATE grant a user can edit sensitive columns on their own row. Both are fixed below.&lt;br&gt;
An RLS policy can look perfect and still leak. When AI helps write your migrations, a policy can also quietly go missing. The only way to know your database is locked down is to try to break it.&lt;br&gt;
This post shows a two-user test you can run in a minute: create User A and User B, sign in as each, and check that A can’t read or edit B’s data. It works on any table. I’ll use a profiles table with owner-only policies as the example.&lt;br&gt;
Why “it works in my app” proves nothing&lt;br&gt;
When you test your own app, you are always logged in as the same user, looking at your own rows. Of course it works. A leak only shows up when a different user requests your data, and that never happens while you’re building.&lt;br&gt;
Supabase also supports SQL tests with pgTAP, which is great if you like writing SQL. Most JavaScript developers just want a short, readable script they can drop into their repo, so that’s what this is.&lt;br&gt;
What the test checks&lt;br&gt;
Assume a profiles table with RLS enabled, owner-only policies (auth.uid() = id), and a signup trigger that creates one row per user. The script checks that:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Setup: both users actually have a profile row. If not, the other results mean nothing, so the script stops.&lt;/li&gt;
&lt;li&gt; User A can read their own row.&lt;/li&gt;
&lt;li&gt; User A can’t read User B’s row.&lt;/li&gt;
&lt;li&gt; User A can’t update User B’s row, and B’s row is unchanged afterwards.&lt;/li&gt;
&lt;li&gt; User A can’t edit a protected column on their own row (this needs the column grants below).&lt;/li&gt;
&lt;li&gt; User A can still edit the columns you allow, so check 5 isn’t passing just because everything is blocked.&lt;/li&gt;
&lt;li&gt; A logged-out (anon) client can’t read the table.
When you add a table, copy these checks for it.
Row policies don’t protect columns
This is the gap that’s easy to miss. RLS decides which rows a user can touch. It doesn’t decide which columns. If authenticated has a table-wide UPDATE grant, owner-only policies stop A from editing B, but A can still edit their own row, including any column like is_admin, role, plan or email.
The fix is a column-level grant. Allow only the columns users should change:
revoke update on public.profiles from authenticated;
grant update (full_name, avatar_url) on public.profiles to authenticated;
After this, updating full_name still works, and updating anything else fails with 42501 permission denied for table profiles. Make sure your client only sends the allowed columns in updates.
The script below tests this using email as the protected column. Change PROTECTED_COLUMN to whatever sensitive column your table has.
The script
Install the Supabase client and save the code as test-rls.mjs. It needs Node 20.6+ for the --env-file flag.
npm install @supabase/supabase-js
Security note: this script uses your SUPABASE_SERVICE_ROLE_KEY to create and delete test users. Never put that key in client-side code, and don’t run this against a live production database. Keep it in a local .env file or an isolated CI test project.
import { createClient } from '@supabase/supabase-js';&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;const url = process.env.SUPABASE_URL;&lt;br&gt;
const anonKey = process.env.SUPABASE_ANON_KEY;&lt;br&gt;
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; // local/CI test only&lt;/p&gt;

&lt;p&gt;const PROTECTED_COLUMN = 'email';  // a column users must NOT be able to edit&lt;br&gt;
const ALLOWED_COLUMN = 'full_name'; // a column users may edit&lt;/p&gt;

&lt;p&gt;const admin = createClient(url, serviceKey, { auth: { persistSession: false } });&lt;/p&gt;

&lt;p&gt;async function makeUser(label) {&lt;br&gt;
  const email = &lt;code&gt;rls-test-${label}-${Date.now()}@example.com&lt;/code&gt;;&lt;br&gt;
  const password = 'Test-password-123!';&lt;/p&gt;

&lt;p&gt;const { data, error } = await admin.auth.admin.createUser({&lt;br&gt;
    email,&lt;br&gt;
    password,&lt;br&gt;
    email_confirm: true,&lt;br&gt;
  });&lt;br&gt;
  if (error) throw error;&lt;/p&gt;

&lt;p&gt;const client = createClient(url, anonKey, { auth: { persistSession: false } });&lt;br&gt;
  const { error: signInError } = await client.auth.signInWithPassword({ email, password });&lt;br&gt;
  if (signInError) throw signInError;&lt;/p&gt;

&lt;p&gt;return { id: data.user.id, client };&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;let failed = 0;&lt;br&gt;
function check(name, ok) {&lt;br&gt;
  console.log(ok ? &lt;code&gt;PASS  ${name}&lt;/code&gt; : &lt;code&gt;FAIL  ${name}&lt;/code&gt;);&lt;br&gt;
  if (!ok) failed++;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;const a = await makeUser('a');&lt;br&gt;
const b = await makeUser('b');&lt;/p&gt;

&lt;p&gt;try {&lt;br&gt;
  // Setup: both users must have a profile row, or the checks below prove nothing&lt;br&gt;
  const aRow = await admin.from('profiles').select('&lt;em&gt;').eq('id', a.id).single();&lt;br&gt;
  const bBefore = await admin.from('profiles').select('&lt;/em&gt;').eq('id', b.id).single();&lt;br&gt;
  check('Setup: A and B both have profile rows', !!aRow.data &amp;amp;&amp;amp; !!bBefore.data);&lt;br&gt;
  if (!aRow.data || !bBefore.data) {&lt;br&gt;
    throw new Error('Signup trigger did not create a profile row. Fix that before trusting any result.');&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;// 1. A can read their own row&lt;br&gt;
  const own = await a.client.from('profiles').select('*').eq('id', a.id);&lt;br&gt;
  check('A can read own profile', !own.error &amp;amp;&amp;amp; own.data.length === 1);&lt;/p&gt;

&lt;p&gt;// 2. A cannot read B's row&lt;br&gt;
  const other = await a.client.from('profiles').select('*').eq('id', b.id);&lt;br&gt;
  check('A cannot read B', !other.error &amp;amp;&amp;amp; other.data.length === 0);&lt;/p&gt;

&lt;p&gt;// 3. A cannot update B's row, and B is unchanged afterwards&lt;br&gt;
  const upd = await a.client&lt;br&gt;
    .from('profiles')&lt;br&gt;
    .update({ [ALLOWED_COLUMN]: 'hacked' })&lt;br&gt;
    .eq('id', b.id)&lt;br&gt;
    .select();&lt;br&gt;
  const bAfter = await admin.from('profiles').select('*').eq('id', b.id).single();&lt;br&gt;
  check(&lt;br&gt;
    'A cannot update B',&lt;br&gt;
    (upd.data ?? []).length === 0 &amp;amp;&amp;amp;&lt;br&gt;
      bAfter.data?.[ALLOWED_COLUMN] === bBefore.data[ALLOWED_COLUMN]&lt;br&gt;
  );&lt;/p&gt;

&lt;p&gt;// 4. A cannot edit a protected column on their own row (expects permission denied)&lt;br&gt;
  const prot = await a.client&lt;br&gt;
    .from('profiles')&lt;br&gt;
    .update({ [PROTECTED_COLUMN]: '&lt;a href="mailto:changed@example.com"&gt;changed@example.com&lt;/a&gt;' })&lt;br&gt;
    .eq('id', a.id)&lt;br&gt;
    .select();&lt;br&gt;
  check('A cannot edit protected column', prot.error?.code === '42501');&lt;/p&gt;

&lt;p&gt;// 5. A can still edit an allowed column (so check 4 isn't passing because everything is blocked)&lt;br&gt;
  const ok = await a.client&lt;br&gt;
    .from('profiles')&lt;br&gt;
    .update({ [ALLOWED_COLUMN]: 'Alice' })&lt;br&gt;
    .eq('id', a.id)&lt;br&gt;
    .select();&lt;br&gt;
  check('A can edit allowed column', !ok.error &amp;amp;&amp;amp; (ok.data ?? []).length === 1);&lt;/p&gt;

&lt;p&gt;// 6. Logged-out client cannot read the table&lt;br&gt;
  const anon = createClient(url, anonKey, { auth: { persistSession: false } });&lt;br&gt;
  const anonRead = await anon.from('profiles').select('*');&lt;br&gt;
  check('anon cannot read profiles', !!anonRead.error || (anonRead.data ?? []).length === 0);&lt;br&gt;
} catch (e) {&lt;br&gt;
  console.error(e.message);&lt;br&gt;
  failed++;&lt;br&gt;
} finally {&lt;br&gt;
  // cleanup: deleting the auth user also removes the profile (on delete cascade)&lt;br&gt;
  await admin.auth.admin.deleteUser(a.id);&lt;br&gt;
  await admin.auth.admin.deleteUser(b.id);&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;console.log(failed === 0 ? '\nAll checks passed' : &lt;code&gt;\n${failed} check(s) failed&lt;/code&gt;);&lt;br&gt;
process.exit(failed === 0 ? 0 : 1);&lt;br&gt;
Add your keys to a local .env file and run:&lt;br&gt;
node --env-file=.env test-rls.mjs&lt;br&gt;
Check 4 asserts the exact error code 42501, not just “any error”. That matters: if you point it at a column that doesn’t exist, you get a different error, and the check correctly fails instead of passing for the wrong reason.&lt;br&gt;
Reading the results&lt;br&gt;
• Setup fails: your signup trigger didn’t create the profile row. Fix that first.&lt;br&gt;
• Check 1 fails (A can’t read own row): you likely have a missing grant. A 42501 here usually means no GRANT SELECT ON public.profiles TO authenticated.&lt;br&gt;
• Check 2 or 3 fails (A can touch B): your policy is too permissive. Look for USING (true), a policy that only says to authenticated with no auth.uid() owner check, or a missing WITH CHECK on updates.&lt;br&gt;
• Check 4 fails (A edited a protected column): you have a table-wide UPDATE grant. Use the column-level grant above.&lt;br&gt;
• Check 5 fails: your column grant is too tight, or you revoked update entirely.&lt;br&gt;
• Check 6 fails (anon can read): you’re granting table access to anon, or a policy targets it. Revoke it and keep policies on authenticated.&lt;br&gt;
Verify the test can fail. Temporarily loosen a policy to USING (true) and run the script. Check 3 should fail. A security test that can’t fail isn’t testing anything.&lt;br&gt;
A quick version in the SQL editor&lt;br&gt;
To poke at a policy without a script, you can impersonate a user inside a transaction in the Supabase SQL editor:&lt;br&gt;
begin;&lt;br&gt;
  set local role authenticated;&lt;br&gt;
  select set_config('request.jwt.claims', '{"sub": ""}', true);&lt;/p&gt;

&lt;p&gt;-- should return only User A's row&lt;br&gt;
  select id from public.profiles;&lt;br&gt;
rollback;&lt;br&gt;
Replace  with a real user id from your Auth dashboard. It’s fast for ad-hoc debugging, but a script you run after every migration is what catches regressions.&lt;br&gt;
Run it after every schema change&lt;br&gt;
Policies break quietly: a new table, a changed grant, a migration that drops a policy. Put the script in CI or your pre-deploy checklist, and extend it whenever you add a table.&lt;br&gt;
Want this set up already?&lt;br&gt;
My Express + Supabase starter includes a two-user RLS test like this one, plus auth, a signup trigger, and explicit grants for Supabase’s newer defaults. Disclosure: I’m the author, and it’s a paid starter, not a security audit. The tests cover the profiles table, so any tables you add need their own policies and tests.&lt;br&gt;
&lt;a href="https://shaameer.gumroad.com/l/SupabaseExpressjsProductionBackend/Launch10" rel="noopener noreferrer"&gt;https://shaameer.gumroad.com/l/SupabaseExpressjsProductionBackend/Launch10&lt;/a&gt;&lt;br&gt;
The script above is free to copy either way. If it catches something in your project, I’d like to hear what.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>supabase</category>
      <category>postgres</category>
      <category>security</category>
    </item>
    <item>
      <title>Supabase “permission denied for table” (42501) after the Oct 30 change: the fix</title>
      <dc:creator>SYED SHAAMEER Ali</dc:creator>
      <pubDate>Sat, 14 Nov 2026 08:02:06 +0000</pubDate>
      <link>https://dev.to/syed_shaameerali_52c39bf/supabase-permission-denied-for-table-42501-after-the-oct-30-change-the-fix-3dco</link>
      <guid>https://dev.to/syed_shaameerali_52c39bf/supabase-permission-denied-for-table-42501-after-the-oct-30-change-the-fix-3dco</guid>
      <description>&lt;p&gt;You create a new table, add RLS policies that look perfect, and your API calls fail with:&lt;br&gt;
error code 42501: permission denied for table profiles&lt;br&gt;
No policy is wrong. The problem is one layer below RLS, and Supabase’s recent default change is why it suddenly bites. Here is what changed, the exact SQL that fixes it, and a two-user test to prove your policies still hold.&lt;br&gt;
What changed&lt;/p&gt;

&lt;p&gt;Supabase no longer automatically grants the API roles (anon, authenticated) access to new tables in the public schema. New projects got this first, and for every project it applies to tables created after Oct 30. Before, a new table was reachable by default and RLS did the filtering. Now you have to grant access explicitly.&lt;br&gt;
Check the exact rollout details in Supabase’s changelog and docs: [LINK TO SUPABASE CHANGELOG/DOCS].&lt;br&gt;
The thing to remember is that there are two separate layers:&lt;br&gt;
• Grants decide whether a role can touch the table at all.&lt;br&gt;
• RLS policies decide which rows that role can see or change.&lt;br&gt;
You need both. A policy without a grant gives you 42501. A grant without RLS gives you a table anyone can read.&lt;/p&gt;

&lt;p&gt;The fix&lt;br&gt;
Grant only what each role needs, and nothing more:&lt;br&gt;
-- Block anonymous access completely&lt;br&gt;
revoke all on table public.profiles from anon;&lt;/p&gt;

&lt;p&gt;-- Logged-in users can read and update (RLS limits which rows)&lt;br&gt;
grant select, update on table public.profiles to authenticated;&lt;/p&gt;

&lt;p&gt;-- Your server-side code (service role key) gets full access&lt;br&gt;
grant select, insert, update, delete on table public.profiles to service_role;&lt;br&gt;
Notice what is missing: authenticated has no insert or delete. That is on purpose, see the trigger section below.&lt;br&gt;
Add owner-only RLS policies&lt;br&gt;
Enable RLS, then write policies so users only touch their own row:&lt;br&gt;
alter table public.profiles enable row level security;&lt;/p&gt;

&lt;p&gt;create policy "Users can view own profile"&lt;br&gt;
  on public.profiles for select&lt;br&gt;
  to authenticated&lt;br&gt;
  using ( auth.uid() = id );&lt;/p&gt;

&lt;p&gt;create policy "Users can update own profile"&lt;br&gt;
  on public.profiles for update&lt;br&gt;
  to authenticated&lt;br&gt;
  using ( auth.uid() = id )&lt;br&gt;
  with check ( auth.uid() = id );&lt;br&gt;
The with check on the update policy matters. Without it, a user could update their row and change id to someone else’s. using filters which rows can be targeted, with check validates the row after the change.&lt;br&gt;
Create profiles with a trigger, not from the client&lt;br&gt;
There is no insert policy above. Clients can’t create profile rows at all. Instead, a trigger creates the row when a user signs up:&lt;br&gt;
create or replace function public.handle_new_user()&lt;br&gt;
returns trigger as $$&lt;br&gt;
begin&lt;br&gt;
  insert into public.profiles (id, email, full_name, avatar_url)&lt;br&gt;
  values (&lt;br&gt;
    new.id,&lt;br&gt;
    new.email,&lt;br&gt;
    new.raw_user_meta_data-&amp;gt;&amp;gt;'full_name',&lt;br&gt;
    new.raw_user_meta_data-&amp;gt;&amp;gt;'avatar_url'&lt;br&gt;
  );&lt;br&gt;
  return new;&lt;br&gt;
end;&lt;br&gt;
$$ language plpgsql security definer set search_path = public;&lt;/p&gt;

&lt;p&gt;create trigger on_auth_user_created&lt;br&gt;
  after insert on auth.users&lt;br&gt;
  for each row&lt;br&gt;
  execute procedure public.handle_new_user();&lt;br&gt;
security definer runs the function with its owner’s permissions, so it can insert even though authenticated can’t. Setting search_path on a security definer function is important, otherwise it can be tricked into running objects from a schema you didn’t intend.&lt;br&gt;
Test it with two users&lt;br&gt;
Don’t trust a policy because it looks right. Create two users, sign in as each, and try to break in:&lt;br&gt;
// userB is a supabase-js client signed in as User B&lt;br&gt;
// userA.id is User A's id&lt;/p&gt;

&lt;p&gt;// 1. B tries to read A's profile -&amp;gt; expect an empty array&lt;br&gt;
const { data: read } = await userB&lt;br&gt;
  .from('profiles')&lt;br&gt;
  .select('*')&lt;br&gt;
  .eq('id', userA.id);&lt;/p&gt;

&lt;p&gt;// 2. B tries to edit A's profile -&amp;gt; expect an empty array (no rows affected)&lt;br&gt;
const { data: write } = await userB&lt;br&gt;
  .from('profiles')&lt;br&gt;
  .update({ full_name: 'hacked' })&lt;br&gt;
  .eq('id', userA.id)&lt;br&gt;
  .select();&lt;/p&gt;

&lt;p&gt;If either call returns A’s row, your policy is too open. If you get 42501 on your own row, you are missing a grant. Both are easy to catch here and painful to catch in production.&lt;br&gt;
Common mistakes&lt;/p&gt;

&lt;p&gt;• Granting to anon “just to make it work.” Combined with a loose or missing policy, anyone on the internet can read the table. Grant to authenticated and write real policies instead.&lt;br&gt;
• A policy that only says to authenticated with using (true). Any signed-in user reads every row. The owner check (auth.uid() = id) belongs in the policy.&lt;br&gt;
• Forgetting with check on update. Users can reassign rows.&lt;br&gt;
• Using the service role key in client code. It bypasses RLS entirely. Keep it server-side only.&lt;/p&gt;

&lt;p&gt;Want the setup already done?&lt;/p&gt;

&lt;p&gt;I built an Express + Supabase starter that ships with the grants, owner-only RLS, the signup trigger, and a one-command two-user test that prints 4 PASS lines. Disclosure: I’m the author, and it’s a paid starter, not an audit. It covers the profiles table. If you add your own tables, you’ll need to write and test their policies too.&lt;br&gt;
&lt;a href="https://shaameer.gumroad.com/l/SupabaseExpressjsProductionBackend/Launch10" rel="noopener noreferrer"&gt;https://shaameer.gumroad.com/l/SupabaseExpressjsProductionBackend/Launch10&lt;/a&gt;&lt;br&gt;
Either way, the SQL above is free to copy. If it saved you an hour, share it with someone who is staring at a 42501.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>supabase</category>
      <category>express</category>
    </item>
  </channel>
</rss>
