2

I'm trying to develop my first application with Next.js, and there's something happening that is really bothering me.

My app makes 2 requests after first loading, /api/me and /api/feed

My component fetches the data like this:

useEffect(() => {
  async function loadData() {
    const res = await fetch('/api/me');
    try {
      const body = await res.json();
      if (body.error) {
        return router.push('/login');
      }
      setUser(body.user);
    } catch (e) {
      router.push('/login');
    }
  }
  loadData();
}, []);

useEffect(() => {
  async function loadFeed() {
    const res = await fetch('/api/feed');
    const body = await res.json();
    console.log('fetch', body.data);
    setFeed(body.data);
  }

  if (user) {
    loadFeed();
  }
}, [user]);

My problem is, sometimes when it reloads, the responses get mixed up. /feed returns an array and /me an object. When reloading, there are times both /feed and /me receives the object from /me, sometimes they both get the array from /feed, sometimes it works correctly. I didn't find anyone reporting a bug like this, so I'm assuming its a bug somewhere on my part.

/pages/feed/api.js

import handler from '../../helpers/routes/handler';
import auth from '../../middlewares/auth';
import * as feedController from '../../controllers/feed';

export default handler
  .use(auth)
  .get((req, res) => feedController.get(req, res));

handler.js

import nextConnect from 'next-connect';
import { getSession } from '../../config/passport/encrypt';

const handler = nextConnect()
  .use(async (req, res, next) => {
    const session = await getSession(req);

    if (!session) {
      return next();
    }
    ...
    next();
  });

export default handler;

controllers/feed.js

import * as expertMarketerService from '../services/expert_marketer';

// eslint-disable-next-line import/prefer-default-export
export const get = async (req, res) => {
  const data = await expertMarketerService.get(req.user);
  return res.status(200).send({ data });
};

pages/api/me.js

import handler from '../../helpers/routes/handler';
import auth from '../../middlewares/auth';

export default handler
  .use(auth)
  .get((req, res) => res.status(200).send({ user: req.user }));
iagowp
  • 2,428
  • 1
  • 21
  • 32

2 Answers2

2

I Found a solution for this. Had the same issue. What I did was created and exported module instead of direct export. here is my code

import nc from 'next-connect';
import someCommonMiddleware from '..some-common-middlware-path';

module globalHandler {
    const config = {
        onError : (error, req, res) => {
            // handle errors
        }
    };
    export function handle() {
        return nc(config)
        .use(someCommonMiddleware);
    }
}

export default globalHandler;

Then you can use it like this

import { NextApiRequest, NextApiResponse } from 'next';
import globalHandler  from '..your-global-handler-path';

const handler = globalHandler.handle()
    .get(async (req: NextApiRequest, res: NextApiResponse) => {
        // handle url api response here
    });

export default handler;
Shansana Waruna
  • 379
  • 1
  • 3
  • 12
  • Oh thats a nice solution. Now I feel bad I didn't think of it myself =) – iagowp Apr 29 '21 at 16:08
  • I had to find this in a hard way. I think this should be well documented since it has been spread through tutorials courses and all. – Shansana Waruna Apr 29 '21 at 16:16
  • Not that importing `next-connect` in every page is a bad solution, just not what I had expected after learning about it – iagowp Apr 29 '21 at 16:36
0

I found the issue. I was using the same next-connect instance for different routes, and that's a no go.

https://github.com/hoangvvo/next-connect/issues/106

Solution is importing next-connect for every page, and using a middleware for that shared logic

iagowp
  • 2,428
  • 1
  • 21
  • 32