Guidelines for accessing the Coinbase exchange API from a localhost

Following the instructions in the Coinbase Cloud documentation, I tried running this code on the client side using JavaScript:

  const options = {
  method: 'GET',
  headers: {
    Accept: 'application/json',
    'cb-access-key': 'Apikey',
    'cb-access-passphrase': 'Mypassphrase',
    'cb-access-sign': cb_access_sign,
    'cb-access-timestamp': cb_access_timestamp
  }
};

fetch('https://api.exchange.coinbase.com/coinbase-accounts', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));
  

I encountered the same issue when attempting to do it with axios.

An error was displayed in the console:

"Access to fetch at 'https://api.exchange.coinbase.com/coinbase-accounts' from origin 'http://localhost:3000' has been blocked by CORS policy:
Request header field cb-access-passphrase is not allowed by Access-Control-Allow-Headers in preflight response."

Could someone please advise on what I might be doing incorrectly?

Answer №1

In order to achieve this task, it is not possible in the browser alone; you have to execute it from the web server. One option is to showcase the data when the page initiates or opt for vue/react and customize your own communication with the webserver.

Additional note: attempting to perform this action directly in the browser may expose your keys...

Answer №2

Coinbase API has a misconfigured CORS setup, making it difficult to test in a dev environment, potentially requiring API calls from a server. One solution is to use a proxy like cors-anywhere, which changes the flow of API calls:

Client (localhost:3000) <-> Coinbase API (api.exchange.coinbase.com)

to

Client (localhost:3000) <-> Proxy Server (www.your-proxy-server.com) <-> Coinbase API (api.exchange.coinbase.com)

In this setup, Coinbase will only see requests coming from the proxy server and won't know where the data is being sent back from. Cors-anywhere will also include headers and data along with the request.

Avoid using public cors-anywhere servers for testing unless necessary; setting up your own is recommended.

Implementation with Firebase

I utilized cors-server to set up mine using Firebase functions. Your Firebase functions should resemble the following:

const {onRequest} = require("firebase-functions/v2/https");
const corsAnywhere = require('cors-anywhere');
const cors = require("cors")({origin:true})

const corsServer = corsAnywhere.createServer({
    originWhitelist: [
      'http://localhost:3000',
    ],
    requireHeader: ['origin', 'x-requested-with'],
    removeHeaders: ['cookie', 'cookie2'],
});

exports.proxy = onRequest((request, response) => {
  cors(request,response,() =>{
    corsServer.emit('request', request, response);
  })    
});

and an example of a request in your client code

return(
       axios({
                url: `https://proxy-your-function-id.a.run.app/https://api.exchange.coinbase.com/profiles`,
                headers: await getHeaders(options),
                method: 'GET',
                data: options.body
             }).then((response)=>{
                return(response)
             }).catch((err)=>{
                return(err.response)
      })
)

Note: Coinbase Pro and its API will be discontinued by the end of 2022. However, Coinbase exchange and its API will still be accessible at . Pro users will be transitioned to Advanced Trading on the main platform, using oAuth for API linkage or standard keys for personal projects.

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

Utilizing Stored Variables and Random Numbers in Selenium IDE

Can you explain how Selenium IDE handles stored variables (stored text) and random numbers? I've been trying to combine the two without much success. For example: <td>type<td> <td>css=input.some-text</td> <td>javascript ...

Why does Froala Editor not maintain formatting when retrieving data from the database?

I've been using the Froala editor to add content on my website, and it's doing well for inserting data into the database. However, I'm facing an issue when retrieving data from the database as it doesn't maintain the original formatting ...

An unexpected 'undefined' occasionally tacked onto 1% of the URLs visitors requested on my website starting from June 12, 2012

Ever since June 12, 2012 at 11:20 TU, I have been noticing strange errors in my varnish/apache logs. At times, after a user has requested a page, I observe a similar request moments later but with the URL string after the last "/" being replaced by "undef ...

I am trying to access a value saved in a service in Angular 8 component and use it in other services. Can anyone help

