Baroshem / nuxt-medusa

🛍️ Medusa module for Nuxt
https://nuxt-medusa.vercel.app
MIT License
129 stars 10 forks source link

auth fails on pageload #47

Open gregorvoinov opened 3 weeks ago

gregorvoinov commented 3 weeks ago

hi,

I installed your module and wanted to start with some basic authentication.

simple middleware

export default defineNuxtRouteMiddleware(async (to, from) => {
  const medusa = useMedusaClient();
  try {
    await medusa.auth.getSession();
  } catch (error) {
    return navigateTo("/login");
  }
});

this works when I navigate with a link inside my app to the secured page

if I am logged in and have an open session in medusa-backend, it shows the page, if not, it redirects to the login

but when I type the URL into the browser and press enter, I get always redirected to the login page, even if I have an existing session

any idea why?

kind regards, gregor

Baroshem commented 2 weeks ago

Hey, I don't have an idea why it happends like this. Have you maybe tried same thing but while using the native medusa js sdk? Maybe it is an issue with the wrapper I have created over it

gregorvoinov commented 2 weeks ago

hi,

ok replaced your module with a plugin

import Medusa from "@medusajs/medusa-js";

export default defineNuxtPlugin((nuxtApp) => {
  const { MEDUSA_API_KEY, MEDUSA_BASE_URL } = useRuntimeConfig().public;

  const medusaClient = new Medusa({
    maxRetries: 3,
    baseUrl: MEDUSA_BASE_URL,
    publishableApiKey: MEDUSA_API_KEY,
  });
  nuxtApp.provide("medusa", medusaClient);
});

but behaves the same... So is this rmore an issue with the medusaClient itself?

gregorvoinov commented 1 week ago

ok figured out when I disable ssr for the secured pages it works like expected on hard reload... which is ok because they do not need to be indexed by search engines

  experimental: {
    inlineRouteRules: true,
  },
  routeRules: {
    "/userarea/**": { ssr: false },
  },

but that means if ssr is activated and the middleware is running on the server then maybe no medusaClient is available?

this is the error I get in the terminal of vs when I enable ssr

Request failed with status code 401

  at settle (node_modules/axios/lib/core/settle.js:19:12)
  at IncomingMessage.handleStreamEnd (node_modules/axios/lib/adapters/http.js:599:11)
  at IncomingMessage.emit (node:events:532:35)
  at endReadableNT (node:internal/streams/readable:1696:12)
  at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
  at Axios.request (node_modules/axios/lib/core/Axios.js:45:41)
  at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  at async $.request (node_modules/@medusajs/medusa-js/dist/index.mjs:136:30)
  at async middleware/auth.js:21:114
  at async Object.callAsync (node_modules/unctx/dist/index.mjs:72:16)
  at async node_modules/nuxt/dist/pages/runtime/plugins/router.js:188:26
Baroshem commented 1 week ago

Hey there, sorry but I missed your message.

Have you also tried with the newer versions of the medusa js client? Or the same one as it is used in the module? Maybe it has to do with the version.

I am glad you have found the solution that works partially.

Do you also use any other modules that could cause this 401 response? It could be that medusa client is not available but that probably would be indicated with a different error than 401.

Would you be able to prepare a stackblitz with such reprodution? I could take a look at it :)

dimitrio-m commented 1 day ago

Hello! I think this is a general Nuxt-SSR problem. In this case medusa works by attaching a cookie header to the subsequent requests, as it says in the docs:

The methods in this class allows you to manage a customer's session, such as login or log out. You can send authenticated requests for a customer either using the Cookie header or using the JWT Token. When you log the customer in using the authenticate method, the JS client will automatically attach the cookie header in all subsequent requests.

So when we refresh the page, nuxt tries to execute the middleware on the server firsts, but there is no valid customer session on the server so that's why you see the 401.

What I normally do in this case since it is an ecommerce website is to disable ssr for secure routes like "/profile" or "/profile/orders".

You may get some hydration errors too if you use the customer session to render some components or elements.

Edit: if you really need ssr everywhere, you could implement some Nuxt Server endpoints to handle the auth, cart, customer logic, in this way the data is shared between client and server. For this you could use the server utility serverMedusaClient