Pablo
Pablo
NNuxt
Created by Pablo on 3/26/2025 in #❓・help
[Solved] Storing a user object globally
Greetings! I want to store a user object globally after parsing a JWT in a server plugin, and I seem to only get this partially right. Why am I doing this? Because where my Nuxt app is deployed, authentication happens before the web traffic reaches the Nuxt app. In the request I can see a header with the JWT that has the user info. What I want to happen (which I accomplished easily in Flask in my previous website) is: 1. before any page loads, check if there is a user already in a context/global object. If so, continue. If not, we need to check the request header. 2. parse the JWT in the request header 2. get the user data from a local database 3. store the user object in a app-level state somewhere 4. get the user info in the templates My solution, which is detailed in this StackOverflow question https://stackoverflow.com/questions/79410348/how-to-store-global-user-object-in-nuxt3-server-middleware/79422062#79422062, is to use a server plugin to parse the JWT and a composable "useUser" to store the user state. I can view the user in my templates, which is great. But, in my server plugin, before checking for a JWT, I am not able to check if a user is already in the state. It is always null. I have tried using the nuxtApp, nuxtApp.payload.state, and my useUser composable. This means I have to parse the JWT and fetch the user from a database on every single request. I appreciate any insight into how I can solve this problem, even if it's something different than this current solution. Thanks!
5 replies