Setting a value through a component export class UniqueComponent { constructor(service:UniqueService){ } count =0 ; onRefresh(){ this.service.count = 1; } } Using the value in the service UniqueService{ count:any; doSomething(){ //using count ...

Redirecting JavaScript form to search engine

I am struggling with creating a form that enables a user to input text and then directs them to a specified search engine with the input as the query. I am encountering difficulties in getting the JavaScript to properly redirect. An interesting observatio ...

VueJS does not show a component if it is contained within a v-if or v-show directive

My goal is to show a component when the 'Add Patient' button is clicked using a v-if directive: // within <template></template> <button type="button" class="btn btn-info" @click="showPatientForm">Ad ...

Images are not being shown by Glide JS

I have implemented the Glide JS carousel within a VueJS project to showcase multiple images, however, I am encountering an issue where only the first image is being displayed. The <img/> tag has the correct src URL for all three images, but only th ...

Creating a Vertical Navbar Dropdown in Bootstrap 3.0 Without Appending to the Last List Item Only

Currently, I'm in the process of creating a panel layout that features an elegant vertical navbar. Although everything seems to be aligned correctly and I've managed to implement a dropdown menu in a vertical layout, it keeps appending to the las ...

Executing multiple nested `getJSON` requests in a synchronous manner using jQuery

I am facing an issue with my code that connects to an API using $.getJSON. It retrieves JSON data and then iterates three times through a for loop because the data has 3 objects. During each of these iterations, it makes another $.getJSON call to fetch spe ...

Intersecting object identification, fresh Function

I'm currently utilizing the "Sinova / Collisions" library on GitHub along with Node.js. The library can be found at https://github.com/Sinova/Collisions. I am in need of a function that allows me to delete all data at once, as the current function for ...

Is there a way to generate and transmit a text file using XmlHttpRequest or $.ajax?

The server is anticipating an html or txt file to be sent from a form named "websitetopdf". The file is dynamically created on client javascript and should only function properly on Chrome. Below is the form that needs to be used for sending: <form ac ...

Visuals and PDF Generation Tool

Trying to generate project report pdf's using pdfmake has presented a challenge when it comes to displaying images. A function I have for creating a pdfmake "object" looks like this: function singleProject(data) { return { text: "Project ...

Can you share the method for concatenating an object at a specific index within an Array using JavaScript?

Currently, I have an array arr = [object1, object2, object3]. After removing the second index, the array now looks like arr = [object1, object3], and I am looking to add back the removed object2 at its original position in the array so that it becomes a ...

Is there a way for me to determine if the HTML code is creating a new line?

Here is my code snippet: <div id="box"> <p> 123 </p> <p> abc </p> </div> <script> var html = document.getElementById("box").innerHTML; for (var i = 0, len = html.length; i & ...

Adjusting the content within a text area using an AngularJS service

I am currently editing text in a textarea within the admin view and I would like to display it through an angular service on the user view. However, I want the text to be displayed in multiple rows, maintaining the same format that I entered in the textare ...

Deliver a message using a loop in jade

I'm struggling with posting a request in Node and Jade using a specific ID. For instance, if Node returns a list of books : res.render('tests', {books: books}); In my Jade template, I display all the books by iterating through them. b ...

Issue with validating alphanumeric value with multiple regex patterns that allow special characters

I have created a regular expression to validate input names that must start with an alphanumeric character and allow certain special characters. However, it seems to be accepting invalid input such as "sample#@#@invalid" even though I am only allowing sp ...

Error: Headers cannot be set after they have already been sent, resulting in an Unhandled Promise Rejection with rejection id 2

I'm a beginner with Node.js and I've been using express.js. In a section of my code, I'm trying to retrieve data from a form via AJAX and store it in a variable called url. I have access to request.body, but I'm encountering an issue wh ...

Tips for maintaining the particles.js interaction while ensuring it stays under other elements

I have incorporated particle.js as a background element. By adjusting the z-index, I successfully positioned it in the background. While exploring solutions on the Github issues page, I came across a suggestion involving the z-index and this code snippet: ...

Utilizing map in React JS to simultaneously execute various functions

Currently, I am working on parsing an array in React JS. Here is an example of my array (it can change dynamically): [ "save", "save", "not", "save"] The objective is to create a function that triggers another funct ...