enkot / nuxt-open-fetch

Generate zero-overhead, typed OpenAPI clients for Nuxt.
https://nuxt-open-fetch.vercel.app
MIT License
134 stars 12 forks source link

Momentary `null` value when use[Client] is used with a server route #62

Open jonkri opened 1 month ago

jonkri commented 1 month ago

Environment

Reproduction

test.zip

Describe the bug

use[Client] produces a null value in its data property when a Nuxt server route is used. useFetch doesn't.

Additional context

This backend can be used when running the reproduction:

const http = require("http");

const app = http.createServer((request, response) => {
  if (request.url === "/api/test") {
    response.setHeader("Content-Type", "application/json");
    response.write(JSON.stringify({ "test": "test" }));
  } else {
    response.statusCode = 404;
  }
  response.end();
})

app.listen({ port: 3001 });

Logs

No response

jonkri commented 1 month ago

I've uploaded a reproduction.

Just run the backend (see Additional context above) with node index.js, run the frontend with npm run dev, and visit http://localhost:3000.

This code in app.vue works:

const test = (await useFetch("/api/test")).data;

This code in app.vue server-side renders the code correctly but then produces a 500 Internal Server Error page due to test being null:

const test = (await useApi("/test")).data;
jonkri commented 4 weeks ago

@enkot: Do you happen to see anything in /server/api/[...].ts that conflicts with nuxt-open-fetch's use[Client] function?

import { defineEventHandler, H3Event, parseCookies, setCookie } from "h3";
import { joinURL } from "ufo";

export default defineEventHandler(async (event: H3Event) => {
  const cookies = parseCookies(event),
    { proxyUrl } = useRuntimeConfig(),
    target = joinURL(proxyUrl, event.path),
    token = cookies?.token;

  if (token !== undefined && token !== "") {
    setCookie(event, "token", token);
  }

  return proxyRequest(event, target);
});
jonkri commented 2 weeks ago

I looked into this some more and have arrived at a simpler reproduction.

test.zip

I'm no longer using a server route, only routeRules.

nuxt.config.ts:

export default defineNuxtConfig({
  // ...
  modules: ["nuxt-open-fetch"],
  openFetch: {
    clients: {
      api: {
        baseURL: "/api",
        schema: "schema.json",
      },
    },
  },
  routeRules: {
    "/api/**": { proxy: "http://localhost:3001/api/**" },
  }
});

App.vue:

// const test = (await useFetch("/api/test")).data; // Works ✅
const test = (await useApi("/test")).data; // Doesn't work ❌

To reproduce:

$ unzip test.zip

In one terminal:

$ cd test
$ node index.js

In another terminal:

$ cd test
$ npm install

Visit http://localhost:3000/ and refresh the page. It will briefly display “test”, then it will display “$setup.test is null”.

c0nd3v commented 1 week ago

Same problem, all response values are undefined