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

The video.play() function encountered an unhandled rejection with a (notallowederror) on IOS

Using peer.js to stream video on a React app addVideoStream(videoElement: HTMLVideoElement, stream: MediaStream) { videoElement.srcObject = stream videoElement?.addEventListener('loadedmetadata', () => { videoElement.play() ...

Unforeseen issue within Vuejs-nuxt (SSR Mode) is preventing the retrieval of the UserUUID through the getter in plugins, resulting in an unexpected '

In my vuejs-nuxt project using SSR mode, I encountered an issue when trying to call a socket event. I need to pass the userID to the socket from the store. The GetUserUUID getter functions properly in all other APIs except when called from the "plugin/sock ...

The intersection observer fails to detect any new elements or entries that are appended to the page after it has

When I press the "add section" button to create a new section, the intersection observer does not seem to observe it. Even when I try to run the observer again after pressing the button, it still doesn't work. I suspect that I need to reassign the `se ...

Ways to retrieve text like innerText that functions across all web browsers

I need to retrieve the text from a Twitter Follow button, like on https://twitter.com/Google/followers Using document.getElementsByClassName("user-actions-follow-button js-follow-btn follow-button")[0].innerText correctly displays the text as: Follow ...

What sets Gulp-Browserify apart from regular Browserify?

After switching from Grunt to Gulp recently, I find myself still learning the ropes. Can anyone shed some light on the distinction between using Gulp-Browserify versus just Browserify? I've heard that Gulp-Browserify has been blacklisted and seen som ...

What is the best way to filter out duplicate objects in JavaScript?

I have the following code snippet: let self = this; self.rows = []; self.data.payload.forEach(function (item, index) { if (!(self.rows.includes(item))) { self.rows.push(item); } }); The issue is that includes always returns false. Each ite ...

Challenges with extracting and organizing dates using JavaScript regular expressions

My task involves organizing these text rows into specific groups based on certain criteria and names. Il Messaggero Roma 22 settembre 2023 Il Messaggero Roma 21 settembre 2023 Il Messaggero 22 settembre 2023 Il Messaggero 21 settembre 2023 Il Messaggero Ro ...

How can I launch five separate instances of Chrome on a Selenium grid, each with a different URL?

I have a list of URLs saved in a JSON file, structured like this: { "urls": [ "http://www.google.com/", "http://www.stackoverflow.com" ] } Currently, these URLs are being opened sequentially by the Selenium WebDriver JavaScript manager on a ...

What is the best method for combining numerous tiles within a level in Kaboom JS?

Creating a level in kaboomJS with a extensive tile map collisions can sometimes result in slower performance. I'm exploring options to optimize this process, such as potentially merging multiple tiles together so that a whole row of blocks could funct ...

Creating a Dynamic Form with jQuery, AJAX, PHP, and MySQL for Multiple Input Fields

Success! The code is now functional. <form name="registration" id="registration" action="" method="post"> <div id="reg_names"> <div class="control-group"> <label>Name</label> <div class= ...

Determining the best use-case for a React framework like Next or Gatsby versus opting for Create React App

As I delve into the world of React and JavaScript, I find myself in the fast-paced prototyping stage. I can't help but ponder at what point developers choose to utilize frameworks like Next.js or Gatsby.js over the usual Create React App. I'm pa ...

Issues with object changes not reflecting in Vue.js 2.0 component rendering

I am facing an issue where my object is not updating immediately after a click event. It appears that a manual refresh or clicking on another element is necessary for the changes to take effect. How can I ensure that the object updates without the need for ...

File reading and processing must be completed before attempting to write to a new file. This is a promise-related stipulation

Feeling completely lost and stuck in a rut. Promises seemed straightforward until I actually tried to implement them. Sharing my basic code here without any promise attempts for simplicity's sake. After taking a few months hiatus from this, I returned ...

Tips for storing and replicating jQuery events

I am working on saving jQuery events in a database. // This Function is called On Click function trackevent(event){ window.events.push(event) } $.each(window.events, function(i, item){ console.log(i +" - "+ $.parseJSON(item)); }); The events a ...

Transforming an array of HashMaps into a JSON object within a servlet and showcasing it on a JSP page

Looking to extract all table rows and store them in an array of hashmaps, then convert them into a JSON object to be sent to a JSP page using Ajax and jQuery. Struggling with displaying the content on the JSP page. I've written the code below but need ...

Issue with JS jQuery: The click event on an li element within an expanded ul does not function properly

I have built a basic webpage to explore jQuery. However, there is an issue that arises when I click on the "Button: another one." It seems to interfere with the event of clicking on the li element, causing it to glitch and not respond. Here is the code: JS ...

Memory Match: Picture Edition

In this memory game, letters are used. I had considered changing it to a picture-based game, but I faced difficulty in generating images and incorporating them into the array. <script> var memory_array = ['A', 'A', 'B&ap ...

When attempting to execute a promise within a test, encountering a 400 error in a NodeJS environment

I recently started using Contentful, a new JavaScript library for creating static websites. My goal is to incorporate it into my Node.js project. To achieve this, I developed an app file called getContent.js: 'use strict'; var contentful = req ...

Angular.js filter issue: "Error: textProvider is not recognized provider"

I implemented a custom filter for my AngularJS project that is similar to the one in this fiddle http://jsfiddle.net/tUyyx/. myapp.filter('truncate',function(text,length){ var end = "..." text = text.replace(/\w\S*/g, function( ...

Footer refusing to stay fixed at the bottom of the viewport

Currently, I am utilizing fullpage.js with scrolloverflow.js activated on the second section. In this setup, I would like to have a footer that remains fixed at the bottom of the viewport for the second section only. However, instead of achieving this desi ...