Implementing Coinbase Connect (OAuth2) in Node

Creating our App

First, we want to create a new application. We’ll create a new directory, and then run “npm init” to generate a new project, using the default values. Then re run “npm install --save express”. Within this directory we want to create an index.js file. For the purpose of this tutorial we will be working within this folder, but you can easily refactor your code.

Coinbase Connect

The basic flow of information can be seen in Coinbase’s documentation. I won’t go through this in detail because they do a pretty good job. Be mindful that the Token URL is incorrect here, it should be https://api.coinbase.com/oauth/token . This flow from server to Coinbase’s server is pretty standard for Oauth2, but there is one extra step as Coinbase makes the user exchange the code returned in the initial request for an access token before you can return a user’s data. Most of these steps will fortunately be taken care of with the Passport Authentication library. I have build out a working version of this in React without utilizing the library, and it’s a little trickier!

Coinbase Strategy

Now let’s pass the correct arguments to the Coinbase Strategy. After reading the documentation, we discover the necessary options that we add to the two CoinbaseStrategy() arguments.

Handling Routes

Next we must handle route handlers so that users get passed into this Passport / Coinbase flow we just set up. Coinbase will call the second URL. We add the following routes:

Testing OAuth2

Now that we have setup most of our flow, let’s see if it’s working correctly. Start your server with “node index.js”, and head to http://localhost:3000/auth/coinbase. This should push you into the flow, and send you to a Coinbase page to sign in. Once you sign in and allow access, it will look like the web page has broken. Go into your terminal, and you should see your access token, refresh token, and profile information logged to the console. Passport helps us through all the authentication intermediary steps, much easier than coding this by hand. If you don’t, go back and check for typos in your code!

Conclusion

I hope this was a straightforward setup of OAuth2 for Coinbase for you. Feel free to reach out with any questions you may have!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store