Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
14
rated 0 times [  15] [ 1]  / answers: 1 / hits: 15314  / 3 Years ago, sat, june 19, 2021, 12:00:00

I created an API in next JS (in the pages/api folder) and I used it on a page in the pages folder.


When I run on the localhost (development stage), the API can be called correctly. But when I deploy to Vercel there is an error during build.


build


This is my code when i call the API which is in the pages/api folder


export const getStaticProps = async () => {
const baseUrlDribble = 'https://api.dribbble.com/v2';
const baseUrl = process.env.NODE_ENV === 'production' ?
'https://jovanka-samudra.vercel.app/api' : 'http://localhost:3000/api';

const resShots = await fetch(`${baseUrlDribble}/user/shots?access_token=${process.env.TOKEN_DRIBBLE}&page=1&per_page=9`);
const shots = await resShots.json();

const resResult = await fetch(`${baseUrl}/projects`);
const result = await resResult.json();
const projects = result.data.projects;

return {
props: {
shots,
projects,
},
revalidate: 1,
}
}

This is the API code to retrieve data from database (pages/api/projects folder)


import ProjectService from "@services/ProjectService";
import connectDB from "@utils/connectDB";
import projectValidator from "@validators/project";
import ClientError from '@exceptions/ClientError';

const handler = async (req, res) => {
const projectService = new ProjectService();

if (req.method === 'GET') {
try {
const projects = await projectService.getProjects();

return res.status(200).json({
success: true,
length: projects.length,
data: {
projects
}
});
} catch (error) {
return res.status(500).json({
success: false,
message: error.message,
});
}
} else if (req.method === 'POST') {
...
}

return res.status(404).json({
success: false,
message: 'Method not alowed'
});
}

export default connectDB(handler);

services/ProjectService folder


import InvariantError from '@exceptions/InvariantError';
import NotFoundError from '@exceptions/NotFoundError';
import Project from '@models/Project';

class ProjectService {
async getProjects() {
const projects = await Project.find().sort({ 'createdAt': -1 });

return projects;
}

...
}

export default ProjectService;

More From » next.js

 Answers
33

You should not fetch an internal API route from getStaticProps — instead, you can write the fetch code in API route directly in getStaticProps.


https://nextjs.org/docs/basic-features/data-fetching/get-static-props#write-server-side-code-directly


[#50257] Sunday, May 16, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emerald

Total Points: 547
Total Questions: 96
Total Answers: 122

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
;