supabase / supabase-js

An isomorphic Javascript client for Supabase. Query your Supabase database, subscribe to realtime events, upload and download files, browse typescript examples, invoke postgres functions via rpc, invoke supabase edge functions, query pgvector.
https://supabase.com
MIT License
2.86k stars 220 forks source link

Empty Data Array Returned when Fetching from Supabase using Node.js and node-fetch #938

Open DeekshithRajBasa opened 4 months ago

DeekshithRajBasa commented 4 months ago

Bug report

I am encountering an issue when trying to fetch data from Supabase using Node.js and the node-fetch library. The response I receive is showing an empty data array (data: []) even though I expect data to be present in the 'contacts' table. It's worth noting that the request works as expected in Postman when hitting directly to https://${subdomain}.supabase.co/rest/v1/contacts when passing the auth token and API key, but encounters issues when making the same request in Node.js to the same url.

To Reproduce

  1. Replace the usage of the Supabase SDK with a direct request to the Supabase endpoint URL in a Node.js application. (https://${subdomain}.supabase.co/rest/v1/table-name)
  2. Make a GET request to the Supabase endpoint URL to fetch data.
  3. It works well in postman, but not through Node.js

Expected behavior

I expect to receive the data from the 'contacts' table when making a GET request to the Supabase endpoint, similar to the successful response in Postman.

Screenshots

Directly hitting https://${subdomain}.supabase.co/rest/v1/contacts from postman:

Screenshot 2024-01-03 at 12 27 56 PM

Trying to make call https://${subdomain}.supabase.co/rest/v1/contacts through Node.js

Here's the code

const { environment } = require('../../../db/supabase-client.js');
const fetch = require('node-fetch');

exports.getContacts = async (req, res) => {
    const access_token = req.headers.authorization;
    try {
        const headers = {
            'Content-Type': 'application/json',
            'Authorization': access_token,
            'Apikey': environment.supabaseKey,
            'Accept': '*/*',
        };
        const _res = await fetch('https://' + environment.subdomain + '.supabase.co/rest/v1/contacts', {
            method: 'GET',
            headers: headers,
        });

        if (_res.ok) {
            const _data = await _res.json();
            if (_data) {
                console.log(_data);
                res.status(200).send(_data);
            }
        } else {
            console.error('Failed to fetch data:', _res.statusText);
            res.status(_res.status).json({ message: _res.statusText });
        }

    } catch (error) {
        console.error('Unexpected error:', error);
        res.status(500).json({ message: '500', error });
    }
};
Screenshot 2024-01-03 at 12 26 11 PM

System information