Next.js Discord

Discord Forum

API Routes in NextJS

Unanswered
Oak apple gall wasp posted this in #help-forum
Open in Discord
Oak apple gall waspOP
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! ❤️

5 Replies

Oak apple gall waspOP
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
@Oak apple gall wasp I modified it to use handler which I saw in another thread here: js // 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
Sloth bear
This is for pages router
The first step is the correct one
@Sloth bear This is for pages router The first step is the correct one
Oak apple gall waspOP
It's still returning a 500 when I try it the first way, what might the issue be? Thanks for the response btw!
Gouty oak gall
Did you set the environment variables in .env.local file?
500 errors come with an error log in the terminal. Check it.