hoangvvo / next-connect

The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
https://www.npmjs.com/package/next-connect
MIT License
1.64k stars 65 forks source link

Same API handler called when reload #181

Closed tequdev closed 2 years ago

tequdev commented 2 years ago

reproduce: https://github.com/develoQ/next-connect-issue-repro

  useEffect(() => {
    const f = async() => {
      const res1 = await fetch("/api/hello1");
      console.log(await res1.json()) // ex) first render=> hello1 , reload after first rende => hello2
      const res2 = await fetch("/api/hello2");
      console.log(await res2.json()) // ex) first render=> hello2 , reload after first rende => hello2
    }
    f()
  },[])

Call 2 api from frontend.

First render, Both hello1, hello2 are correctly called.

after first render, when Reload, A is called twice or B twice.

frontend log スクリーンショット 2022-03-08 23 32 10

backend log

スクリーンショット 2022-03-08 23 32 56

Looking at backend log, api path is correct but path handling is something wrong.

hoangvvo commented 2 years ago

This is due to the same handler being reused (from ./handler). This is already noted in the README: https://github.com/hoangvvo/next-connect#common-errors

DO NOT reuse the same instance of nc like the below pattern:

// middleware/common
export default nc().use(a).use(b);

// api/foo
import Handler from "middleware/common";
export default Handler.get(x);

// api/bar
import Handler from "middleware/common";
export default Handler.get(y);
tequdev commented 2 years ago

Sorry for the lack of reading of the document.

Thanks.