Back

How to build a public Tumblr integration: Building the Auth Flow

Aug 2, 20246 minute read

Hey there, fellow JavaScript enthusiasts! Ready to dive into the world of Tumblr integrations? Let's roll up our sleeves and build an auth flow that'll make your users say, "Wow, that was smooth!"

Introduction

Tumblr's API is a goldmine of creative content, and OAuth 2.0 is our key to unlocking it. We're going to walk through building a slick authorization flow that'll have your users connected to Tumblr faster than you can say "reblog."

Prerequisites

Before we jump in, make sure you've got:

  • Tumblr API credentials (if you don't have 'em, go grab 'em!)
  • Node.js and npm installed (you're a JS dev, so I'm sure you're covered)
  • A basic understanding of OAuth 2.0 (don't worry, we'll refresh your memory)

Setting up the project

Let's get our project off the ground:

mkdir tumblr-integration cd tumblr-integration npm init -y npm install express axios dotenv

Configuring environment variables

Create a .env file in your project root:

TUMBLR_API_KEY=your_api_key
TUMBLR_API_SECRET=your_api_secret
REDIRECT_URI=http://localhost:3000/callback

Pro tip: Don't forget to add .env to your .gitignore!

Implementing the authorization flow

Create authorization URL

First, let's craft that authorization URL:

const authUrl = `https://www.tumblr.com/oauth2/authorize?client_id=${process.env.TUMBLR_API_KEY}&response_type=code&redirect_uri=${encodeURIComponent(process.env.REDIRECT_URI)}`;

Now, when a user hits your auth endpoint, send them to this URL:

app.get('/auth', (req, res) => { res.redirect(authUrl); });

Handle authorization callback

Set up a route to catch that callback:

app.get('/callback', async (req, res) => { const { code } = req.query; try { const tokenResponse = await axios.post('https://api.tumblr.com/v2/oauth2/token', { grant_type: 'authorization_code', code, client_id: process.env.TUMBLR_API_KEY, client_secret: process.env.TUMBLR_API_SECRET, redirect_uri: process.env.REDIRECT_URI }); const { access_token, refresh_token } = tokenResponse.data; // Store these securely - we'll talk about this later! res.send('Authorization successful!'); } catch (error) { console.error('Error exchanging code for token:', error); res.status(500).send('Authorization failed'); } });

Implement token refresh mechanism

Keep those tokens fresh:

async function refreshAccessToken(refreshToken) { try { const response = await axios.post('https://api.tumblr.com/v2/oauth2/token', { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: process.env.TUMBLR_API_KEY, client_secret: process.env.TUMBLR_API_SECRET }); return response.data.access_token; } catch (error) { console.error('Error refreshing token:', error); throw error; } }

Making authenticated requests

Now for the fun part - using that shiny new token:

async function getUserInfo(accessToken) { try { const response = await axios.get('https://api.tumblr.com/v2/user/info', { headers: { Authorization: `Bearer ${accessToken}` } }); return response.data; } catch (error) { console.error('Error fetching user info:', error); throw error; } }

Error handling and edge cases

Always be prepared:

function handleAuthError(error) { if (error.response && error.response.status === 401) { // Token expired, refresh it return refreshAccessToken(refreshToken); } else { // Handle other errors console.error('Authentication error:', error); throw error; } }

Security considerations

  • Always use HTTPS in production
  • Store tokens securely (consider using encrypted cookies or a secure database)
  • Implement CSRF protection (use libraries like csurf)

Testing the integration

Manual testing:

  1. Start your server
  2. Navigate to your auth endpoint
  3. Go through the Tumblr authorization process
  4. Verify the callback is handled correctly

For automated testing, consider using Jest with mocked API responses.

Conclusion

And there you have it! You've just built a rock-solid auth flow for your Tumblr integration. Remember, this is just the beginning - now you can start building amazing features on top of this foundation.

Keep exploring the Tumblr API, and don't be afraid to push the boundaries. Happy coding, and may your integrations always be smooth and your tokens forever fresh!