Recently, I developed an API using next JS in the pages/api
directory and utilized it on a page located in the pages
folder.
During the localhost testing phase, the API functions smoothly without any issues. However, when deploying to Vercel, I encountered an error in the build process.
https://i.sstatic.net/cOehV.png
Below is the code snippet where I call the API from the pages/api
directory:
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,
}
}
Furthermore, this is the API code responsible for fetching data from the database located in the pages/api/projects
directory:
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 allowed'
});
}
export default connectDB(handler);
Moreover, the @services/ProjectService
folder contains the following code:
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;