/bolt.new-ai-integrations

Bolt.new AI and Fitbit API integration: Step-by-Step Guide 2025

Master the integration of Bolt.new AI with the Fitbit API. Follow our step-by-step guide to merge advanced AI with fitness tracking for enhanced health insights.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to integrate Bolt.new AI with Fitbit API?

 

Prerequisites

 
  • Setup a Fitbit Developer account at https://dev.fitbit.com and create a new application to obtain your clientid and clientsecret.
  • Note your app’s callback URL; this will be used as the redirect URI (e.g. https://your-app.com/fitbit/callback).
  • Make sure you have your Bolt.new AI project open.

 

Adding Necessary Dependencies

 
  • Since Bolt.new AI doesn’t have a terminal, add a package.json file in the root of your project if it doesn’t exist yet.
  • Add the dependency for axios by pasting the following JSON code into the file. This ensures that the required modules are installed when the project loads.

{
  "name": "bolt-fitbit-integration",
  "version": "1.0.0",
  "dependencies": {
    "axios": "^0.27.2"
  }
}

 

Creating the Fitbit API Integration File

 
  • Create a new file named fitbit.ts in your project’s source directory.
  • This file will contain functions to generate the Fitbit authorization URL and to exchange the authorization code for an access token.
  • Paste the code snippet below into fitbit.ts. Replace environment variables as needed.

import axios from 'axios';

const CLIENTID = process.env.FITBITCLIENT_ID as string;
const CLIENTSECRET = process.env.FITBITCLIENT_SECRET as string;
const REDIRECTURI = process.env.FITBITREDIRECT_URI as string;

export function getAuthUrl(): string {
  const scopes = 'activity profile';
  const url = https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=${CLIENT_ID}&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&scope=${encodeURIComponent(scopes)};
  return url;
}

export async function exchangeCodeForToken(code: string): Promise {
  const tokenUrl = 'https://api.fitbit.com/oauth2/token';
  const authHeader = Buffer.from(${CLIENT_ID}:${CLIENT_SECRET}).toString('base64');

  const params = new URLSearchParams();
  params.append('clientid', CLIENTID);
  params.append('granttype', 'authorizationcode');
  params.append('redirecturi', REDIRECTURI);
  params.append('code', code);

  try {
    const response = await axios.post(tokenUrl, params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': Basic ${authHeader}
      }
    });
    return response.data;
  } catch (error) {
    console.error('Error exchanging code for token:', error);
    throw error;
  }
}

 

Creating Route Handlers for Authentication

 
  • Create a new file named routes.ts in your project’s source directory to handle HTTP routes for Fitbit OAuth.
  • Insert the following code which uses the functions from fitbit.ts:

import express from 'express';
import { getAuthUrl, exchangeCodeForToken } from './fitbit';

const router = express.Router();

// Route to redirect users to Fitbit for authorization
router.get('/fitbit/auth', (req, res) => {
  const authUrl = getAuthUrl();
  res.redirect(authUrl);
});

// Callback route to handle Fitbit response
router.get('/fitbit/callback', async (req, res) => {
  const code = req.query.code as string;
  if (!code) {
    return res.status(400).send('Authorization code not provided.');
  }
  try {
    const tokenData = await exchangeCodeForToken(code);
    // Process the tokenData (e.g. save tokens for future API calls)
    res.json(tokenData);
  } catch (error) {
    res.status(500).send('Error exchanging code for token.');
  }
});

export default router;

 

Integrating Routes with Your Main Application

 
  • Open your main application file (commonly index.ts or app.ts) in your Bolt.new AI project.
  • Import the Express framework and the routes from routes.ts.
  • Add the routes to your app and make sure your server listens on the correct port. Insert the following snippet into your main file:

import express from 'express';
import fitbitRoutes from './routes';

const app = express();

// Middleware for parsing JSON if needed
app.use(express.json());

// Use the Fitbit API routes
app.use(fitbitRoutes);

// Default route to test the server
app.get('/', (req, res) => {
  res.send('Bolt.new AI Fitbit integration is running.');
});

// Start the server on the port provided by Bolt.new or a default port
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(Server is listening on port ${PORT});
});

 

Configuring Environment Variables

 
  • Because Bolt.new AI does not expose a terminal for setting environment variables, use its built-in secrets feature.
  • Add the following keys and their corresponding values (from your Fitbit Developer app) using your project’s environment variable configuration:
    • FITBITCLIENTID – your Fitbit client ID
    • FITBITCLIENTSECRET – your Fitbit client secret
    • FITBITREDIRECTURI – the callback URL you registered with Fitbit

 

Testing Your Integration

 
  • Deploy your project on Bolt.new AI by clicking the Run button.
  • Visit the default route (e.g. /) to ensure your server is up.
  • Navigate to /fitbit/auth to be redirected to Fitbit’s authorization page. After authorizing, Fitbit will redirect you to your callback URL where the access token details are returned as JSON.

 

Final Notes

 
  • Make sure to handle and store the token data securely if you plan to make additional API calls on behalf of the user.
  • This guide assumes the Bolt.new AI project supports Express-based routing. Adjust accordingly if your project structure is different.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022