Securely Mutate Supabase Data with Remix Actions

Share this video with your friends

Send Tweet

To mutate data in Remix, we use an Action function. In this lesson, we look at creating a Remix <Form /> to submit the content of a message as a post request to our Action function.

Additionally, we use the server-side Supabase client from the Remix Auth Helpers package to make an authenticated request to Supabase, writing the new message to the messages table.

Futhermore, we run into an issue with RLS as we have not yet written a policy for the insert action. By setting this to the authenticated role and ensuring that the user_id column is equal to the value returned by the auth.uid() function - a function we get from Supabase to retrieve the ID for the user attempting to insert a new row - we ensure that users can not write a message on someone else's behalf.

Lastly, we use the auth.uid() function to set the default value of the user_id column to the ID of the user attempting to insert the new row in the messages table.

Code Snippets

Write data to Supabase

export const action = async ({ request }: ActionArgs) => {
  const response = new Response();
  const supabase = createServerSupabase({ request, response });

  const { message } = Object.fromEntries(await request.formData());

  await supabase.from("messages").insert({ content: String(message) });

  return json(null, { headers: response.headers });
};

Form to submit to action

<Form method="post">
  <input type="text" name="message" />
  <button type="submit">Send</button>
</Form>

Add policy for insert

create policy "users can insert their own messages" on "public"."messages"
as permissive for insert
to authenticated
wuth check (user_id = auth.uid());

SQL code snippets can be run against your Supabase database by heading over to your project's SQL Editor, pasting them into a new query, and clicking RUN.

Resources

ed leach
ed leach
~ a year ago

Jon, when I try to set the default value of messages - user_id to auth.uid() or (auth.uid()) I get an error: failed to update pg.columns with the given ID: must be owner of event trigger pgsodium_trg_mask_update