So, I developed a portfolio website that fetches repositories and details from GitHub and send it to my website. While using localhost everything was working fine but as i deployed the code in Vercel it is showing ERROR 401
Function to get repositories from the GitHub API using Bearer key authentication:
const axios = require(axios);const fetchrepositories = async (url,headers,retries = 3)=>{try{const response = await axios.get(url , {headers});return response.data;}catch(error){if(retres.error > 3 && error.response?.status === 403){console.warn(`Rate limit reached. Retrying in 60 seconds...`); await new Promise(resolve => setTimeout(resolve, 60000)); // Wait 60 seconds return fetchRepositories(url, headers, retries - 1);}throw error; }};module.exports = async (req, res) => { const username = 'coderanik'; // Replace with the GitHub username const apiUrl = `https://api.github.com/users/${username}/repos?sort=created&direction=desc`; const GITHUB_TOKEN = process.env.GITHUB_TOKEN || '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'; try { const response = await axios.get(apiUrl, { headers: { Authorization: `token ${GITHUB_TOKEN}` // Optional for higher rate limits } }); // Return only the top 6 repositories const recentRepos = response.data.slice(0, 6); res.status(200).json(recentRepos); } catch (error) { console.error('Error fetching repositories:', error.message); res.status(error.response?.status || 500).json({ error: 'Failed to fetch repositories' }); }};
Function to send the repositories in the frontend:
async function fetchRepositories() { try { const response = await fetch('/api/repositories'); // Calls the serverless function if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const repos = await response.json(); renderRepositories(repos); } catch (error) { document.getElementById('repositories').innerHTML = `<p>Error fetching repositories: ${error.message}</p>`; console.error("Failed to fetch repositories:", error.message); }}function renderRepositories(repos) { const repoContainer = document.getElementById('repositories'); repoContainer.innerHTML = ''; // Clear the loading message repos.forEach(repo => { const repoElement = document.createElement('div'); repoElement.className = 'repo'; repoElement.innerHTML = `<h3>${repo.name}</h3><p>Created At: ${new Date(repo.created_at).toLocaleString()}</p><p>Language: ${repo.language || 'Not specified'}</p><button onclick="window.open('${repo.html_url}', '_blank')">View on GitHub</button> `; repoContainer.appendChild(repoElement); });}fetchRepositories();
Code to start the server:
const express = require('express');const path = require('path');const app = express();// Serve static filesapp.use(express.static(path.join(__dirname, 'public')));// API routesapp.use('/api/repositories', require('./api/repositories'));// Start serverconst PORT = process.env.PORT || 3000;app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`);});