nuxt / bridge

🌉 Experience Nuxt 3 features on existing Nuxt 2 projects
MIT License
272 stars 29 forks source link

nuxtApp availability in nuxt 2 middleware #48

Open psycongaroo opened 2 years ago

psycongaroo commented 2 years ago

Environment

Reproduction

Describe the bug

useCookie not working in middleware:

`nuxt app instance unavailable

at Module.useNuxtApp (file://./.nuxt/dist/server/server.mjs:11336:13)
at useSSRReq (file://./.nuxt/dist/server/server.mjs:11682:52)
at readRawCookies (file://./.nuxt/dist/server/server.mjs:11690:40)
at Module.useCookie (file://./.nuxt/dist/server/server.mjs:11664:19)
at file://./.nuxt/dist/server/server.mjs:11266:47
at promisify (file://./.nuxt/dist/server/server.mjs:12117:15)
at Module.middlewareSeries (file://./.nuxt/dist/server/server.mjs:12093:10)
at __vite_ssr_exports__.default (file://./.nuxt/dist/server/server.mjs:175:31)
at async renderToString (file://./node_modules/vue-bundle-renderer/dist/index.mjs:247:19)
at async renderMiddleware (file://./.nuxt/nitro/index.mjs:191:20)`

Additional context

No response

Logs

No response

atinux commented 2 years ago

Do you mind creating a reproduction on GitHub or CodeSandBox?

pi0 commented 2 years ago

Hi @shinguweb96. You probably need to import useCookie from h3 not #app for server/api and server/middleware.

Please see example in docs: https://v3.nuxtjs.org/docs/usage/cookies#handling-cookies-in-api-routes

psycongaroo commented 2 years ago

@Atinux Hi, here: https://stackblitz.com/edit/nuxt-starter-yx9zm5 (yarn dev)

@pi0 Hi, sorry is not for API Middleware, I was talking about Nuxt-Bridge and route middleware (nuxt 2).

atinux commented 2 years ago

I think this is due to the fact that getCurrentInstance() used by useNuxtApp() (used by useCookie()): https://github.com/nuxt/framework/blob/main/packages/nuxt3/src/app/nuxt.ts#L196

Since in Nuxt 2, the router middleware are handled with router.beforeEach, the Vue app has not been instanciated yet.

We are working on the router middleware for Nuxt 3 on https://github.com/nuxt/framework/discussions/2468, potentially this would help solve the issue.

psycongaroo commented 2 years ago

Thank you @Atinux, there is any eta about #2468?

atinux commented 2 years ago

Cc @danielroe

psycongaroo commented 2 years ago

@Atinux @danielroe @pi0 same identical problem using $fetch inside middleware

I know is same reason about useCookie, but I wanted to report it too.

Tcharlyson commented 2 years ago

@Atinux @danielroe @pi0 same identical problem using $fetch inside middleware

I know is same reason about useCookie, but I wanted to report it too.

Same issue here, using $fetch inside a middleware