Discover how to integrate Bolt.new AI with Garmin Connect. Follow our step-by-step guide to enhance your tracking and gain smarter insights.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
package.json
in your project’s root directory with the following content:
{
"name": "bolt-garmin-integration",
"version": "1.0.0",
"dependencies": {
"axios": "^0.27.2"
},
"scripts": {
"start": "node build/index.js"
}
}
Also, make sure to set environment variables for your Garmin Connect credentials. In your project settings or configuration file (depending on how Bolt.new AI manages secrets), add the following:
// GARMINCLIENTID: Your Garmin Client ID
// GARMINCLIENTSECRET: Your Garmin Client Secret
// GARMINREDIRECTURI: The URL Garmin Connect will redirect to after authentication
garmin.ts
in a folder called services
within your project. This file encapsulates the logic to interact with Garmin Connect’s OAuth endpoints and retrieve data.
import axios from 'axios';
const clientId = process.env.GARMINCLIENTID;
const clientSecret = process.env.GARMINCLIENTSECRET;
const redirectUri = process.env.GARMINREDIRECTURI;
if (!clientId || !clientSecret || !redirectUri) {
throw new Error('Missing Garmin Connect environment variables.');
}
/**
- Constructs the Garmin Connect authorization URL for OAuth login.
*/
export function getGarminAuthUrl(): string {
const baseUrl = 'https://connect.garmin.com/oauth/authorize';
const queryParams = new URLSearchParams({
response_type: 'code',
client_id: clientId,
redirect_uri: redirectUri,
scope: 'profile activity', // Adjust scopes as needed
state: 'custom_state' // You can use a random string for CSRF protection
});
return ${baseUrl}?${queryParams.toString()};
}
/**
- Exchanges the provided OAuth code for an access token.
*/
export async function exchangeCodeForToken(code: string): Promise<string> {
const tokenUrl = 'https://connect.garmin.com/oauth/token';
const params = new URLSearchParams({
granttype: 'authorizationcode',
code,
redirect_uri: redirectUri,
client_id: clientId,
client_secret: clientSecret
});
const response = await axios.post(tokenUrl, params);
if (response.data && response.data.access_token) {
return response.data.access_token;
}
throw new Error('Failed to retrieve access token from Garmin Connect.');
}
/**
- Uses the access token to fetch user data from Garmin Connect.
*/
export async function fetchGarminData(token: string): Promise<any> {
const apiUrl = 'https://connect.garmin.com/api/userdata';
const response = await axios.get(apiUrl, {
headers: {
Authorization: Bearer ${token}
}
});
return response.data;
}
index.ts
) and add the following route handlers. These routes will redirect the user to Garmin Connect’s login page and process the callback containing the OAuth code.
import express from 'express';
import {
getGarminAuthUrl,
exchangeCodeForToken,
fetchGarminData
} from './services/garmin';
const app = express();
const PORT = process.env.PORT || 3000;
/**
- Route to redirect the user to Garmin Connect’s OAuth login.
*/
app.get('/auth/garmin', (req, res) => {
const authUrl = getGarminAuthUrl();
res.redirect(authUrl);
});
/**
- Callback route for Garmin Connect OAuth.
*/
app.get('/callback/garmin', async (req, res) => {
const code = req.query.code;
if (!code) {
return res.status(400).send('Missing code parameter.');
}
try {
const token = await exchangeCodeForToken(code.toString());
// Optionally, fetch Garmin user data
const userData = await fetchGarminData(token);
res.json({ token, userData });
} catch (error) {
console.error(error);
res.status(500).send('An error occurred during Garmin authentication.');
}
});
app.listen(PORT, () => {
console.log(Server is running on port ${PORT});
});
// GARMINCLIENTID=yourgarminclient_id
// GARMINCLIENTSECRET=yourgarminclient_secret
// GARMINREDIRECTURI=yourredirecturi (e.g., https://your-app.bolt.new/callback/garmin)
// Step 1: Open your app and visit the route: /auth/garmin. This should redirect you to Garmin Connect’s login page.
// Step 2: After logging in on Garmin Connect, you will be redirected to /callback/garmin where the app exchanges the code for a token and fetches user data.
// Step 3: If successful, you'll see a JSON response containing the access token and Garmin user data.
package.json
, garmin.ts
, and your main file such as index.ts
) are saved in the correct directories as described. Adjust endpoint URLs and scopes according to Garmin Connect’s current API documentation and your project requirements.When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.