Supabase guidelines for utilizing getServerSideProps in Next.js

I am creating a Trello-like application using Next.js and Supabase as my backend as a service.

Within my Supabase table, I have set up certain policies:

https://i.sstatic.net/gl5Si.png

The policies function correctly on the client-side with this code snippet:

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

However, when attempting to retrieve board information in getServerSideProps, it consistently returns null. I know that for accessing the authenticated user on the server-side, you must use

supabase.auth.api.getUserByCookie(context.req)
. So, I am unsure if there is something I am overlooking, as I couldn't find any relevant information regarding this issue.

Does anyone have experience dealing with this scenario?

[Edited]

Below is the code within the getServerSideProps:

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,
    },
  };
};

Answer №1

My approach may not be the most optimal, but I managed to solve it with some guidance from a discussion on Github https://github.com/supabase/supabase/discussions/1094#discussioncomment-714633

As far as I can tell, the Supabase client behaves slightly differently on the server side compared to in a browser (lacks session handling). Extracting the token from cookies and setting it for the client allows requests to Supabase to be made on behalf of an 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(...

Answer №2

Upon investigation, I discovered that the request is being sent to the database with the anonymous key rather than the authenticated JWT in the getSSProps function. The reason for this behavior is unclear to me at this time; it's uncertain whether it is intentional or not. Adding the rule role() = 'anon' allows it to work, although this may not align with what you actually desire.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Custom Type Guard Leads to Intersection Type Outcome

Recently, I've been experimenting with Typescript and decided to explore the creation of an innovative Either type that could distinguish between success and failure scenarios. Utilizing a user-defined type guard, I managed to precisely narrow down th ...

The notion of await goes beyond simply waiting for a promise to be fulfilled

Hey there everyone! I've been struggling with a problem for some time now, and I just can't seem to figure it out by simply searching online. That's why I'm turning to all of you for help. Situation: I'm working on a small applic ...

Next.js 13 React Server Component not displaying updated data upon build completion

I have a React Server Component that retrieves its data at build time and does not reload it while the site is running. I expected it to fetch the data once when the server component is first rendered. Is there a way to force this server component to relo ...

The Ionic search bar will only initiate a search once the keyboard is no longer in view

In my Ionic application, I have implemented a search bar to filter and search through a list. The filtering process is triggered as soon as I start typing in the search bar. However, the updated results are not displayed on the screen until I manually hide ...

How can I emphasize the React Material UI TextField "Cell" within a React Material UI Table?

Currently, I am working on a project using React Material UI along with TypeScript. In one part of the application, there is a Material UI Table that includes a column of Material TextFields in each row. The goal is to highlight the entire table cell when ...

OnPush strategy and template updates: Propagating modifications to the parent component

I am currently facing an issue with a parent component that consists of two templates. The first template simply displays data-bound text, while the second template contains a child component responsible for updating the data model. Both the parent and chi ...

Having trouble retrieving data in the service. Unable to subscribe to it from other components

userService.ts private APIUrl: string = environment.APIUrl; constructor(private inService: API, private httpClient: HttpClient) { } private _userDataDashboard$ = new ReplaySubject<UserDetailsDashboard>(1); getUserDetailsSubject(): Obser ...

What is the process for including a selected-by option in a VIS network graph?

I'm trying to outline the neighboring nodes of the node that has been selected (highlightNearest). https://i.sstatic.net/lynhu.png Unfortunately, I haven't had success achieving this using JavaScript. Link to StackBlitz ...

Attempting to develop a server component that will transmit a JSON result set from a MySQL database located on the local server. What is the best method to send the server object (RowDataPacket) to the

After successfully rendering server-side pages and creating forms with react hooks for database updates, I encountered a challenge in integrating Ag-Grid into my application. Despite being able to retrieve data from the database using the mysql2 module and ...

Unprocessed Promise Rejection Alert: The function res.status is not recognized as a valid function (NEXT JS)

When I console.log(response), I see the result in the terminal. However, when I use res.status(200).json(response), I encounter an error in my Next.js project: Not Found in the browser. router.get("/api/backendData", async (req, res) => { dbConne ...

Fulfill the specified amounts for each row within a collection of items

I have an array of objects containing quantities. Each object includes a key indicating the amount to fill (amountToFill) and another key representing the already filled amount (amountFilled). The goal is to specify a quantity (amount: number = 50;) and au ...

Can you explain the purpose of the GenericType parameter in a TypeScript promise declaration for me?

I am curious about whether the generic type in Typescript's Promise<GenericType> definition indicates the type of the object passed to the then handler. As an example, consider the following code: const pr:Promise<Array<Number>> ...

Develop a personalized React route component using TypeScript. The error message "Property 'path' does not exist on type... RouteProps" is displayed

I am currently working on creating my own route component using React. Although I am new to TypeScript, I believe that is the root cause of the issue I am facing. import * as React from 'react' import { ApplicationState } from '../../store& ...

Having trouble initialising an array of objects in TypeScript? (TS1109: Expression expected)

While working on my project, I encountered a problem when trying to create an array of objects: Error TS1110: Type expected Error TS1109: Expression expected https://i.sstatic.net/Y5qb8.png This is how my array is structured: export let COUNTRIES: A ...

Is it normal for the Array of Observables to be empty upon initial page load, only to contain content later

Currently, I am working on integrating ngx-infinite-scroll functionality. My goal is to extract the initial 5 posts from my "posts" array and populate them into the "shownPosts" array at the beginning. Subsequently, as the user continues scrolling down, I ...

Discovering the most recent 10 date elements in a JSON object within a React application

I have an array of objects containing a date element. My goal is to identify the 10 most recent dates from this element and display them in a table format. When I attempt to render these dates using a mapping technique that targets each data with data.date ...

The interactive Material UI Radio buttons are not responding to click events due to dynamic generation

Click here to see the demo in action: https://codesandbox.io/s/material-demo-9fwlz I expected this code to produce checkable radio elements, but it doesn't seem to be working correctly. Can anyone identify what might be causing the issue? This code s ...

A secure way to perform a deep update on any type, even if it is completely different from the original

Is there a method to eliminate the as any in the update_substate function? It seems type-safe when directly invoking the update_state function, so it should also be safe when invoked indirectly, right? These functions are meant to be lightweight helpers ...

Visual Studio Code continues to compile code automatically without requiring me to save any changes

Question: VSC triggers compilation even without any file changes in Angular(6) project ng serve It's frustrating when Visual Studio Code starts compiling repeatedly, even when no changes have been made. How can I prevent this from happening? I&apos ...

Creating a powerful combination: Building an Express backend integrated with a sleek React front-end

I am facing a bit of challenge in setting up the connection between my front-end and back-end logic. I'm simply trying to fetch data from Express to test if everything is working correctly, but it's proving to be quite difficult. Additionally, I ...