Pedro Gómez
Pedro Gómez

Reputation: 53

Supabase policies on getServerSideProps - Next.js

I'm crafting a Trello clone with Next.js and Supabase as a BaaS.

In my Supabase table I have this policies:

enter image description here

Policies are working grate on client side with the following code:

const { data } = await supabase
    .from<BoardType>('board')
    .select('*')
    .eq('id', board.id)
    .single();

but when I try to get the board info on getServerSideProps it doesn't work, it return null all the time. I know that, for example, if you want to get the authenticated user on server side, you have to use supabase.auth.api.getUserByCookie(context.req) so I don't know if there's something I'm missing, but I couldn't find anything related to that.

Does anyone know how to handle that?

[Edited]

Here is the getServerSideProps code:

export const getServerSideProps: GetServerSideProps<BoardSlugProps> = async ({
  query,
}) => {
  const { data } = await supabase
    .from<BoardType>('board')
    .select('*')
    .eq('id', query.slug as string)
    .single();
  console.log(data);
  return {
    props: {
      board: data,
    },
  };
};

Upvotes: 3

Views: 2107

Answers (2)

Josiah Mortenson
Josiah Mortenson

Reputation: 96

Might not be the best way, but this is how I solved it with some hints from this Github discussion https://github.com/supabase/supabase/discussions/1094#discussioncomment-714633

From my understanding, the Supabase client is a little different on the server compared to in the browser (no session). Pulling the token out of cookies and adding it to the client lets the requests to supabase be from the authenticated user.

export const getServerSideProps: GetServerSideProps = ({ req }) => {
  const { user, token } = await supabase.auth.api.getUserByCookie(req);
  supabase.auth.setAuth(token);

  const { data, error } = await supabase.from(...

Upvotes: 4

vskorepa
vskorepa

Reputation: 53

I found out it sends the request on the datebase with the anon key and not the authenticated jwt in the getSSProps. not sure why or if its intentional. If you add the role() = 'anon' rule it works, but that is not what you want in my opinion.

Upvotes: 1

Related Questions