Hey there, I'm trying to configure an API route in NextJS. I'm using NextJS version 14.2.5 and have been trying to prompt ChatGPT to set up a basic route but it doesn't seem that it is working as intended so I expect ChatGPT is out of date / misinformed about proper implementation for API routes in Next.
src/app/api/credentials/route.js
// File: src/app/api/credentials/route.js
import { NextResponse } from 'next/server';
export async function GET() {
console.log('API route /api/credentials is called'); // Initial log to confirm route is called
try {
// Fetch environment variables securely
const careerOneStopUserID = process.env.CAREER_ONESTOP_USER_ID;
const careerOneStopKey = process.env.CAREER_ONESTOP_KEY;
const mapboxAccessToken = process.env.MAPBOX_ACCESS_TOKEN;
// Log the fetched environment variables (Ensure you sanitize these logs in production)
console.log('Fetched environment variables:', {
careerOneStopUserID: careerOneStopUserID ? 'Loaded' : 'Missing',
careerOneStopKey: careerOneStopKey ? 'Loaded' : 'Missing',
mapboxAccessToken: mapboxAccessToken ? 'Loaded' : 'Missing',
});
// Ensure all required environment variables are set
if (!careerOneStopUserID || !careerOneStopKey || !mapboxAccessToken) {
console.error('Missing environment variables');
return NextResponse.json({ error: 'Missing environment variables' }, { status: 500 });
}
// Return credentials as JSON
return NextResponse.json({
careerOneStopUserID,
careerOneStopKey,
mapboxAccessToken,
});
} catch (error) {
// Log any errors that occur during the fetch
console.error('Error fetching credentials:', error);
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
}
}
However, I am getting a 500 Response and the console log at the start of try block never logs implying we're not actually hitting the API route. For reference, this is the call in my JS:
// Function to fetch API credentials from the server
const fetchApiCredentials = async () => {
try {
const response = await fetch('/api/credentials');
if (!response.ok) {
throw new Error('Failed to fetch API credentials');
}
const credentials = await response.json();
return credentials;
} catch (error) {
console.error("Failed to fetch API credentials", error);
return null;
}
};
What am I missing here? How can I modify this to work properly with the latest NextJS API Routes implementation?
Thank you! ❤️