#API Routes in NextJS

7 messages · Page 1 of 1 (latest)

scenic shuttle
#

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! ❤️

brave coralBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

scenic shuttle
#

I modified it to use handler which I saw in another thread here:

// File: src/app/api/credentials/route.js

import { NextResponse } from 'next/server';

export default async function handler(req, res) {
    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 });
    }
}

Now I'm getting a 405 instead

outer atlas
scenic shuttle
green skiff
#

Did you set the environment variables in .env.local file?

dusk parcel
#

500 errors come with an error log in the terminal. Check it.