Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch data from an api handler from another api handler in Nextjs?

Using Nextjs, I am struggling with fetching data from an API handler in another API handler. /api/batch.js handler retrieves some data from a MongoDB:

import middleware from '../../libs/mongodb';
import nextConnect from 'next-connect';

const handler = nextConnect();
handler.use(middleware);
handler.get(async (req, res) => {
  const {batch_uuid} = req.query
  const batch_stats = await req.db.collection('stats').find({
    'batch.uuid': uuid
  }).toArray()
  res.json(batch_stats)  
})
export default (req, res) => handler.apply(req, res)

/api/stats.js handler retrieves some data from MySQL and, based on that and on data from Mongo, it builds a payload.

A dirty fix works as below in stats.js:

const response = await fetch('http://localhost:3000/api/batch?uuid=1234')
const data = await response.json()
// use data and build another payload

However, this requires doing an http call and it does not make sense to do it for an internal endpoint. I tried calling the batch handler dirrectly, but getting undefined

const getBatch = require('./batch');
module.exports = async (req, res) => {
   const accounts = await getBatch()
   res.status(200).json({accounts})
}

What am I missing?

like image 272
vicusbass Avatar asked Feb 28 '26 09:02

vicusbass


1 Answers

You could extract fetching data from the database to a separate module and import this module in both API handlers. Instead of one API endpoint making request to another API endpoint, API handlers would just use the same module that fetches data from MongoDB.

like image 143
Nikolai Kiselev Avatar answered Mar 03 '26 01:03

Nikolai Kiselev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!