enigmare/v2-crawler
1904
1{"id":"stack-49251437","source":"stackoverflow","questionId":49251437,"title":"Difference between Asyncdata vs Fetch","tags":["vue.js","vuejs2","vuex","nuxt.js"],"text":"Title: Difference between Asyncdata vs Fetch\nTags: vue.js, vuejs2, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhat is the exact difference between fetch and async data. The official documentation says the following:\n\n**asyncData**\n\nYou may want to fetch data and render it on the server-side. Nuxt.js\nadds an asyncData method that lets you handle async operations before\nsetting the component data.\n\n**asyncData** is called every time before loading the component (only for\npage components). It can be called from the server-side or before\nnavigating to the corresponding route. This method receives the\ncontext object as the first argument, you can use it to fetch some\ndata and return the component data.\n\n**Fetch**\n\nThe fetch method is used to fill the store before rendering the page, it's\nlike the asyncData method except it doesn't set the component data.\nThe fetch method, if set, is called every time before loading the\ncomponent (only for page components). It can be called from the\nserver-side or before navigating to the corresponding route.\n\nThe fetch method receives the context object as the first argument, we\ncan use it to fetch some data and fill the store. To make the fetch\nmethod asynchronous, return a Promise, nuxt.js will wait for the\npromise to be resolved before rendering the component.\n\nFetch is been used to fill the store with data? But in asyncData is this also possible to commit trough a store? I don't understand why there are two methods for.\n\nBoth methods are running server-side on the initial load, after that when you navigate through the applicatie it runs client side.\n\nCan someone explain me the advantage of use these methods above the other?\n\nThanks for help.\n\n========================================\n\nTop Answer:\nTL;DR - use `asyncData` for stuff which must be loaded before rendering a page, use `fetch` for everything else.\n\nKey differences:\n\n### Availability\n\n- `asyncData` is only available on page components\n\n- `fetch` can be used on any component (including page components)\n\n### Loading\n\n- `asyncData` blocks the page transition until it resolves. This means the data properties returned are guaranteed to be available on the component. But it also means users may have to wait longer before seeing content.\n\n- `fetch` exposes a `$fetchState.pending` property and it's up to you how to handle that\n\n### Error handling\n\n- if an error is thrown in `asyncData` the page is not rendered\n\n- `fetch` exposes a `$fetchState.error` property and it's up to you how to handle that\n\n========================================\n\nCode:\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nuse fetch\n```\n\n```text\nuse asyncData\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\n<script>\nexport default {\n async fetch ({ store, params }) {\n await store.dispatch('GET_STARS');\n }\n}\n</script>\n```\n\n```text\n<script>\nexport default {\n asyncData (context) {\n return { project: 'nuxt' }\n }\n}\n</script>\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\n$fetchState.pending\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\n$fetchState.error\n```\n\n```text\n<script>\nimport { mapActions, mapMutations, mapState } from 'vuex'\n\nexport default {\n name: 'PagesBlog',\n\n async asyncData ({ store }) {\n if (!store.state.global.blogAuthors.length) {\n store.commit('global/blogAuthorsSet', await blogAuthorsDownload())\n }\n\n await store.dispatch('global/blogsDownloadAndSet')\n },\n\n async fetch () {\n if (!this.blogAuthors.length) {\n this.blogAuthorsSet(await blogAuthorsDownload())\n }\n\n await this.blogsDownloadAndSet()\n },\n\n computed: {\n ...mapState('global', [\n 'blogAuthors'\n ])\n },\n\n methods: {\n ...mapActions('global', [\n 'blogsDownloadAndSet'\n ]),\n\n ...mapMutations('global', [\n 'blogAuthorsSet'\n ])\n }\n</script>\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n========================================\n\nComments:\n- upvoted! can I call fetch manually, i have a universal mode nuxt app where on one page I must paginate a table fetching data from the server without changing the page, if I click next page button should I call fetch manually or how\n- @PirateApp my practical experience is, you cannot execute 'fetch' manually, behavior of 'fetch' is controlled by nuxtjs. if you need to trigger any events (for dataFetch) after pageLoad, better to write a customMethod for dataFetch and bind the 'nextPage button' to it\n- What about not using them at all, and using created or mounted hooks instead?\n- @PrimozRome `created & mounted` hooks always runs on the client side. on first request to the nuxtapp for a particular route `asyncData & fetch` will run on the server side. So with `asyncData & fetch`, you have the opportunity to load the data into client without any ajax request after page load in client side as you would do for `created & mounted` hooks\n- @divine yes that is correct, thanks for explanation. I forgot to mention in my comment if using Nuxt.js app in SPA mode only. Then it should be the same using `fetch()` or `created()` hook, correct?\n- @PrimozRome yes correct, in spa whatever goes into `asyncData` or `fetch` will be invoked first then `created` hook gets invoked then `mounted` hook gets invoked. So `asyncData` or `fetch` gets invoked before the component gets `created`.\n- I want to fill the VUEX store with data in the fetch method. Is this data then available in the asyncData method? I cannot understand which one runs first...\n- @divine To clarify: are the created and mounted hooks called server side in nuxt? If so, the only reason to use asyncData would be timing.\n- To emphasize: `asyncData` is only in 'pages' not in 'components.' Must use `fetch` in that one. Strangely, when making this mistake of using `asyncData` in a 'components' file, there is no warning or linting error. 🤷🏽♂️\n- But doesn't fetch has access to component context with `this`? Then it can set data like this.someData = data; -> `With the help of this context, fetch is able to mutate component’s data directly.`\n- > \"yes correct, in spa whatever goes into asyncData or fetch will be invoked first then created hook gets invoked\" - if you check update in nuxt 2.12 fetch() is called after create()\n- a drawback of using fetch() is that you can't insert requested data at page headers\n- this is incorrect example. While asyncData indeed can change local/component data, you can use it to save data in store as well. Simply replace \"fetch\" by \"asyncData\" in your example, that's it.\n- That said, in a SSG site we \"should\" use `asyncData` for retrieving data for a page that will not change during navigation and, for example, set the dynamic meta tags in the head method (if using `fetch()`, `head()` could not receive the data in time). We should use `fetch()` when we want more control on the data received, for example if there is a button to trigger the `fetch()` again while showing a placeholder with `$fetchState.pending`. Am I thinking it right?\n- @StefanoFranceschetto makes sense\n- The section on \"loading\" really clarifies things for me.","metadata":{"transformedAt":"2026-08-18T18:33:07.826Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":42,"totalLines":304,"estimatedTokens":1901}}2{"id":"stack-44748575","source":"stackoverflow","questionId":44748575,"title":"How to get current route name in Nuxt 2 and 3?","tags":["vue.js","vuejs2","vue-component","vue-router","nuxt.js"],"text":"Title: How to get current route name in Nuxt 2 and 3?\nTags: vue.js, vuejs2, vue-component, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt.js for building a static website. \n\nHow to access in component's `script` code currently displayed route name (I would like to avoid reading direct url from browser location)? \n\nCan I somehow access `$route.name` ?\n\n========================================\n\nTop Answer:\n**In Vue2**\n\nAn alternative way is to use either of the following:\n\n- `this.$route.path` → Example on `http://localhost:3000` , `{{this.$route.path}}` will print `/`\n\n- `this.$route.name` → Example on `http://localhost:3000`, `{{this.$route.name}}` will print `index`\n\n========================================\n\nCode:\n```text\nscript\n```\n\n```text\n$route.name\n```\n\n```text\n$nuxt.$route.path\n```\n\n```text\n$nuxt.$route.name\n```\n\n```text\ndata() {\n return {\n zone: this.$nuxt.$route.query.zone,\n jour: this.$nuxt.$route.query.jour\n \n } },\n```\n\n```text\n$route.name\n```\n\n```text\n$route.path\n```\n\n```text\nthis.$route.path\n```\n\n```text\nhttp://localhost:3000\n```\n\n```text\n{{this.$route.path}}\n```\n\n```text\n/\n```\n\n```text\nthis.$route.name\n```\n\n```text\nhttp://localhost:3000\n```\n\n```text\n{{this.$route.name}}\n```\n\n```text\nindex\n```\n\n```js\nimport { computed, defineComponent, useRoute } from '@nuxtjs/composition-api'\n\nexport default defineComponent({\n setup() {\n const route = useRoute()\n const routeName = computed(() => route.value.name)\n return { routeName }\n },\n})\n```\n\n```text\nuseRouter\n```\n\n```html\n<script setup>\nconst route = useRoute()\nconsole.log('current name', route.name)\n</script>\n```\n\n```html\n<script>\nexport default {\n mounted () {\n console.log('current name', this.$route.name)\n },\n}\n</script>\n```\n\n```text\nexport default ({\n setup () {\n const route = useRoute()\n return {\n route\n }\n }\n})\n```\n\n```text\n{{ route.name }}\n```\n\n```text\nconst { currentRoute } = useRouter();\nconst routeName = currentRoute.value.name;\n```\n\n```js\n<script setup>\n const route = useRoute(); // built-in composable\n // route.name\n\n useHead( function() {\n return {\n htmlAttrs: {\n \"data-route\": route.name,\n },\n };\n });\n</script>\n```\n\n```text\n{{ $route.name }}\n```\n\n```text\nindex\n```\n\n========================================\n\nComments:\n- Yes you should be able to access it in component in way like `this.$route.name`\n- My URL contains some characters after a hash sign. Not path nor name returns the value after # /my/url/#somemore only /my/url/ is returned\n- For me, this doesnt work. I'm trying it in the stup, and it always says it's undefined\n- @CodeHacker feel free to open a new question with some relevant code.","metadata":{"transformedAt":"2026-08-18T18:33:07.827Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":173,"estimatedTokens":690}}3{"id":"stack-48068520","source":"stackoverflow","questionId":48068520,"title":"How to get route url params in a page in Nuxt2 and 3?","tags":["javascript","vue.js","nuxt.js","nuxt3.js"],"text":"Title: How to get route url params in a page in Nuxt2 and 3?\nTags: javascript, vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am using Nuxt.js, and have a dymanic page which is defined under \n\n```\npages/post/_slug.vue\n```\n\nSo, when I visit the page url, say, http://localhost:3000/post/hello-world, how can I read this slug parameter value inside my page.\n\nCurrently I am geting it using asyncData as follows:\n\n```\nasyncData ({ params }) {\n // called every time before loading the component\n return {\n slug: params.slug\n }\n }\n```\n\nThis is working fine, but I think this is not the best way, and there should be a better way to make the parameter available to the page. Any help is appreciated!\n\n========================================\n\nTop Answer:\nTo read params from URL you should use this way in Nuxt:\n\n`this.$route.query.`\n\nFor example\n\nURL: `https://example.com/example/?token=QWERTYUASDFGH`\n\nwith this line of code, you can read `token`:\n\n`this.$route.query.token`\n\nand give you `QWERTYUASDFGH`.\n\n========================================\n\nCode:\n```text\npages/post/_slug.vue\n```\n\n```text\nasyncData ({ params }) {\n // called every time before loading the component\n return {\n slug: params.slug\n }\n }\n```\n\n```text\nthis.$route\n```\n\n```text\n{\n fullpath: string,\n params: {\n [params_name]: string\n },\n //fullpath without query\n path: string\n //all the things after ? in url\n query: {\n [query_name]: string\n }\n}\n```\n\n```text\n<script>\n export default {\n mounted() {\n console.log(this.$route.fullPath);\n }\n };\n </script>\n```\n\n```text\n<script>\n export default {\n mounted() {\n console.log(this.$route.params.slug);\n }\n };\n </script>\n```\n\n```text\n<script>\n export default {\n asyncData({route, params}) {\n if (process.server) {\n //use route object\n console.log(route.params.slug)\n //directly use params\n console.log(params.slug)\n }\n }\n };\n </script>\n```\n\n```text\nthis.$router\n```\n\n```text\n$route\n```\n\n```text\n$route\n```\n\n```text\nroute.params\n```\n\n```text\nroute.params.slug\n```\n\n```text\nasyncData\n```\n\n```text\napollo: {\n items: {\n query: jobsBy,\n variables() {\n return {\n clientId: this.$route.query.id\n }\n },\n }\n }\n```\n\n```text\napollo\n```\n\n```text\nthis.$router.currentRoute.query['param_name']\n```\n\n```text\nthis.$route.query.<name_of_your_parameter_in_url>\n```\n\n```text\nhttps://example.com/example/?token=QWERTYUASDFGH\n```\n\n```text\ntoken\n```\n\n```text\nthis.$route.query.token\n```\n\n```text\nQWERTYUASDFGH\n```\n\n```text\nasync asyncData(context){\n const query_params=context.route.query;\n}\n```\n\n```html\n<script setup>\nconst route = useRoute()\n</script>\n\n<template>\n <pre>{{ route }}</pre>\n</template>\n```\n\n```json\n{\n \"path\": \"/about\",\n \"name\": \"about\",\n \"params\": {},\n \"query\": {\n \"fruit\": \"watermelon\"\n },\n \"hash\": \"\",\n \"fullPath\": \"/about?fruit=watermelon\",\n \"matched\": [\n {\n \"path\": \"/about\",\n \"name\": \"about\",\n \"meta\": {},\n \"props\": {\n \"default\": false\n },\n \"children\": [],\n \"instances\": {},\n \"leaveGuards\": {\n \"Set(0)\": []\n },\n \"updateGuards\": {\n \"Set(0)\": []\n },\n \"enterCallbacks\": {},\n \"components\": {\n \"default\": {\n \"__hmrId\": \"0a606064\",\n \"__file\": \"/home/kissu/code/test/n3-default/pages/about.vue\"\n }\n }\n }\n ],\n \"meta\": {}\n}\n```\n\n```html\n<script>\nexport default {\n mounted () {\n console.log('route object', this.$.appContext.app.$nuxt._route.query)\n },\n}\n</script>\n```\n\n```text\n.vue\n```\n\n```text\nroute\n```\n\n```text\nhttp://localhost:5678/about?fruit=watermelon\n```\n\n```text\nRoutes\n```\n\n```text\nquery params\n```\n\n```text\n\"route params\"\n```\n\n```text\n_\n```\n\n```text\n_\n```\n\n```text\n[]\n```\n\n```text\n$route\n```\n\n```text\nthis.$route.params\n```\n\n```text\nuseRoute\n```\n\n```text\nconst { params } = useRoute()\n```\n\n========================================\n\nComments:\n- could you tell you want use params for what?\n- I use this param to query and fetch some data from an API.\n- Then I think your way is the best way!\n- ok thanks! I will continue to use this method till we find a better one :)\n- This seems like a very bad practice as it's never mentioned in nuxt js documentations !\n- $nuxt.$route is documented though.\n- params is not right, it is query\n- This help me a lot, ty. But better use this.$router.currentRoute.params.param_name\n- A query params is not a path variable. Here, OP is looking for the `path variable` params as per se. Yeah, the working is poor on this one.\n- query is the correct answer for me in nuxtjs\n- Correct me if I'm wrong, params != query. `example.com/post/{id}` would be a parameter, `example.com/post?id=123` would be a query.","metadata":{"transformedAt":"2026-08-18T18:33:07.827Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":309,"estimatedTokens":1215}}4{"id":"stack-47862591","source":"stackoverflow","questionId":47862591,"title":"Vuejs Error: The client-side rendered virtual DOM tree is not matching server-rendered","tags":["javascript","vue.js","vuejs2","nuxt.js"],"text":"Title: Vuejs Error: The client-side rendered virtual DOM tree is not matching server-rendered\nTags: javascript, vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using Nuxt.js / Vuejs for my app, and I keep facing this error in different places:\n\n```\nThe client-side rendered virtual DOM tree is not matching server-rendered content. \nThis is likely caused by incorrect HTML markup, for example nesting block-level elements inside , or missing . \nBailing hydration and performing full client-side render.\n```\n\nI would like to understand what is the best way to debug this error? Is their a way I can record/get the virtual DOM tree for client and server so I could compare and find where the error lies?\n\nMine is a large application and manually verifying is difficult.\n\n========================================\n\nTop Answer:\nFor me this error happened cuz get Array list in `AsyncData` and rendered `` tags by `v-for`, i put `v-for` codes in `` blocks and problem solved\n\n========================================\n\nCode:\n```text\nThe client-side rendered virtual DOM tree is not matching server-rendered content. \nThis is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. \nBailing hydration and performing full client-side render.\n```\n\n```text\nmsg\n```\n\n```text\nhydrate\n```\n\n```text\npatch\n```\n\n```text\nhydrate\n```\n\n```text\nhydrate\n```\n\n```text\nfalse\n```\n\n```text\nassertNodeMatch\n```\n\n```text\nfalse\n```\n\n```text\nhydrate\n```\n\n```text\nelm\n```\n\n```text\nvnode\n```\n\n```text\nAsyncData\n```\n\n```text\n<tr>\n```\n\n```text\nv-for\n```\n\n```text\nv-for\n```\n\n```text\n<client-only>\n```\n\n```js\n// Search for this line: \nfunction hydrate (elm, vnode, insertedVnodeQueue, inVPre) {\n var i;\n var tag = vnode.tag;\n var data = vnode.data;\n var children = vnode.children;\n inVPre = inVPre || (data && data.pre);\n vnode.elm = elm;\n\n // Add the following lines: \n console.log('elm', elm)\n console.log('vnode', vnode)\n console.log('inVpre', inVPre)\n // ...\n```\n\n```text\nnode_modules/vue/dist/vue.esm.js\n```\n\n```text\n<client-only>\n```\n\n```html\n<nuxt-link to=\"/game42day\">\n <a>Game For Today</a>\n</nuxt-link>\n```\n\n```html\n<nuxt-link to=\"/game42day\">\n Game For Today\n</nuxt-link>\n```\n\n```text\n\"nuxt\": \"^2.12.2\"\n```\n\n```html\n<client-only>\n <vue-particles>\n </vue-particles>\n</client-only>\n```\n\n```html\n<no-ssr>\n <vue-particles>\n </vue-particles>\n</no-ssr>\n```\n\n```text\n2.14.0\n```\n\n```text\nno-ssr\n```\n\n```text\n2.9.0\n```\n\n```html\n<v-expansion-panel-header v-text=\"name\" />\n```\n\n```html\n<v-expansion-panel-header>{{ name }}</v-expansion-panel-header>\n```\n\n```text\nextend (config, ctx) {\n config.resolve.symlinks = false\n}\n```\n\n```text\nv-if\n```\n\n```text\n<no-ssr></no-ssr>\n```\n\n```text\nv-if\n```\n\n```text\nv-show\n```\n\n```text\n<client-only>\n```\n\n```text\nv-show\n```\n\n```text\nv-if\n```\n\n```text\n<p>\n```\n\n```text\na\n```\n\n```text\nnew Date()\n```\n\n```text\n<template>\n <v-btn\n :width=\"width\"\n :color=\"color\"\n :class=\"[rounded ? 'rounded-pill' : 'rounded-lg',textColor]\"\n v-on:click=\"onClick\"\n elevation=\"0\"\n :outlined=\"outlined\"\n :type=\"type\"\n :name=\"name\"\n :form=\"form\"\n :disabled=\"disabled\"\n v-bind=\"$attrs\"\n >{{ text }}</v-btn>\n</template>\n```\n\n```text\n<v-btn>{{text}}</v-btn>\n```\n\n```text\n<p>\n```\n\n```text\n<p v-html='html'></p>\n```\n\n```text\n<div v-html='html'></div>\n```\n\n```text\n<client-only></client-only>\n```\n\n```text\n<p v-html=\"$md.render(post.content)\"></p>\n```\n\n```text\n<p>{{ $md.render(post.content) }}</p>\n```\n\n```text\nif (process.env.NODE_ENV !== 'production') {\n if (!assertNodeMatch(elm, vnode, inVPre)) {\n return false\n }\n }\n```\n\n```text\nwarn\n```\n\n```text\nSources\n```\n\n```text\nvue.runtime.esm.js?xxxx\n```\n\n```text\nctrl+f\n```\n\n```text\nassertNodeMatch\n```\n\n```text\nreturn false\n```\n\n```text\nScope->Local\n```\n\n```text\nelm\n```\n\n```text\nElements\n```\n\n```text\nclient side\n```\n\n```text\n<client-only>\n```\n\n```text\nisHydrate\n```\n\n```text\nmounted\n```\n\n```text\n<p><p>Text</p></p>\n```\n\n```text\n<div>\n```\n\n```text\n<p>\n```\n\n```text\n<span>\n```\n\n```text\n<Transition tag=\"div\">\n```\n\n```text\n<p>\n```\n\n```text\n<div>\n```\n\n```text\n<p>\n```\n\n```text\n$md.render()\n```\n\n```text\nvar i;\n var tag = vnode.tag, data = vnode.data, children = vnode.children;\n inVPre = inVPre || (data && data.pre);\n vnode.elm = elm;\n\n console.log('elm', elm)\n console.log('vnode', vnode)\n console.log('inVpre', inVPre)\n \n if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) {\n vnode.isAsyncPlaceholder = true;\n return true;\n }\n```\n\n```text\n<NuxtLink to=\"/services\">\n <a class=\"main-content-left-content-more_link ml-30 pointer m-ml-0\">\n My link\n </a>\n</NuxtLink>\n```\n\n```text\n<a>\n```\n\n```text\n<NuxtLink>\n```\n\n```text\n<a>\n```\n\n```text\n<NuxtLink>\n```\n\n```text\nThe client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.\n```\n\n========================================\n\nComments:\n- inspect the issue: blog.lichter.io/posts/vue-hydration-error/…\n- `Nuxt 5.6.0`, You live in the future?\n- A quicker way to access the hydrate function execution is to expand the error in the console area of Chrome dev tools and you can see it in the list. Simply click the link after the @ symbol of the same line. e.g. hydrate @ commons.app.js:15934\n- I found that this blog posted an expanded explanation of this error, based on @budden73 answer and it actually helped me understand the problem. Hope this can helps someone else: blog.lichter.io/posts/vue-hydration-error\n- If your not using Nuxt you will need to install vue-client-only\n- Does this mean we cannot render table server side? and send the complete html to the browser? this really ruin the concept of SSR and SEO features of Nuxt. I get the same issue and can be resolved with block but it is not the real fix I guess\n- @Tekz you can render tables server-side, as long as you make sure rows are wrapped in ``, `` and `` tags (see MDN for reference on how to use these tags properly)\n- @FelixEve this one is no longer needed because it is baked into Nuxt.\n- It is the easiest way to debug this issue. can find out the element responsible for any warning or error. thanks a lot.\n- Thanks for you answer, did you perform any additional actions except editing this file and starting nuxt (probably yarn dev). Does not work for me, old file is used according to Sources in Chrome(\n- @BogdanTimofeev I did not perform any addition actions. I was using Vue without Nuxt. For Nuxt it may be an other similar file.\n- looks like it's `ClientOnly` now\n- @David天宇Wong the camel or kebab case is just a preference. Both work well.\n- Great advice. A good tip for the future.\n- This is 100% match qoute from blog.lichter.io , so should be marked as qoute ;)\n- This is an HTML semantic rule indeed (cannot have a link inside of a link), not even related to Vue/Nuxt.","metadata":{"transformedAt":"2026-08-18T18:33:07.827Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":79,"totalLines":421,"estimatedTokens":1776}}5{"id":"stack-67631879","source":"stackoverflow","questionId":67631879,"title":"Nuxtjs vuetify throwing lots of `Using / for division is deprecated and will be removed in Dart Sass 2.0.0.`","tags":["sass","vuetify.js","nuxt.js"],"text":"Title: Nuxtjs vuetify throwing lots of `Using / for division is deprecated and will be removed in Dart Sass 2.0.0.`\nTags: sass, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nNuxtjs using vuetify throwing lots of error `Using / for division is deprecated and will be removed in Dart Sass 2.0.0.` during yarn dev\n\nNuxtjs: v2.15.6\n@nuxtjs/vuetify\": \"1.11.3\",\n\"sass\": \"1.32.8\",\n\"sass-loader\": \"10.2.0\",\n\nAnyone know how to fix it ?\n\n```\n: Using / for division is deprecated and will be removed in Dart Sass 2.0.0.\n\nRecommendation: math.div($grid-gutter, 3)\n\nMore info and automated migrator: https://sass-lang.com/d/slash-div\n\n ╷\n63 │ 'md': $grid-gutter / 3,\n │ ^^^^^^^^^^^^^^^^\n ╵\n node_modules/vuetify/src/styles/settings/_variables.scss 63:11 @import\n node_modules/vuetify/src/styles/settings/_index.sass 1:9 @import\n node_modules/vuetify/src/styles/styles.sass 2:9 @import\n node_modules/vuetify/src/components/VIcon/_variables.scss 1:9 @import\n node_modules/vuetify/src/components/VIcon/VIcon.sass 2:9 root stylesheet\n\n: Using / for division is deprecated and will be removed in Dart Sass 2.0.0.\n\nRecommendation: math.div($grid-gutter * 2, 3)\n\nMore info and automated migrator: https://sass-lang.com/d/slash-div\n\n ╷\n64 │ 'lg': $grid-gutter * 2/3,\n │ ^^^^^^^^^^^^^^^^^^\n ╵\n node_modules/vuetify/src/styles/settings/_variables.scss 64:11 @import\n node_modules/vuetify/src/styles/settings/_index.sass 1:9 @import\n node_modules/vuetify/src/styles/styles.sass 2:9 @import\n node_modules/vuetify/src/components/VIcon/_variables.scss 1:9 @import\n node_modules/vuetify/src/components/VIcon/VIcon.sass 2:9 root stylesheet\n```\n\n```\n\"dependencies\": {\n \"@nuxtjs/apollo\": \"^4.0.1-rc.5\",\n \"@nuxtjs/auth-next\": \"5.0.0-1617968180.f699074\",\n \"@nuxtjs/axios\": \"^5.4.1\",\n \"@nuxtjs/gtm\": \"^2.3.0\",\n \"axios-extensions\": \"^3.0.6\",\n \"global\": \"^4.4.0\",\n \"googleapis\": \"^71.0.0\",\n \"graphql-tag\": \"^2.10.3\",\n \"jszip\": \"^3.2.1\",\n \"jwt-decode\": \"^3.1.2\",\n \"leaflet\": \"1.6.0\",\n \"leaflet-draw\": \"^1.0.4\",\n \"leaflet-editablecirclemarker\": \"^1.0.4\",\n \"leaflet-geosearch\": \"2.5.1\",\n \"leaflet.gridlayer.googlemutant\": \"0.9.0\",\n \"leaflet.heat\": \"^0.2.0\",\n \"lodash\": \"^4.17.15\",\n \"lodash-webpack-plugin\": \"^0.11.5\",\n \"lru-cache\": \"^6.0.0\",\n \"multi-download\": \"^3.0.0\",\n \"nuxt\": \"^2.6.3\",\n \"nuxt-i18n\": \"^6.20.1\",\n \"nuxt-leaflet\": \"^0.0.21\",\n \"reiko-parser\": \"^1.0.8\",\n \"sass\": \"1.32.8\",\n \"sass-loader\": \"10.2.0\",\n \"sortablejs\": \"1.13.0\",\n \"style\": \"^0.0.3\",\n \"style-loader\": \"^2.0.0\",\n \"svgo\": \"^2.3.0\",\n \"vue\": \"^2.6.6\",\n \"vue-mqtt\": \"^2.0.3\",\n \"vue-recaptcha\": \"^1.1.1\",\n \"vue-upload-component\": \"^2.8.19\",\n \"vuedraggable\": \"willhoyle/Vue.Draggable\"\n },\n \"devDependencies\": {\n \"@aceforth/nuxt-optimized-images\": \"^1.0.1\",\n \"@babel/preset-env\": \"^7.13.15\",\n \"@babel/runtime-corejs3\": \"^7.13.10\",\n \"@mdi/font\": \"^5.9.55\",\n \"@nuxtjs/eslint-config\": \"^6.0.0\",\n \"@nuxtjs/vuetify\": \"^1.11.3\",\n \"@storybook/addon-essentials\": \"^6.2.8\",\n \"@storybook/vue\": \"^6.2\",\n \"@vue/cli-plugin-eslint\": \"^4.5.12\",\n \"babel-core\": \"^6.26.3\",\n \"babel-eslint\": \"^10.0.1\",\n \"babel-loader\": \"^8.0.6\",\n \"babel-plugin-lodash\": \"^3.3.4\",\n \"babel-plugin-transform-pug-html\": \"^0.1.3\",\n \"babel-plugin-transform-runtime\": \"^6.23.0\",\n \"babel-polyfill\": \"^6.26.0\",\n \"babel-preset-vue\": \"^2.0.2\",\n \"core-js\": \"3\",\n \"css-loader\": \"^5.2.1\",\n \"eslint\": \"^7.24.0\",\n \"eslint-config-prettier\": \"^8.2.0\",\n \"eslint-config-standard\": \"^16.0.2\",\n \"eslint-loader\": \"^4.0.2\",\n \"eslint-plugin-html\": \"^6.1.2\",\n \"eslint-plugin-import\": \"^2.16.0\",\n \"eslint-plugin-node\": \"^11.1.0\",\n \"eslint-plugin-prettier\": \"^3.4.0\",\n \"eslint-plugin-promise\": \"^5.1.0\",\n \"eslint-plugin-standard\": \"^5.0.0\",\n \"eslint-plugin-vue\": \"^7.9.0\",\n \"googleapis\": \"^71.0.0\",\n \"image-webpack-loader\": \"^7.0.1\",\n \"imagemin-mozjpeg\": \"^9.0.0\",\n \"imagemin-pngquant\": \"^9.0.2\",\n \"minify-css-string\": \"^1.0.0\",\n \"plop\": \"^2.4.0\",\n \"prettier\": \"^2.2.1\",\n \"sass-migrator\": \"^1.3.9\",\n \"storybook\": \"^6.2.8\",\n \"storybook-readme\": \"^5.0.9\",\n \"stylus\": \"^0.54.8\",\n \"stylus-loader\": \"^4.0.0\",\n \"vue-loader\": \"^15.9.6\",\n \"vue-recaptcha\": \"^1.1.1\",\n \"vue-template-compiler\": \"^2.6.6\",\n \"vue2-leaflet\": \"2.5.2\",\n \"vue2-leaflet-editablecirclemarker\": \"^1.0.5\",\n \"vue2-leaflet-geosearch\": \"1.0.6\",\n \"vue2-leaflet-googlemutant\": \"^2.0.0\",\n \"vue2-leaflet-markercluster\": \"^3.1.0\",\n \"vuetify-loader\": \"^1.7.2\"\n },\n \"browserslist\": {\n \"production\": [\n \">0.2%\",\n \"not dead\",\n \"not op_mini all\",\n \"ie 11\"\n ]\n }\n}\n```\n\n========================================\n\nTop Answer:\nThere's an issue with vuetify I think.\nBut if you use yarn, you can use\n\n```\n\"resolutions\": {\n \"@nuxtjs/vuetify/**/sass\": \"1.32.12\"\n}\n```\n\nin `package.json`.\n\n**EDIT**\n\nIf you use npm, you can just simply add\n\n```\n\"devDependencies\": {\n ...,\n \"sass\": \"~1.32.12\"\n}\n```\n\nto `package.json`\n\n========================================\n\nCode:\n```text\n: Using / for division is deprecated and will be removed in Dart Sass 2.0.0.\n\nRecommendation: math.div($grid-gutter, 3)\n\nMore info and automated migrator: https://sass-lang.com/d/slash-div\n\n ╷\n63 │ 'md': $grid-gutter / 3,\n │ ^^^^^^^^^^^^^^^^\n ╵\n node_modules/vuetify/src/styles/settings/_variables.scss 63:11 @import\n node_modules/vuetify/src/styles/settings/_index.sass 1:9 @import\n node_modules/vuetify/src/styles/styles.sass 2:9 @import\n node_modules/vuetify/src/components/VIcon/_variables.scss 1:9 @import\n node_modules/vuetify/src/components/VIcon/VIcon.sass 2:9 root stylesheet\n\n: Using / for division is deprecated and will be removed in Dart Sass 2.0.0.\n\nRecommendation: math.div($grid-gutter * 2, 3)\n\nMore info and automated migrator: https://sass-lang.com/d/slash-div\n\n ╷\n64 │ 'lg': $grid-gutter * 2/3,\n │ ^^^^^^^^^^^^^^^^^^\n ╵\n node_modules/vuetify/src/styles/settings/_variables.scss 64:11 @import\n node_modules/vuetify/src/styles/settings/_index.sass 1:9 @import\n node_modules/vuetify/src/styles/styles.sass 2:9 @import\n node_modules/vuetify/src/components/VIcon/_variables.scss 1:9 @import\n node_modules/vuetify/src/components/VIcon/VIcon.sass 2:9 root stylesheet\n```\n\n```text\n\"dependencies\": {\n \"@nuxtjs/apollo\": \"^4.0.1-rc.5\",\n \"@nuxtjs/auth-next\": \"5.0.0-1617968180.f699074\",\n \"@nuxtjs/axios\": \"^5.4.1\",\n \"@nuxtjs/gtm\": \"^2.3.0\",\n \"axios-extensions\": \"^3.0.6\",\n \"global\": \"^4.4.0\",\n \"googleapis\": \"^71.0.0\",\n \"graphql-tag\": \"^2.10.3\",\n \"jszip\": \"^3.2.1\",\n \"jwt-decode\": \"^3.1.2\",\n \"leaflet\": \"1.6.0\",\n \"leaflet-draw\": \"^1.0.4\",\n \"leaflet-editablecirclemarker\": \"^1.0.4\",\n \"leaflet-geosearch\": \"2.5.1\",\n \"leaflet.gridlayer.googlemutant\": \"0.9.0\",\n \"leaflet.heat\": \"^0.2.0\",\n \"lodash\": \"^4.17.15\",\n \"lodash-webpack-plugin\": \"^0.11.5\",\n \"lru-cache\": \"^6.0.0\",\n \"multi-download\": \"^3.0.0\",\n \"nuxt\": \"^2.6.3\",\n \"nuxt-i18n\": \"^6.20.1\",\n \"nuxt-leaflet\": \"^0.0.21\",\n \"reiko-parser\": \"^1.0.8\",\n \"sass\": \"1.32.8\",\n \"sass-loader\": \"10.2.0\",\n \"sortablejs\": \"1.13.0\",\n \"style\": \"^0.0.3\",\n \"style-loader\": \"^2.0.0\",\n \"svgo\": \"^2.3.0\",\n \"vue\": \"^2.6.6\",\n \"vue-mqtt\": \"^2.0.3\",\n \"vue-recaptcha\": \"^1.1.1\",\n \"vue-upload-component\": \"^2.8.19\",\n \"vuedraggable\": \"willhoyle/Vue.Draggable\"\n },\n \"devDependencies\": {\n \"@aceforth/nuxt-optimized-images\": \"^1.0.1\",\n \"@babel/preset-env\": \"^7.13.15\",\n \"@babel/runtime-corejs3\": \"^7.13.10\",\n \"@mdi/font\": \"^5.9.55\",\n \"@nuxtjs/eslint-config\": \"^6.0.0\",\n \"@nuxtjs/vuetify\": \"^1.11.3\",\n \"@storybook/addon-essentials\": \"^6.2.8\",\n \"@storybook/vue\": \"^6.2\",\n \"@vue/cli-plugin-eslint\": \"^4.5.12\",\n \"babel-core\": \"^6.26.3\",\n \"babel-eslint\": \"^10.0.1\",\n \"babel-loader\": \"^8.0.6\",\n \"babel-plugin-lodash\": \"^3.3.4\",\n \"babel-plugin-transform-pug-html\": \"^0.1.3\",\n \"babel-plugin-transform-runtime\": \"^6.23.0\",\n \"babel-polyfill\": \"^6.26.0\",\n \"babel-preset-vue\": \"^2.0.2\",\n \"core-js\": \"3\",\n \"css-loader\": \"^5.2.1\",\n \"eslint\": \"^7.24.0\",\n \"eslint-config-prettier\": \"^8.2.0\",\n \"eslint-config-standard\": \"^16.0.2\",\n \"eslint-loader\": \"^4.0.2\",\n \"eslint-plugin-html\": \"^6.1.2\",\n \"eslint-plugin-import\": \"^2.16.0\",\n \"eslint-plugin-node\": \"^11.1.0\",\n \"eslint-plugin-prettier\": \"^3.4.0\",\n \"eslint-plugin-promise\": \"^5.1.0\",\n \"eslint-plugin-standard\": \"^5.0.0\",\n \"eslint-plugin-vue\": \"^7.9.0\",\n \"googleapis\": \"^71.0.0\",\n \"image-webpack-loader\": \"^7.0.1\",\n \"imagemin-mozjpeg\": \"^9.0.0\",\n \"imagemin-pngquant\": \"^9.0.2\",\n \"minify-css-string\": \"^1.0.0\",\n \"plop\": \"^2.4.0\",\n \"prettier\": \"^2.2.1\",\n \"sass-migrator\": \"^1.3.9\",\n \"storybook\": \"^6.2.8\",\n \"storybook-readme\": \"^5.0.9\",\n \"stylus\": \"^0.54.8\",\n \"stylus-loader\": \"^4.0.0\",\n \"vue-loader\": \"^15.9.6\",\n \"vue-recaptcha\": \"^1.1.1\",\n \"vue-template-compiler\": \"^2.6.6\",\n \"vue2-leaflet\": \"2.5.2\",\n \"vue2-leaflet-editablecirclemarker\": \"^1.0.5\",\n \"vue2-leaflet-geosearch\": \"1.0.6\",\n \"vue2-leaflet-googlemutant\": \"^2.0.0\",\n \"vue2-leaflet-markercluster\": \"^3.1.0\",\n \"vuetify-loader\": \"^1.7.2\"\n },\n \"browserslist\": {\n \"production\": [\n \">0.2%\",\n \"not dead\",\n \"not op_mini all\",\n \"ie 11\"\n ]\n }\n}\n```\n\n```text\nUsing / for division is deprecated and will be removed in Dart Sass 2.0.0.\n```\n\n```text\n\"sass\": \"~1.32.6\"\n```\n\n```text\n~\n```\n\n```text\n/\n```\n\n```text\n'@nuxtjs/style-resources'\n```\n\n```text\nbuildModules\n```\n\n```text\nhoistUseStatements: true\n```\n\n```text\nstyleResources\n```\n\n```text\n@use 'sass:math';\n```\n\n```text\na/b\n```\n\n```text\nmath.div(a, b)\n```\n\n```json\n\"resolutions\": {\n \"@nuxtjs/vuetify/**/sass\": \"1.32.12\"\n}\n```\n\n```json\n\"devDependencies\": {\n ...,\n \"sass\": \"~1.32.12\"\n}\n```\n\n```text\npackage.json\n```\n\n```text\npackage.json\n```\n\n```text\n@nuxtjs/vuetify\n```\n\n```text\nrm -r .\\node_modules\\\n```\n\n```text\nrm -r .\\package-lock.json\n```\n\n```text\n\"sass\": \"1.32.13\"\n```\n\n```text\ndevDependencies\n```\n\n```text\nrm -R node_modules\n```\n\n```text\nrm -R package-lock.json\n```\n\n```text\n\"sass\": \"1.32.13\"\n```\n\n```text\ndevDependencies\n```\n\n```text\nnuxtjs/vuetify\n```\n\n```text\n\"sass\": \"~1.32.12\"\n```\n\n```text\n$ npm install\n```\n\n```text\n@use \"sass:math\";\n\n// WRONG, will not work in future Sass versions.\n@debug (12px/4px); // 3\n\n// RIGHT, will work in future Sass versions.\n@debug math.div(12px, 4px); // 3\n```\n\n```sh\n$ npm install -g sass-migrator\n$ sass-migrator division **/*.scss\n```\n\n```text\nsass\n```\n\n```text\nnpm update\n```\n\n```text\nnuxt\n```\n\n```text\n@nuxtjs/vuetify\n```\n\n```text\nyarn add @nuxtjs/vuetify@^1.0.0 -D\n```\n\n```text\nnpm i @nuxtjs/vuetify@^1.0.0 --save-dev\n```\n\n```text\n@nuxtjs/vuetify\n```\n\n```text\nsass\": \"^1.32.12\n```\n\n```text\n\"sass\": \"1.32.12\"\n```\n\n```text\nnpx sass-migrator division **/*.scss\n```\n\n```js\n{\n ....\n loaderOptions: {\n sass: {\n quietDeps: true\n }\n }\n}\n```\n\n========================================\n\nComments:\n- Looks like a Wont-Fix bug/implementation in Vuetify 2: From Vuetify issue #13694: `This is fixed in Vuetify 3, you now have to use vuetify-loader or @vuetify/vite-plugin to change variables. Vuetify 2 is still limited to sass@~1.32`\n- See also Vuetify issue #13694.\n- `nuxt biuld` is working fine, but got same errors for `nuxt generate` command\n- show me the error or your error screenshot\n- I would recommend against downgrading packages to suppress some warnings at compile time, as well as deleting package-lock to install a package. If you really want to downgrade i suggest using \"npm ls sass\" to detect what version is being used now and by which dependancies. then \"npm install --save-dev sass@1.32.12\". check again with ls to see if the install worked or if another dependancy is in the way. Then fix that dependancy instead of bombing your repo.\n- This might be reasonable in a development dependency, but in this case my UI framework depends on Sass, causing my builds to break due to excessive output. This is nothing I should need to fix, and certainly should *not* occur after a minor version update.\n- it's only a warning and not an error, it does not break anything. it's there to annoy you so you would fix each and every line\n- It breaks tooling that does not expect this message to be printed in a seemingly endless loop, for instance when using Vuetify - which apparently has *lots and lots and lots of places* the deprecated division style is used. I'm not rambling against Sass here, but Vuetify: they should have used a more restrictive Sass version to prevent this message from ever bothering downstream devs.\n- \"*but Vuetify: they should have used a more restrictive Sass version to prevent this message from ever bothering downstream devs.*\" Winner winner, chicken dinner! vsync's answer is the \"right\" one if your code produces this error string. And it sounds like Vuetify could benefit from a quick patch that follows vsync's advice. ;^) Worth mentioning that **the error string mentions an automated fix:** More info and automated migrator: https://sass-lang.com/d/slash-div).\n- For this solution, actually also work within vuetify's /node_modules/vuetify/** . but if new repo or removed node_modules it will come back.\n- @ruffin vsync's answer may be correct, but that doesn't change the fact that *it doesn't address this particular question*. The OP is quite obviously a *user* of Vuetify, not one of its contributors. Providing an answer targeted at the contributors of Vuetify may be valuable in itself, but not helpful for Vuetify users.\n- @MoritzFriedrich Yep; thanks. Looks like a typo in my previous comment: \"*And it sounds like Vuetify could benefit from a quick patch that follows vsync's **Moritz'** advice.*\" Sans typo, I'm making exactly your distinction. vsync \"*if your code produces this error string*\" and Mortiz (you) if you're a contributor for the benefit of \"*downstream devs*\". Was trying to say you (both together) were 100% on the money.\n- ...magical! Never has sass also!\n- This is the right answer and should be pinned, but things have changed since this post. I provided the updated config for vite here: stackoverflow.com/a/79038040/1331018","metadata":{"transformedAt":"2026-08-18T18:33:07.827Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":42,"totalLines":512,"estimatedTokens":3509}}6{"id":"stack-46044276","source":"stackoverflow","questionId":46044276,"title":"Vuex - Do not mutate vuex store state outside mutation handlers","tags":["vue.js","vuejs2","nuxt.js","vuex"],"text":"Title: Vuex - Do not mutate vuex store state outside mutation handlers\nTags: vue.js, vuejs2, nuxt.js, vuex\nSource: Stack Overflow\n\nQuestion:\nWhy do I get this error:\n\nError [vuex] Do not mutate vuex store state outside mutation handlers.\n\n**What does it mean?**\n\nIt happens when I try to type in the **edit input file**.\n\n`pages/todos/index.vue`\n\n```\n\n \n \n \n {{ todo.text }}\n delete\n\n \n\n \n \n- \n \n\nimport { mapMutations } from 'vuex'\n\nexport default {\n data () {\n return {\n todo: '',\n editedTodo: null\n }\n },\n head () {\n return {\n title: this.$route.params.slug || 'all',\n titleTemplate: 'Nuxt TodoMVC : %s todos'\n }\n },\n fetch ({ store }) {\n store.commit('todos/add', 'Hello World')\n },\n computed: {\n todos () {\n // console.log(this)\n return this.$store.state.todos.list\n }\n },\n methods: {\n add (e) {\n\n var value = this.todo && this.todo.trim()\n if (value) {\n this.$store.commit('todos/add', value)\n this.todo = ''\n }\n\n },\n toggle (todo) {\n this.$store.commit('todos/toggle', todo)\n },\n remove (todo) {\n this.$store.commit('todos/remove', todo)\n },\n\n doneEdit (todo) {\n this.editedTodo = null\n todo.text = todo.text.trim()\n if (!todo.text) {\n this.$store.commit('todos/remove', todo)\n }\n },\n cancelEdit (todo) {\n this.editedTodo = null\n todo.text = this.beforeEditCache\n },\n },\n directives: {\n 'todo-focus' (el, binding) {\n if (binding.value) {\n el.focus()\n }\n }\n },\n}\n\n.done {\n text-decoration: line-through;\n}\n\n```\n\n`stores/todos.js`\n\n```\nexport const state = () => ({\n list: []\n})\n\nexport const mutations = {\n add (state, text) {\n state.list.push({\n text: text,\n done: false\n })\n },\n remove (state, todo) {\n state.list.splice(state.list.indexOf(todo), 1)\n },\n toggle (state, todo) {\n todo.done = !todo.done\n }\n}\n```\n\nAny ideas how I can fix this?\n\n========================================\n\nTop Answer:\nHello I have get the same problem and solve it with clone my object using one of the following:\n\n```\n{ ...obj} //spread syntax \nObject.assign({}, obj)\nJSON.parse(JSON.stringify(obj))\n```\n\nFor your code I think you need to replace this part\n\n```\ncomputed: {\n todos () {\n // console.log(this)\n return this.$store.state.todos.list\n }\n}\n```\n\nWith this\n\n```\ncomputed: {\n todos () {\n // console.log(this)\n return {...this.$store.state.todos.list}\n }\n}\n```\n\nI don't make sure if this is the best way but hope this helpful for other people that have the same issue.\n\n========================================\n\nCode:\n```html\n<template>\n <ul>\n <li v-for=\"todo in todos\">\n <input type=\"checkbox\" :checked=\"todo.done\" v-on:change=\"toggle(todo)\">\n <span :class=\"{ done: todo.done }\">{{ todo.text }}</span>\n <button class=\"destroy\" v-on:click=\"remove(todo)\">delete</button>\n\n <input class=\"edit\" type=\"text\" v-model=\"todo.text\" v-todo-focus=\"todo == editedTodo\" @blur=\"doneEdit(todo)\" @keyup.enter=\"doneEdit(todo)\" @keyup.esc=\"cancelEdit(todo)\">\n\n </li>\n <li><input placeholder=\"What needs to be done?\" autofocus v-model=\"todo\" v-on:keyup.enter=\"add\"></li>\n </ul>\n</template>\n\n<script>\nimport { mapMutations } from 'vuex'\n\nexport default {\n data () {\n return {\n todo: '',\n editedTodo: null\n }\n },\n head () {\n return {\n title: this.$route.params.slug || 'all',\n titleTemplate: 'Nuxt TodoMVC : %s todos'\n }\n },\n fetch ({ store }) {\n store.commit('todos/add', 'Hello World')\n },\n computed: {\n todos () {\n // console.log(this)\n return this.$store.state.todos.list\n }\n },\n methods: {\n add (e) {\n\n var value = this.todo && this.todo.trim()\n if (value) {\n this.$store.commit('todos/add', value)\n this.todo = ''\n }\n\n },\n toggle (todo) {\n this.$store.commit('todos/toggle', todo)\n },\n remove (todo) {\n this.$store.commit('todos/remove', todo)\n },\n\n doneEdit (todo) {\n this.editedTodo = null\n todo.text = todo.text.trim()\n if (!todo.text) {\n this.$store.commit('todos/remove', todo)\n }\n },\n cancelEdit (todo) {\n this.editedTodo = null\n todo.text = this.beforeEditCache\n },\n },\n directives: {\n 'todo-focus' (el, binding) {\n if (binding.value) {\n el.focus()\n }\n }\n },\n}\n</script>\n\n<style>\n.done {\n text-decoration: line-through;\n}\n</style>\n```\n\n```js\nexport const state = () => ({\n list: []\n})\n\nexport const mutations = {\n add (state, text) {\n state.list.push({\n text: text,\n done: false\n })\n },\n remove (state, todo) {\n state.list.splice(state.list.indexOf(todo), 1)\n },\n toggle (state, todo) {\n todo.done = !todo.done\n }\n}\n```\n\n```text\npages/todos/index.vue\n```\n\n```text\nstores/todos.js\n```\n\n```html\n<input class=\"edit\" type=\"text\" v-model=\"todo.text\" v-todo-focus=\"todo == editedTodo\" @blur=\"doneEdit(todo)\" @keyup.enter=\"doneEdit(todo)\" @keyup.esc=\"cancelEdit(todo)\">\n```\n\n```text\nv-model\n```\n\n```text\ntodo.text\n```\n\n```text\n:value\n```\n\n```text\nv-on:input\n```\n\n```text\nv-on:change\n```\n\n```js\n{ ...obj} //spread syntax \nObject.assign({}, obj)\nJSON.parse(JSON.stringify(obj))\n```\n\n```js\ncomputed: {\n todos () {\n // console.log(this)\n return this.$store.state.todos.list\n }\n}\n```\n\n```js\ncomputed: {\n todos () {\n // console.log(this)\n return {...this.$store.state.todos.list}\n }\n}\n```\n\n```js\ncomputed: {\n ...mapState({\n todo: (state) => _.cloneDeep(state.todo)\n })\n}\n```\n\n```js\nexport default new Vuex.Store({\n ...\n strict: true\n})\n```\n\n```js\ncomputed: {\n todos () {\n return [ ...this.$store.state.todos.list ]\n }\n}\n```\n\n```js\nbuild: {\n transpile: ['lodash-es'],\n}\n```\n\n```html\n<script>\nimport { cloneDeep } from 'lodash-es'\n\n...\nconst properlyClonedObject = cloneDeep(myDeeplyNestedObject)\n...\n</script>\n```\n\n```text\nString\n```\n\n```text\nNumber\n```\n\n```text\nlodash\n```\n\n```text\nlodash-es\n```\n\n```text\nyarn add lodash-es\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n.vue\n```\n\n```text\nJSON.parse(JSON.stringify(object))\n```\n\n```text\nstructuredClone\n```\n\n```js\n// In stores/YourModule.js\nexport default {\n state: { name: 'Foo' },\n}\n```\n\n```js\n// In stores/YourModule.js\nexport default {\n state: () => {\n return { name: 'Foo' };\n },\n}\n```\n\n```text\ndata\n```\n\n```text\nconst toyData = await this.$store.dispatch(\n `user/fetchCoinToys`,\n payload\n)\nconst msgList = toyData.msglist.map((data) => {\n return { ...data }\n})\n```\n\n```text\nsomeAction({state, rootState}) {\n state.someValue = true;\n}\n```\n\n```text\nmutations: {\n ...\n setSomeValue(state, val) {\n state.someValue = val;\n },\n ...\n}\n...\nsomeAction({state, commit, rootState}) {\n commit('setSomeValue', true);\n}\n```\n\n```text\nthis: any\n```\n\n```text\ndata() {\n return {\n myList: []\n }\n},\ncomputed: {\n ...mapGetters(['storedList'])\n},\nasync mounted() {\n this.myList = this.storedList.map(item => {\n return {...item, created: moment(item.created).format(\"MMMM Do YYYY\")}\n })\n},\n```\n\n========================================\n\nComments:\n- You can just turn off Vuex strict mode.\n- @Xhua the strict mode is here for a reason (better practices), rather keep it to have cleaner code.\n- thanks. I have read that. but this example is fine using `v-model` - github.com/nuxt/todomvc/blob/master/pages/_slug.vue?\n- I recommend using data with v-model for forms in vuex.\n- OK for display but to set the value back, still have to make each field mutation (set new value)\n- Thanks! I was struggling with this issue for hours... Now it works :)\n- This is the option, which may be considered a workaround. Apparently, there is a store that has both \"local\" and \"cached\" data for these both to be available for other Vuex modules/Vue components which depend on the comparison of both. The \"cached\" is only changed inside the Vuex store, but the \"local\" is assigned to fields and table, where the exception \"do not mutate\" is thrown when a field inside the table gets changed. While it's logical, since we are mutating properties of computed Vuex store state, is it a mistaken approach to tie a store to the table? What might go wrong in such case?\n- @SeriousAngel In code he present he is using mutate method to vuex. better to use action (dispatch) . But the quicker implementation he can just remove strict mode. Better to use vuex: action > mutations > state > getters getters are cached in local memory. But in his case I think he receive this error from this line \"\" And he is mutating state directly in v-model, item of list, as his state.todos.list is array of o\n- @PabloRamirez , the option that company chose eventually was having 3 states: 1) The component's data (used in the table); 2) \"Local\" in the Vuex State that is to be in sync with the the first upon appropriate changes; 3) \"Cached\" or the \"Remote\" that represents the remote. In the result, watcher on the component's `data` changes the `local` in Vuex; and once clicked `Save`, the `local` is send to the remote and set in `cached`. I believe this allows to both have the adequate approach for mutations between the component and Vuex store; and carefully reset the whole to the known \"cached\".\n- But this answer is already given: stackoverflow.com/a/65651645/5468463\n- Spread operator will only make a shallow copy of the object.","metadata":{"transformedAt":"2026-08-18T18:33:07.827Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":483,"estimatedTokens":2291}}7{"id":"stack-67350359","source":"stackoverflow","questionId":67350359,"title":"Nuxt js - Fresh install of nuxt 2.14.6 contains babel \"loose option\" warnings","tags":["vue.js","nuxt.js","babeljs"],"text":"Title: Nuxt js - Fresh install of nuxt 2.14.6 contains babel \"loose option\" warnings\nTags: vue.js, nuxt.js, babeljs\nSource: Stack Overflow\n\nQuestion:\nI have a fresh install of nuxt version 2.14.6 and I would like to silence an error I get when I run the nuxt command:\n\n```\nWARN Though the \"loose\" option was set to \"false\" in your @babel/preset-env co\nThe \"loose\" option must be the same for @babel/plugin-proposal-class-properties,\n [\"@babel/plugin-proposal-private-methods\", { \"loose\": true }]\nto the \"plugins\" section of your Babel config.\n```\n\nI'm assuming I need to override the babel config in my nuxt.config.js file, but I haven't found any helpful solutions.\n\n========================================\n\nTop Answer:\nTry add these in nuxt.config.js:\n\n```\nbuild: {\n babel:{\n plugins: [\n [\"@babel/plugin-proposal-class-properties\", { \"loose\": true }],\n [\"@babel/plugin-proposal-private-methods\", { \"loose\": true }],\n [\"@babel/plugin-proposal-private-property-in-object\", { \"loose\": true }]\n ]\n } \n},\n```\n\n========================================\n\nCode:\n```text\nWARN Though the \"loose\" option was set to \"false\" in your @babel/preset-env co\nThe \"loose\" option must be the same for @babel/plugin-proposal-class-properties,\n [\"@babel/plugin-proposal-private-methods\", { \"loose\": true }]\nto the \"plugins\" section of your Babel config.\n```\n\n```js\nbuild: {\n babel:{\n plugins: [\n ['@babel/plugin-proposal-private-methods', { loose: true }]\n ]\n }\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nbuild\n```\n\n```text\nnuxt\n```\n\n```text\n2.15.2\n```\n\n```text\nv2.15.5\n```\n\n```text\nresolutions\n```\n\n```text\nbuild.babel.plugins\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nyarn.lock\n```\n\n```text\npackage-lock.json\n```\n\n```text\nnode_modules/.cache\n```\n\n```text\n.nuxt\n```\n\n```json\n\"dependencies\": {\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"core-js\": \"^3.15.1\",\n \"nuxt\": \"^2.15.7\",\n \"vuetify\": \"^2.5.5\"\n},\n\"devDependencies\": {\n \"@nuxtjs/vuetify\": \"^1.12.1\"\n}\n```\n\n```js\nbuild: {\n babel: {\n plugins: [\n ['@babel/plugin-proposal-private-property-in-object', { loose: true }]\n ],\n },\n}\n```\n\n```js\nbuild: {\n babel:{\n plugins: [\n [\"@babel/plugin-proposal-class-properties\", { \"loose\": true }],\n [\"@babel/plugin-proposal-private-methods\", { \"loose\": true }],\n [\"@babel/plugin-proposal-private-property-in-object\", { \"loose\": true }]\n ]\n } \n},\n```\n\n```text\n\"resolutions\": {\n \"@babel/core\": \"7.13.15\",\n \"@babel/preset-env\": \"7.13.15\"\n}\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- Feel free to check my answer here: stackoverflow.com/questions/68663581/… or in this question here: stackoverflow.com/a/67466363/8816585 @Anthony\n- Upvoted. It's always good to make sure you aren't silencing something you might actually care about, without fully understanding the ramifications. Don't mind me while I add this to my Babel config for now though... :D\n- Np, just wanted to add for completeness and for others.\n- Why? The current behavior is a bug (warnings on a fresh install), and it's a solution until a fixed version is available.\n- Alright I got the point. It wasn't primarily meant to be a critique to the proposed solution but more of an alternative. But it's up to moderators to decide.\n- It seems to be fixed with 2.15.5. cheerio 🥳.\n- It's just the mods having a power trip, as per usual on SO. This answer was vital to me frankly\n- Is is happening if the `nuxt` version is between `2.15.5` and `2.15.7`.\n- Valid answer for `nuxt: 2.15.7`\n- `@babel/plugin-proposal-private-property-in-object` is enough, no need to have all of them.\n- Thank you. I am using nuxt@2.14.0 and getting the same warnings littering the console. Listing all of the plugins like this worked for me whereas only listing `@babel/plugin-proposal-private-property-in-object` did not.","metadata":{"transformedAt":"2026-08-18T18:33:07.827Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":160,"estimatedTokens":959}}8{"id":"stack-54979644","source":"stackoverflow","questionId":54979644,"title":"“window is not defined” in Nuxt.js","tags":["vue.js","nuxt.js"],"text":"Title: “window is not defined” in Nuxt.js\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI get an error porting from Vue.js to Nuxt.js. \n\nI am trying to use `vue-session` in `node_modules`. It compiles successfully, but in the browser I see the error:\n\n ReferenceError window is not defined\n\n`node_modules\\vue-session\\index.js`:\n\n\r\n\r\n\n```\nVueSession.install = function(Vue, options) {\r\n if (options && 'persist' in options && options.persist) STORAGE = window.localStorage;\r\n else STORAGE = window.sessionStorage;\r\n Vue.prototype.$session = {\r\n flash: {\r\n parent: function() {\r\n return Vue.prototype.$session;\r\n },\n```\n\n\r\n\r\n\r\n\nso, I followed this documentation:\n\n`rewardadd.vue`:\n\n\r\n\r\n\n```\nimport VueSession from 'vue-session';\r\n\r\nVue.use(VueSession);\r\n\r\nif (process.client) {\r\n require('vue-session');\r\n}\n```\n\n\r\n\r\n\r\n\n`nuxt.config.js`:\n\n\r\n\r\n\n```\nbuild: {\r\n vendor: ['vue-session'],\n```\n\n\r\n\r\n\r\n\nBut I still cannot solve this problem.\n\n========================================\n\nTop Answer:\nThere is no window object on the server side rendering side. But the quick fix is to check `process.browser`.\n\n```\ncreated(){\n if (process.browser){\n console.log(window.innerWidth, window.innerHeight);\n }\n }\n```\n\nThis is a little bit sloppy but it works. Here's a good writeup about how to use plugins to do it better.\n\n========================================\n\nCode:\n```js\nVueSession.install = function(Vue, options) {\n if (options && 'persist' in options && options.persist) STORAGE = window.localStorage;\n else STORAGE = window.sessionStorage;\n Vue.prototype.$session = {\n flash: {\n parent: function() {\n return Vue.prototype.$session;\n },\n```\n\n```js\nimport VueSession from 'vue-session';\n\nVue.use(VueSession);\n\nif (process.client) {\n require('vue-session');\n}\n```\n\n```js\nbuild: {\n vendor: ['vue-session'],\n```\n\n```text\nvue-session\n```\n\n```text\nnode_modules\n```\n\n```text\nnode_modules\\vue-session\\index.js\n```\n\n```text\nrewardadd.vue\n```\n\n```text\nnuxt.config.js\n```\n\n```js\nimport Vue from 'vue';\n// your imported custom plugin or in this scenario the 'vue-session' plugin\nimport VueSession from 'vue-session';\n\nVue.use(VueSession);\n```\n\n```js\nplugins: [\n { src: '~/plugins/myplugin.js', mode: 'client' }\n]\n```\n\n```js\nplugins: ['~/plugins/myplugin.client.js']\n```\n\n```text\nprocess.client\n```\n\n```text\nprocess.browser\n```\n\n```text\n~/plugins/myplugin.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n.server.js\n```\n\n```text\n.client.js\n```\n\n```text\n.client.js\n```\n\n```text\n.server.js\n```\n\n```js\nplugins: [\n { src: '~/plugins/vue-notifications', mode: 'client' }\n]\n```\n\n```js\ncreated(){\n if (process.browser){\n console.log(window.innerWidth, window.innerHeight);\n }\n }\n```\n\n```text\nprocess.browser\n```\n\n```text\nexport default {\n components: {\n StepProgress: () => import('vue-step-progress')\n }\n};\n```\n\n```js\nconst isClientSide: boolean = typeof window !== 'undefined'\n```\n\n```text\nwindow\n```\n\n```text\nimport Vue from 'vue'\nimport VueSession from 'vue-session'\n//depending on what you need it for\nVue.use(VueSession)\n// I needed mine as a component so I did something like this\nVue.component('vue-session', VueSession)\n```\n\n```text\nplugins:[\n...\n{ src: '~/plugins/vue-session.client.js'},\n...\n]\n```\n\n```text\nexport default {\n ...\n mounted() {\n if (process.client) {\n const VueSession = () => import('vue-session')\n }\n }\n...\n}\n```\n\n```text\n.client.js\n```\n\n```text\nplugins\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nssr: false\n```\n\n```text\nprocess.client\n```\n\n```text\n<client-only>\n```\n\n```text\nconst Ace = await import('ace-builds/src-noconflict/ace')\n```\n\n```text\ncomponents: { [process.client && 'VueEditor']: () => import('vue2-editor') }\n```\n\n```js\nif (process.client) {\n alert(window);\n}\n```\n\n```text\nprocess.client\n```\n\n========================================\n\nComments:\n- `window` exists only on the client side, in a browser. In Node.js evironment it does not exists.\n- get a same case\n- how to determine which plugin is needed for the server side and which for the client?\n- @ЯрославПрохоров that depends on what you want to achieve with your plugin and how much data it consumes on the client side(as this will impact your user experience). If you plugin makes a number of api calls that affects the loading times of pages I'd suggest making it asyncronous on the client side, on the other hand if you are touchy about making your plugin secure then render it on the backend. This is just my opinion you can ask other devs and get an answer that suits your application. Happy Holidays!\n- This works for me as well. But I would like to restrict the use of the `plugin` on specific components. Is there a way to import the plugin on specific components, rather than having it available globally?\n- @Adriano this is actually a very good idea (limit the usage of global plugins). To import it into a specific component, you can write `import VueSession from 'vue-session'` directly into your component. That way, it will be scoped there and only there. Useful when only one component uses the package and when you don't want to give a penalty to your whole app.\n- @kissu but then how do you get it to load only on client?\n- Put it inside of `` tags.\n- I just want to know why the heck is there a client and a server on the frontend, WHAT'S HAPPENING\n- @Seraf NuxtJS uses server side rendering so it typically attempts to process all JS code on the backend first before rendering on the frontend. Now the problems occurs when it attempts to process objects in the DOM, it will throw an error. Hence the need to manually configure the plugins to process certain parts of the code in the browser only.\n- i also found this post because of apex-charts in nuxt3 did you find a way to do it and keep ssr?\n- don't know why this is downvoted... fixed the issue for me 👍 n.b. `ssr: false` essentially means only client-side rendering. So I guess this is because server-side doesn't know what the Window object is because it isn't a browser...\n- you can use it in vue2, too","metadata":{"transformedAt":"2026-08-18T18:33:07.828Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":303,"estimatedTokens":1508}}9{"id":"stack-66127933","source":"stackoverflow","questionId":66127933,"title":"Cloud Run: \"Failed to start and then listen on the port defined by the PORT environment variable.\" When I use 8080","tags":["google-cloud-platform","dockerfile","nuxt.js","google-cloud-run"],"text":"Title: Cloud Run: \"Failed to start and then listen on the port defined by the PORT environment variable.\" When I use 8080\nTags: google-cloud-platform, dockerfile, nuxt.js, google-cloud-run\nSource: Stack Overflow\n\nQuestion:\nI got this error message when I try to run my container in Google Cloud Run.\n\n```\ntype: Ready\nstatus: 'False'\nreason: HealthCheckContainerError\nmessage: |-\nCloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information.\n```\n\nI already checked the followings but nothing helped to me:\n\nhttps://cloud.google.com/run/docs/troubleshooting\n\nCloud Run error: Container failed to start\n\nMy container is running locally and it's listening on default PORT `8080` with HOST configured as `0.0.0.0`.\n\nMy Dockerfile:\n\n```\nFROM node:10\n\nWORKDIR /usr/src/app\n\nENV PORT 8080\nENV HOST 0.0.0.0\n\nCOPY package*.json ./\n\nRUN npm install --only=production\n\nCOPY . .\n\nRUN npm run build\n\nCMD npm start\n```\n\nAny idea on why Cloud Run keeps failing to listen on the port?\n\nProject GitHub repo:\n\nhttps://github.com/fodorpapbalazsdev/ssr-app\n\n========================================\n\nTop Answer:\nThe attached logs seem to indicate your entrypoint may be malformed.\n\nFailed to create init process: failed to load /usr/local/bin/docker-entrypoint.sh: exec format error\",\n\nAre there any commands or arguments specified as input? Would it be possible for you to put the complete yaml for the cloud run instance either in your repo, a gist, or in this question?\n\nhttps://i.sstatic.net/LjMeB.png\n\n========================================\n\nCode:\n```text\ntype: Ready\nstatus: 'False'\nreason: HealthCheckContainerError\nmessage: |-\nCloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information.\n```\n\n```text\nFROM node:10\n\nWORKDIR /usr/src/app\n\nENV PORT 8080\nENV HOST 0.0.0.0\n\nCOPY package*.json ./\n\nRUN npm install --only=production\n\nCOPY . .\n\nRUN npm run build\n\nCMD npm start\n```\n\n```text\n8080\n```\n\n```text\n0.0.0.0\n```\n\n```text\n--platform linux/amd64\n```\n\n```text\ncontainer failed to start and listen to the $PORT\n```\n\n```text\nApplication failed to start: Failed to create init process: failed to load /usr/local/bin/npm: exec format error\n```\n\n```text\nExecutables in the container image must be compiled for Linux 64-bit. Cloud Run specifically supports the Linux x86_64 ABI format.\n```\n\n```text\nFROM node:10\n\nWORKDIR /usr/src/app\n\nENV PORT 8080\nENV HOST 0.0.0.0\n\nCOPY package*.json ./\n\nRUN npm install --only=production\n\nCOPY . .\n\nRUN npm run build\nEXPOSE 8080\nCMD npm start\n```\n\n```text\nFROM node:10\n\nWORKDIR /usr/src/app\n\nENV PORT 8080\nENV HOST 0.0.0.0\n\nCOPY package*.json ./\n\nRUN npm install \n\nCOPY . .\n\nRUN npm run build\n\nCMD npm start\n```\n\n```text\nsteps:\n- name: 'gcr.io/cloud-builders/docker'\n entrypoint: 'bash'\n args: ['-c','docker build --no-cache -t gcr.io/$PROJECT_ID/testssr:$SHORT_SHA .']\n- name: 'gcr.io/cloud-builders/docker'\n args: ['push','gcr.io/$PROJECT_ID/testssr:$SHORT_SHA']\n- name: 'gcr.io/cloud-builders/gcloud'\n args:\n - 'beta'\n - 'run'\n - 'deploy'\n - 'testssr'\n - '--image=gcr.io/$PROJECT_ID/testssr:$SHORT_SHA'\n - '--region=us-central1'\n - '--platform=managed'\n```\n\n```text\nexport default {\n // Global page headers: https://go.nuxtjs.dev/config-head\n server: {\n port: process.env.PORT, // default: 3000\n host: process.env.HOST // default: localhost\n },\n head: {\n title: 'ssr-app',\n htmlAttrs: {\n lang: 'en'\n },\n\n ...\n}\n```\n\n```text\nserver\n```\n\n========================================\n\nComments:\n- Edit your question with all details. Links change, break and get deleted. The content of links might change in the future. It is OK to include links as an addition reference but you must include everything in the question.\n- What's your logs in Cloud Logging?\n- @guillaumeblaquiere see my first comment here: github.com/fodorpapbalazsdev/ssr-app/issues/1\n- Did you manage to find a solution for this problem? I'm facing the same problem and would appreciate any help!\n- I faced the same problem and I haven't found a solution yet. I'm facing this problem when I try to convert my image file that contains a static web project based on Nginx to service. Did you find a solution???\n- See the answer from @Bk Lim. that was the solution for me.\n- You can found my YAML file here: github.com/fodorpapbalazsdev/ssr-app/issues/1\n- I noticed you are browsing to 'localhost:8080' locally. If you browse to '0.0.0.0:8080' does that work? Localhost may be binding to '127.0.0.1:8080'. cloud.google.com/run/docs/troubleshooting#listen_address\n- Yes, '0.0.0.0:8080' is also working locally.\n- `EXPOSE` has no effect on a Cloud Run container. It is a comment only in Cloud Run.\n- @BalázsFodor-Pap does the update on this answer solve your issue? You can execute configs manually by following this doc cloud.google.com/cloud-build/docs/running-builds/…\n- @DonnaldCucharo No 'EXPOSE 8080' not solved my issue. github.com/fodorpapbalazsdev/ssr-app/blob/…\n- If you look at my update I have removed the EXPOSE as it doesnt matter in cloud run. I have taken your repo and set up build pipeline, the only problem i faced was removing —only=production as It failed to build. After I have build your container it is running just fine on Cloud Run.\n- @MaciejPerliński and where should I update the cloudbuild.yaml file? I removed '--only=production' from my Dockerfile and it's still not workging. Is this cloudbuild.yaml mandatory? or the default: github.com/fodorpapbalazsdev/ssr-app/issues/1#issue-80496563‌​5 is ok? github.com/fodorpapbalazsdev/ssr-app/pull/2\n- I have set up the Cloud Build and this cloud build is building your image whenever there is a change in your repository connected to the your project. So I'm not sure where is a problem but using Cloud Build for building the image and deploying it to the Cloud Run proves to be working fine and there is no problem with your code. To conclude cloudbuild.yaml is telling cloud build how to build and deploy your container.\n- By introducing Cloud Build you'll resolve your problem and introduce CD/CI tool which is always a good thing.\n- I edited nuxt.config.js as you suggested: github.com/fodorpapbalazsdev/ssr-app/blob/… It not solve the problem. I am just wondering, why my app run locally and why I able to open localhost:8080 (using 'docker run -d -p 8080:8080 imageid'), if its not working on Cloud Run ?\n- @BalázsFodor-Pap I agree. I'm wondering too as it seems to be working fine on Docker as well as on Cloud Run (both on master and the branch containing my solution) though I had to add '@nuxt/typescript-build' on dependencies to build the image. Are you sure that we have the code similar to what you're testing? I can see a Nuxt.js logo when access the Cloud Run URL.\n- Yes, I am almost 100% sure about that I'm using the same code, same image. (But maybe I miss something, because I'm new in these technologies) I put some screenshot to here: github.com/fodorpapbalazsdev/ssr-app/issues/…\n- This worked for me. The full command: `docker buildx build --platform linux/amd64 -t image-name:v0.1.0 .` Reference: Docker Docs\n- After losing more hours of my life to this than I care to admit to, this solved my problem. Thank you so much.\n- Thanks, this worked for me on M1 as well. By the way, you should update your reference to \"the other answer in this post\".\n- This worked for me. I love stackoverflow. Thank you very much. Congrats to everyone that got new laptops recently.\n- `docker buildx build --platform linux/amd64 -t TAG_NAME .`\n- Even Google Cloud could not resolve my issue until I came to SO. M1 and its issue. Definitely `--platform=linux/amd64`\n- This caused immense frustraition, glad there is a quick resolution but they should just always specify that argument if this edge case can come up imo\n- The one answer chatgpt couldn't solve for me. Kudos, my man.\n- I cannot stress how helpul this answer was! many many thanks\n- Thank you SO much! Please let me know if I can buy you a coffee/beer!!\n- Lost sooooo many hours, changed the whole wsgi (from apache mod_wsgi) to gunicorn (and even tried to deploy example images).... just to see that I needed to build with the proper platform flag. This is the kind of things we need here.\n- This answer is a stack overflow GEM!! Thank you!\n- Adding this flag doesn't seem to the --platform linux/amd64 to my Dockerfile doesn't seem to fix this issue when I deploy the revision to Cloud Run. If any one can offer any insight, I've linked my question: stackoverflow.com/questions/79067392/…","metadata":{"transformedAt":"2026-08-18T18:33:07.828Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":227,"estimatedTokens":2195}}10{"id":"stack-56966137","source":"stackoverflow","questionId":56966137,"title":"How to run NUXT (npm run dev) with HTTPS in localhost?","tags":["vue.js","nginx","nginx-reverse-proxy","nuxt.js"],"text":"Title: How to run NUXT (npm run dev) with HTTPS in localhost?\nTags: vue.js, nginx, nginx-reverse-proxy, nuxt.js\nSource: Stack Overflow\n\nQuestion:\n**EDIT:** Updated the text in general to keep it shorter and more concise.\n\nI am trying to configure HTTPS when I run `npm run dev` so I can test MediaStream and alike locally (for which browsers require me to provide HTTPS).\n\nI am trying to configure it through nuxt.config.js but without any success.\n\nHere is my nuxt.config.js file:\n\n```\nimport fs from \"fs\";\nimport pkg from \"./package\";\n\nexport default {\n mode: \"spa\",\n\n /*\n ** Headers of the page\n */\n head: {\n title: pkg.name,\n meta: [\n { charset: \"utf-8\" },\n { name: \"viewport\", content: \"width=device-width, initial-scale=1\" },\n { hid: \"description\", name: \"description\", content: pkg.description },\n ],\n link: [\n { rel: \"icon\", type: \"image/x-icon\", href: \"/favicon.ico\" },\n ],\n },\n\n /*\n ** Customize the progress-bar color\n */\n loading: { color: \"#fff\" },\n\n /*\n ** Global CSS\n */\n css: [\n \"element-ui/lib/theme-chalk/index.css\",\n \"@makay/flexbox/flexbox.min.css\",\n ],\n\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n \"@/plugins/element-ui\",\n \"@/plugins/vue-upload\",\n \"@/plugins/axios-error-event-emitter\",\n \"@/plugins/eventemitter2\",\n \"@/plugins/vue-awesome\",\n \"@/plugins/webrtc-adapter\",\n \"@/plugins/vue-browser-detect-plugin\",\n ],\n\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://axios.nuxtjs.org/usage\n \"@nuxtjs/axios\",\n \"@nuxtjs/pwa\",\n ],\n /*\n ** Axios module configuration\n */\n axios: {\n // See https://github.com/nuxt-community/axios-module#options\n baseURL: process.env.NODE_ENV === \"production\" ? \"https://startupsportugal.com/api/v1\" : \"http://localhost:8080/v1\",\n },\n\n /*\n ** Build configuration\n */\n build: {\n transpile: [/^element-ui/, /^vue-awesome/],\n\n filenames: {\n app: ({ isDev }) => (isDev ? \"[name].[hash].js\" : \"[chunkhash].js\"),\n chunk: ({ isDev }) => (isDev ? \"[name].[hash].js\" : \"[chunkhash].js\"),\n },\n\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n // Run ESLint on save\n\n if (ctx.isClient) config.devtool = \"#source-map\";\n\n if (ctx.isDev) {\n config.devServer = {\n https: {\n key: fs.readFileSync(\"server.key\"),\n cert: fs.readFileSync(\"server.crt\"),\n ca: fs.readFileSync(\"ca.pem\"),\n },\n };\n }\n\n if (ctx.isDev && ctx.isClient) {\n config.module.rules.push({\n enforce: \"pre\",\n test: /\\.(js|vue)$/,\n loader: \"eslint-loader\",\n exclude: /(node_modules)/,\n });\n }\n },\n },\n};\n```\n\nAlso, here you can see my dependencies in package.json:\n\n```\n\"dependencies\": {\n \"@makay/flexbox\": \"^3.0.0\",\n \"@nuxtjs/axios\": \"^5.3.6\",\n \"@nuxtjs/pwa\": \"^2.6.0\",\n \"cross-env\": \"^5.2.0\",\n \"element-ui\": \"^2.4.11\",\n \"eventemitter2\": \"^5.0.1\",\n \"lodash\": \"^4.17.11\",\n \"nuxt\": \"^2.8.0\",\n \"pug\": \"^2.0.3\",\n \"pug-plain-loader\": \"^1.0.0\",\n \"quagga\": \"^0.12.1\",\n \"stylus\": \"^0.54.5\",\n \"stylus-loader\": \"^3.0.2\",\n \"vue-awesome\": \"^3.5.3\",\n \"vue-browser-detect-plugin\": \"^0.1.2\",\n \"vue-upload-component\": \"^2.8.20\",\n \"webrtc-adapter\": \"^7.2.4\"\n },\n \"devDependencies\": {\n \"@nuxtjs/eslint-config\": \"^0.0.1\",\n \"babel-eslint\": \"^10.0.1\",\n \"eslint\": \"^5.15.1\",\n \"eslint-config-airbnb-base\": \"^13.1.0\",\n \"eslint-config-standard\": \">=12.0.0\",\n \"eslint-import-resolver-webpack\": \"^0.11.1\",\n \"eslint-loader\": \"^2.1.2\",\n \"eslint-plugin-import\": \">=2.16.0\",\n \"eslint-plugin-jest\": \">=22.3.0\",\n \"eslint-plugin-node\": \">=8.0.1\",\n \"eslint-plugin-nuxt\": \">=0.4.2\",\n \"eslint-plugin-promise\": \">=4.0.1\",\n \"eslint-plugin-standard\": \">=4.0.0\",\n \"eslint-plugin-vue\": \"^5.2.2\",\n \"nodemon\": \"^1.18.9\"\n }\n```\n\nHowever when I run `npm run dev` it still does not provide HTTPS, but does not provide any error output as well...\n\nThe output is exactly the same as if I didn't have the HTTPS configurations in nuxt.config.js:\n\n```\n$ npm run dev\n\n> clothing-demo@1.0.0 dev /mnt/d/tralha/clothing-demo-app/frontend\n> nuxt --hostname 0.0.0.0 --port 3000\n\n ╭────────────────────────────────────────────────╮\n │ │\n │ Nuxt.js v2.8.1 │\n │ Running in development mode (spa) │\n │ │\n │ Listening on: http://192.168.126.241:3000/ │\n │ │\n ╰────────────────────────────────────────────────╯\n\nℹ Preparing project for development 14:30:34\nℹ Initial build may take a while 14:30:35\n✔ Builder initialized 14:30:35\n✔ Nuxt files generated\n```\n\n========================================\n\nTop Answer:\nYou can use `mkcert`\n\n- Install mkcert:\n\n```\nbrew install mkcert\nbrew install nss # if you use Firefox\n```\n\n- Add mkcert to your local root CAs:\n\n```\nmkcert -install\n```\n\n- In your terminal, navigate to your site's root directory or whichever directory you'd like the certificates to be located at. And run:\n\n```\nmkcert localhost\n```\n\n- Add the following to your `nuxt.config.js`:\n\n```\nserver: {\n https: {\n key: fs.readFileSync(path.resolve(__dirname, 'localhost-key.pem')),\n cert: fs.readFileSync(path.resolve(__dirname, 'localhost.pem'))\n }\n }\n```\n\nhttps://web.dev/how-to-use-local-https/\n\n========================================\n\nCode:\n```text\nimport fs from \"fs\";\nimport pkg from \"./package\";\n\nexport default {\n mode: \"spa\",\n\n /*\n ** Headers of the page\n */\n head: {\n title: pkg.name,\n meta: [\n { charset: \"utf-8\" },\n { name: \"viewport\", content: \"width=device-width, initial-scale=1\" },\n { hid: \"description\", name: \"description\", content: pkg.description },\n ],\n link: [\n { rel: \"icon\", type: \"image/x-icon\", href: \"/favicon.ico\" },\n ],\n },\n\n /*\n ** Customize the progress-bar color\n */\n loading: { color: \"#fff\" },\n\n /*\n ** Global CSS\n */\n css: [\n \"element-ui/lib/theme-chalk/index.css\",\n \"@makay/flexbox/flexbox.min.css\",\n ],\n\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n \"@/plugins/element-ui\",\n \"@/plugins/vue-upload\",\n \"@/plugins/axios-error-event-emitter\",\n \"@/plugins/eventemitter2\",\n \"@/plugins/vue-awesome\",\n \"@/plugins/webrtc-adapter\",\n \"@/plugins/vue-browser-detect-plugin\",\n ],\n\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://axios.nuxtjs.org/usage\n \"@nuxtjs/axios\",\n \"@nuxtjs/pwa\",\n ],\n /*\n ** Axios module configuration\n */\n axios: {\n // See https://github.com/nuxt-community/axios-module#options\n baseURL: process.env.NODE_ENV === \"production\" ? \"https://startupsportugal.com/api/v1\" : \"http://localhost:8080/v1\",\n },\n\n /*\n ** Build configuration\n */\n build: {\n transpile: [/^element-ui/, /^vue-awesome/],\n\n filenames: {\n app: ({ isDev }) => (isDev ? \"[name].[hash].js\" : \"[chunkhash].js\"),\n chunk: ({ isDev }) => (isDev ? \"[name].[hash].js\" : \"[chunkhash].js\"),\n },\n\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n // Run ESLint on save\n\n if (ctx.isClient) config.devtool = \"#source-map\";\n\n if (ctx.isDev) {\n config.devServer = {\n https: {\n key: fs.readFileSync(\"server.key\"),\n cert: fs.readFileSync(\"server.crt\"),\n ca: fs.readFileSync(\"ca.pem\"),\n },\n };\n }\n\n if (ctx.isDev && ctx.isClient) {\n config.module.rules.push({\n enforce: \"pre\",\n test: /\\.(js|vue)$/,\n loader: \"eslint-loader\",\n exclude: /(node_modules)/,\n });\n }\n },\n },\n};\n```\n\n```text\n\"dependencies\": {\n \"@makay/flexbox\": \"^3.0.0\",\n \"@nuxtjs/axios\": \"^5.3.6\",\n \"@nuxtjs/pwa\": \"^2.6.0\",\n \"cross-env\": \"^5.2.0\",\n \"element-ui\": \"^2.4.11\",\n \"eventemitter2\": \"^5.0.1\",\n \"lodash\": \"^4.17.11\",\n \"nuxt\": \"^2.8.0\",\n \"pug\": \"^2.0.3\",\n \"pug-plain-loader\": \"^1.0.0\",\n \"quagga\": \"^0.12.1\",\n \"stylus\": \"^0.54.5\",\n \"stylus-loader\": \"^3.0.2\",\n \"vue-awesome\": \"^3.5.3\",\n \"vue-browser-detect-plugin\": \"^0.1.2\",\n \"vue-upload-component\": \"^2.8.20\",\n \"webrtc-adapter\": \"^7.2.4\"\n },\n \"devDependencies\": {\n \"@nuxtjs/eslint-config\": \"^0.0.1\",\n \"babel-eslint\": \"^10.0.1\",\n \"eslint\": \"^5.15.1\",\n \"eslint-config-airbnb-base\": \"^13.1.0\",\n \"eslint-config-standard\": \">=12.0.0\",\n \"eslint-import-resolver-webpack\": \"^0.11.1\",\n \"eslint-loader\": \"^2.1.2\",\n \"eslint-plugin-import\": \">=2.16.0\",\n \"eslint-plugin-jest\": \">=22.3.0\",\n \"eslint-plugin-node\": \">=8.0.1\",\n \"eslint-plugin-nuxt\": \">=0.4.2\",\n \"eslint-plugin-promise\": \">=4.0.1\",\n \"eslint-plugin-standard\": \">=4.0.0\",\n \"eslint-plugin-vue\": \"^5.2.2\",\n \"nodemon\": \"^1.18.9\"\n }\n```\n\n```text\n$ npm run dev\n\n> clothing-demo@1.0.0 dev /mnt/d/tralha/clothing-demo-app/frontend\n> nuxt --hostname 0.0.0.0 --port 3000\n\n\n ╭────────────────────────────────────────────────╮\n │ │\n │ Nuxt.js v2.8.1 │\n │ Running in development mode (spa) │\n │ │\n │ Listening on: http://192.168.126.241:3000/ │\n │ │\n ╰────────────────────────────────────────────────╯\n\nℹ Preparing project for development 14:30:34\nℹ Initial build may take a while 14:30:35\n✔ Builder initialized 14:30:35\n✔ Nuxt files generated\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run dev\n```\n\n```text\nopenssl genrsa 2048 > server.key\nchmod 400 server.key\nopenssl req -new -x509 -nodes -sha256 -days 365 -key server.key -out server.crt\n```\n\n```text\nimport path from 'path'\nimport fs from 'fs'\n```\n\n```text\nserver: {\n https: {\n key: fs.readFileSync(path.resolve(__dirname, 'server.key')),\n cert: fs.readFileSync(path.resolve(__dirname, 'server.crt'))\n }\n}\n```\n\n```text\napp.listen(port, host)\n consola.ready({\n message: `Server listening on http://${host}:${port}`,\n badge: true\n })\n```\n\n```text\nhttps.createServer(nuxt.options.server.https, app).listen(port, host);\n```\n\n```text\nserver/index.js\n```\n\n```text\nserver/index.js\n```\n\n```text\nconst https = require('https')\n```\n\n```text\naxios: {\n baseURL: 'http://yourapi:8000',\n https:false,\n },\n```\n\n```text\nserver: {\n https: {\n key: fs.readFileSync(path.resolve(__dirname, '[key-file-name].key')),\n cert: fs.readFileSync(path.resolve(__dirname, '[crt-file-name].crt')),\n passphrase: '[your password]'\n }\n }\n```\n\n```text\n\"dev\": \"nuxt --hostname subdmain.domain.com --port 8000\"\n```\n\n```text\nhttps\n```\n\n```text\ndomain\n```\n\n```text\nsubdomain\n```\n\n```text\nSingle Sign On\n```\n\n```text\nopenssl.exe\n```\n\n```text\nC:\\Program Files\\Git\\usr\\bin\n```\n\n```text\npkcs12 -in '[full-path-and-name-of-your].pfx' -nocerts -out '[full-path-and-name-to-create-the].key'\n```\n\n```text\npkcs12 -in '[full-path-and-name-of-your].pfx' -clcerts -nokeys -out '[full-path-and-name-to-create-the].crt'\n```\n\n```text\nserver\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nhttps://subdmain.domain.com:8000\n```\n\n```sh\nbrew install mkcert\nbrew install nss # if you use Firefox\n```\n\n```sh\nmkcert -install\n```\n\n```sh\nmkcert localhost\n```\n\n```js\nserver: {\n https: {\n key: fs.readFileSync(path.resolve(__dirname, 'localhost-key.pem')),\n cert: fs.readFileSync(path.resolve(__dirname, 'localhost.pem'))\n }\n }\n```\n\n```text\nmkcert\n```\n\n```text\nnuxt.config.js\n```\n\n```json\n{\n \"scripts\": {\n \"dev\": \"nuxi dev --host website.test --https --ssl-key key.pem --ssl-cert cert.pem --port 3000\",\n}\n```\n\n```text\nNuxt 3\n```\n\n```text\nnuxt.config\n```\n\n```text\n--port, --host, --https, --ssl-cert\n```\n\n```text\n--ssl-key\n```\n\n```text\n--\n```\n\n```text\n// https://nuxt.com/docs/api/configuration/nuxt-config\nimport fs from \"fs-extra\";\nexport default defineNuxtConfig({\n devServer: {\n host: \"vios.uni.edu.my\",\n port: 3000,\n https: {\n key: fs.readFileSync(\"../ssl/private.key\").toString(),\n cert: fs.readFileSync(\"../ssl/cert.crt\").toString(),\n },\n },\n});\n```\n\n```text\nNuxt 3\n```\n\n```text\ndefineNuxtConfig\n```\n\n```text\n3.2.3\n```\n\n```text\nFor Nuxt 3 and using TypeScript\n```\n\n```text\nfs-extra\n```\n\n```text\n@types/fs-extra\n```\n\n```text\nkey\n```\n\n```text\ncert\n```\n\n```text\nstring\n```\n\n```text\nstring\n```\n\n```text\ntoString()\n```\n\n```text\nnpm run dev -- --host 0.0.0.0\n```\n\n```text\ndevServer: {\n https:true,\n port: your PORT, // default: 3000\n host: 'your HOST' // deafult: 'localhost'\n},\n```\n\n```text\nNODE_TLS_REJECT_UNAUTHORIZED=0\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n.env\n```\n\n========================================\n\nComments:\n- are you using webpack?\n- NUXT uses webpack. I'll add the dependencies and versions to the post\n- so you can use the https dev server to solve the problem? webpack.js.org/configuration/dev-server/#devserverhttps\n- I'm a bit lost. I added the following to my nuxt.config.js and tried \"npm run dev\" but nothing new happens... What am I missing? if (ctx.isDev) { config.devServer = { http2: true, }; }\n- why do you use http2 if you want https?\n- sorry, I mispelled, I meant https. Still that's not the cause, it had no effect at all... what am I missing?\n- can you show your webpackconfig for the https server pls?\n- Sure, I pastedbin it here: pastebin.com/SD2k77Ft\n- ok. I also removed the nginx part as it is not the core of the issue.\n- Have you the guid from the official website? nuxtjs.org/api/configuration-server/…\n- Having the same problem as OP. Followed these instructions to the letter but no luck.\n- This works for me, but how can I have this to only when I'm in development mode? This code is running in production and I don't want this.\n- @LincolnLemos try: server: process.env.NODE_ENV !== 'production' ? {https: {...}} : {},\n- Just in case somebody need it, this instructions stackoverflow.com/a/60516812/4059304 and this security.stackexchange.com/questions/163199/…\n- I'm using localhost.run. It works and easy to setup. You don't need to do all those setup to make local authority to work with emulator/simulator.\n- don't understand you last sentence. did you mean will use `http` instead of `https`?\n- Easiest and most complete solution. Thank you. To add on this, `const fs = require('fs'); const path = require('path');` must be included at the top of the nuxt.config.js file.\n- I get a \"No default export found in imported module \"fs-extra\".\" error, any idea how to fix this?\n- Have you tried to import it using an alias? `import * as fs from \"fs-extra\"`","metadata":{"transformedAt":"2026-08-18T18:33:07.828Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":56,"totalLines":671,"estimatedTokens":3664}}11{"id":"stack-48238472","source":"stackoverflow","questionId":48238472,"title":"How to set lang attribute on html element with Nuxt?","tags":["javascript","html","vue.js","nuxt.js","vue-meta"],"text":"Title: How to set lang attribute on html element with Nuxt?\nTags: javascript, html, vue.js, nuxt.js, vue-meta\nSource: Stack Overflow\n\nQuestion:\nUsing the file `nuxt.config.js` file, `head` contents can be customized to add some meta, or other things:\n\n```\nmodule.exports = {\n /*\n ** Headers of the page\n */\n head: {\n title: 'awesome title',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: 'Nuxt.js project' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n ...\n}\n```\n\nBut I can't find anything in the documentation to set attributes on the `html` element -- I want to set the `lang` attribute. Is there a way to do that?\n\n========================================\n\nTop Answer:\nIn Nuxt 3 type in the component\n\n```\n\nuseHead({\n htmlAttrs: {\n lang: 'en',\n style: 'font-size: 13px'\n }\n})\n\n```\n\nhttps://v3.nuxtjs.org/getting-started/seo-meta/\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n /*\n ** Headers of the page\n */\n head: {\n title: 'awesome title',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: 'Nuxt.js project' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n ...\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nhead\n```\n\n```text\nhtml\n```\n\n```text\nlang\n```\n\n```text\nmodule.exports = {\n head: {\n htmlAttrs: {\n lang: 'en'\n }\n }\n}\n```\n\n```text\nhead\n```\n\n```text\nhtmlAttrs\n```\n\n```js\n<script setup>\nuseHead({\n htmlAttrs: {\n lang: 'en',\n style: 'font-size: 13px'\n }\n})\n</script>\n```\n\n```text\nexport default defineNuxtConfig({\n app: {\n head: {\n htmlAttrs: {\n lang: 'en',\n },\n title: 'title',\n charset: 'utf-8',\n meta: [],\n link: [],\n }\n },\n})\n```\n\n```text\nnuxt.config.js\n```\n\n```js\n<template>\n <main>\n <NuxtPage />\n </main>\n</template>\n\n<script setup lang=\"ts\">\nuseHead({\n htmlAttrs: {\n lang: \"en\",\n },\n});\n</script>\n```\n\n```text\nuseHead()\n```\n\n```text\napp.vue\n```\n\n```text\nnuxt.config.ts\n```\n\n========================================\n\nComments:\n- Try Declaring language in HTML tag · Issue #388 · nuxt/nuxt.js\n- @yuriy636 it worked. Would you make it an answer so I can accept it?\n- What if you are using different languages (locales)?\n- This also work with Body bodyAttrs and Head headAttrs\n- Yes, like @JMK said, what if using i18n with different locales ?\n- @Vinny Looks like he created a separate question for that. Check stackoverflow.com/questions/50656053/…\n- Thanks! This isn't documented in v3.nuxtjs.org/getting-started/seo-meta\n- It is mentioned, but now displying is bugged github.com/nuxt/framework/issues/9178\n- I see, they changed link to docs and now there are two different methods (in component and in nuxt config), in april there was no option to add it by globally like today.","metadata":{"transformedAt":"2026-08-18T18:33:07.828Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":175,"estimatedTokens":774}}12{"id":"stack-54173375","source":"stackoverflow","questionId":54173375,"title":"potentially fixable with the `--fix` option","tags":["vue.js","eslint","nuxt.js"],"text":"Title: potentially fixable with the `--fix` option\nTags: vue.js, eslint, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am creating a app with nuxt.js but everytime I launch the app, gives me the error of eslint and saying \"potentially fixable with the `--fix` option.\"\n\nI did the command `npm run lint -- --fix` and it works but then If I do another change in any vue file it comes again the same error and I have to do it again\n\nAny idea of how to fix that?\n\n========================================\n\nTop Answer:\nIf anyone facing this issue when working with Cloud Functions try this. Find `package.json` file inside `functions` folder, replace\n\n```\n\"lint\": \"eslint --ext .js,.ts .\",\n```\n\nwith\n\n```\n\"lint\": \"eslint --ext .js,.ts . --fix\",\n```\n\nThen run the command again:\n\n```\nfirebase deploy --only functions\n```\n\nIt should fix all issues which fixable. If any error left (sometimes 1 or 2 still left) find that one and edit manually and voila it works.\n\n========================================\n\nCode:\n```text\n--fix\n```\n\n```text\nnpm run lint -- --fix\n```\n\n```js\nbuild: {\n extend(config, ctx) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/,\n options: {\n fix: true\n }\n })\n }\n}\n```\n\n```js\noptions: {\n fix: true\n}\n```\n\n```json\n{\n \"editor.codeActionsOnSave\": {\n \"source.fixAll\": true, // this one will fix it on save for you\n },\n \"eslint.options\": {\n \"extensions\": [\n \".html\",\n \".js\",\n \".vue\",\n \".jsx\",\n ]\n },\n \"eslint.validate\": [\n \"javascript\",\n \"javascriptreact\",\n \"typescript\",\n \"typescriptreact\",\n \"html\",\n \"vue\",\n ],\n}\n```\n\n```js\nmodule.exports = {\n root: true,\n env: {\n browser: true,\n node: true,\n },\n parserOptions: {\n parser: '@babel/eslint-parser',\n requireConfigFile: false,\n },\n extends: ['@nuxtjs']\n}\n```\n\n```text\nsettings.json\n```\n\n```text\n.eslintrc.js\n```\n\n```json\n\"scripts\": {\n \"lint\": \"eslint \\\"**/*.{js,mjs}\\\" && prettier --check --loglevel warn \\\"**/*.{js,mjs,json}\\\" && stylelint \\\"**/*.scss\\\"\",\n \"format\": \"eslint \\\"**/*.{js,mjs}\\\" --fix && prettier --write --loglevel warn \\\"**/*.{js,mjs,json}\\\" && stylelint \\\"**/*.scss\\\" --fix\",\n}\n```\n\n```text\nnpm run lint -- --fix\n```\n\n```text\nnpm run format\n```\n\n```text\nlint\n```\n\n```text\nformat\n```\n\n```text\n\"lint\": \"eslint --ext .js,.ts .\",\n```\n\n```text\n\"lint\": \"eslint --ext .js,.ts . --fix\",\n```\n\n```text\nfirebase deploy --only functions\n```\n\n```text\npackage.json\n```\n\n```text\nfunctions\n```\n\n========================================\n\nComments:\n- Is your editor formatting on save? Is it doing it the same way ESLint enforces?\n- No it's not. Should it be @jonrsharpe?\n- I asked two questions, which were you answering? If you're asking whether your editor should be applying the same formatting that your linter expects: yes, otherwise you *keep having to reformat it*.\n- Yeah you right. My answer would fit both of your questions. Yes it was for the first one. Thanks for the explanation\n- Was looking for this: `npm run lint -- --fix` - thank you!\n- Does this years-old answer apply to Nuxt 3?\n- Got `npm ERR! Missing script: \"format\"` What is your script for `format`?","metadata":{"transformedAt":"2026-08-18T18:33:07.828Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":167,"estimatedTokens":808}}13{"id":"stack-46175023","source":"stackoverflow","questionId":46175023,"title":"nuxt build --spa vs nuxt generate","tags":["vue.js","nuxt.js"],"text":"Title: nuxt build --spa vs nuxt generate\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhat is the difference between \n\n```\nnuxt build\n```\n\nvs\n\n```\nnuxt generate\n```\n\nvs \n\n```\nnuxt build --spa\n```\n\nI am trying to compile three different variations:\n\n```\n1. regular nuxt with ssr\n2. prerendered spa\n3. spa without prerendering\n```\n\nI am struggling to find the appropriate commands for it\n\n========================================\n\nCode:\n```text\nnuxt build\n```\n\n```text\nnuxt generate\n```\n\n```text\nnuxt build --spa\n```\n\n```text\n1. regular nuxt with ssr\n2. prerendered spa\n3. spa without prerendering\n```\n\n```text\nnuxt build\n```\n\n```text\nnuxt generate\n```\n\n```text\n--spa\n```\n\n```text\n--spa\n```\n\n```text\nnuxt build\n```\n\n```text\nnuxt generate\n```\n\n```text\nnuxt build --spa\n```\n\n========================================\n\nComments:\n- I just tried several combinations. Seems that 1 and 3 are correct. But 2 (nuxt generate --spa) seems to produce the same output in the dist folder as 3 (nuxt build --spa). So generate needs to be used without the --spa flag to prerender the pages. Please update your answer and I will accept it\n- @Chris Thanks for the feedback, I've made the update.\n- Does `nuxt generate` also minify JS/CSS?\n- @AliGajani have you found answer I also have the same question or hint about minify JS/CSS\n- @A.L not sure about before, but `nuxt generate` totally allows dynamic routes nowadays.\n- in nuxt.config.ts add \"ssr: false, target: 'static' \", and then use nuxt generate\n- What if you have different route rules? For example, prerender: true for blogs and landing pages and ssr: false for my dashboard. Should I use nuxt generate or nuxt build?\n- @Mathijs in that case you have to use `nuxt build`, else it will statically generate what the prederend looks like but not be dynamic, in that case you need a node server running, check it here: youtube.com/watch?v=SiT_1tfuPa4","metadata":{"transformedAt":"2026-08-18T18:33:07.828Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":93,"estimatedTokens":475}}14{"id":"stack-74548318","source":"stackoverflow","questionId":74548318,"title":"How to resolve \"Error: error:0308010C:digital envelope routines::unsupported\" Nodejs 18 error","tags":["javascript","node.js","vue.js","frontend","nuxt.js"],"text":"Title: How to resolve \"Error: error:0308010C:digital envelope routines::unsupported\" Nodejs 18 error\nTags: javascript, node.js, vue.js, frontend, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI need help with my NuxtJS application.\n\nI recently had ESLint conflicts in the app after I left it for some time without updating (2 months). So after I started working on it, it presented a challenge trying to resolve the ESLint issue. I then had to migrate the project to a newer version of Node and ESLint.\n\nAfter doing this, I solved the conflict issue and my project could install my dependencies, but now the server won't start. Node is now throwing an error that I don't even know how to fix. I don't know if many others are facing this issue after upgrading their versions of Node.js, but it's throwing an error about an unsupported hash function.\n\nHere is a screenshot of the terminal error that is preventing my server from starting up:\n\nhttps://i.sstatic.net/TQeVJ.png\n\nI have resolved all ESLint and syntax errors that came with the migration, so I don't know what else to do.\n\nBelow is a snippet of my nuxt.config.js file:\n\n```\nexport default {\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: 'heritage-fd',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: '' },\n { name: 'format-detection', content: 'telephone=no' }\n ],\n \n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ],\n \n script: [\n {\n src: '~/static/css/bootstrap.min.js',\n },\n ],\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\n {src: '~/static/css/bootstrap.min.css', lang: 'scss'},\n {src: '~/assets/scss/custom.scss', lang: 'scss'},\n {src: \"~layouts/global.css\"},\n {src: '~/static/css/style.css', lang: 'scss'},\n {src: '~/assets/css/main.css'}\n \n ],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [\n \"~/plugins/vee-validate.js\",\n { src: '~/plugins/persistedState.client.js', ssr: false }\n ],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n // https://go.nuxtjs.dev/eslint\n '@nuxtjs/eslint-module',\n 'nuxt-gsap-module',\n '@nuxtjs/fontawesome',\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\n // https://go.nuxtjs.dev/axios\n '@nuxtjs/axios',\n // https://go.nuxtjs.dev/pwa\n '@nuxtjs/pwa',\n '@nuxtjs/auth-next',\n 'nuxt-vue-select'\n ],\n\n // Axios module configuration: https://go.nuxtjs.dev/config-axios\n axios: {\n // Workaround to avoid enforcing hard-coded localhost:3000: https://github.com/nuxt-community/axios-module/issues/308\n baseURL: 'http://localhost:8000/api/',\n \n },\n\n // PWA module configuration: https://go.nuxtjs.dev/pwa\n pwa: {\n manifest: {\n lang: 'en',\n },\n },\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {\n transpile: [\"vee-validate/dist/rules\"],\n vendor: [\"vue-tables-2\"]\n },\n}\n```\n\n========================================\n\nTop Answer:\nIn my case this happened in my Github Actions build pipeline when I was running `npm run build`.\n\nI was able to fix it by providing the following environment argument:\n\n```\nexport NODE_OPTIONS=--openssl-legacy-provider\n```\n\nAccording from what I have read this node option can also be set in **package.json**.\n\nWhat I did was modifying the *scripts* section of my **package.json**:\n\n```\n\"scripts\": {\n \"ng\": \"set NODE_OPTIONS=--openssl-legacy-provider && ng\",\n \"start\": \"set NODE_OPTIONS=--openssl-legacy-provider && ng serve\",\n \"build\": \"ng build\",\n \"test\": \"ng test\",\n \"lint\": \"ng lint\",\n \"e2e\": \"ng e2e\"\n},\n```\n\nNow I can run `npm start` again without problems.\n\nThis seems a bit easier than downgrading nodejs to v16.\n\n========================================\n\nCode:\n```js\nexport default {\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: 'heritage-fd',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: '' },\n { name: 'format-detection', content: 'telephone=no' }\n ],\n \n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ],\n \n script: [\n {\n src: '~/static/css/bootstrap.min.js',\n },\n ],\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\n {src: '~/static/css/bootstrap.min.css', lang: 'scss'},\n {src: '~/assets/scss/custom.scss', lang: 'scss'},\n {src: \"~layouts/global.css\"},\n {src: '~/static/css/style.css', lang: 'scss'},\n {src: '~/assets/css/main.css'}\n \n ],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [\n \"~/plugins/vee-validate.js\",\n { src: '~/plugins/persistedState.client.js', ssr: false }\n ],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n // https://go.nuxtjs.dev/eslint\n '@nuxtjs/eslint-module',\n 'nuxt-gsap-module',\n '@nuxtjs/fontawesome',\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\n // https://go.nuxtjs.dev/axios\n '@nuxtjs/axios',\n // https://go.nuxtjs.dev/pwa\n '@nuxtjs/pwa',\n '@nuxtjs/auth-next',\n 'nuxt-vue-select'\n ],\n\n // Axios module configuration: https://go.nuxtjs.dev/config-axios\n axios: {\n // Workaround to avoid enforcing hard-coded localhost:3000: https://github.com/nuxt-community/axios-module/issues/308\n baseURL: 'http://localhost:8000/api/',\n \n },\n\n // PWA module configuration: https://go.nuxtjs.dev/pwa\n pwa: {\n manifest: {\n lang: 'en',\n },\n },\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {\n transpile: [\"vee-validate/dist/rules\"],\n vendor: [\"vue-tables-2\"]\n },\n}\n```\n\n```text\nnvm\n```\n\n```text\nnvm install 16.0.0\n```\n\n```text\nnvm uninstall 18.12.1\n```\n\n```text\nnpm install node@16.0.0 --save-dev\n```\n\n```text\n\"scripts\": {\n \"dev\": \"npm run serve\",\n \"serve\": \"vue-cli-service serve\",\n \"build\": \"vue-cli-service build\",\n \"lint\": \"vue-cli-service lint\"\n},\n```\n\n```text\nnpm run dev\n```\n\n```text\nexport NODE_OPTIONS=--openssl-legacy-provider\n```\n\n```json\n\"scripts\": {\n \"ng\": \"set NODE_OPTIONS=--openssl-legacy-provider && ng\",\n \"start\": \"set NODE_OPTIONS=--openssl-legacy-provider && ng serve\",\n \"build\": \"ng build\",\n \"test\": \"ng test\",\n \"lint\": \"ng lint\",\n \"e2e\": \"ng e2e\"\n},\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm start\n```\n\n```text\nNODE_OPTIONS=--openssl-legacy-provider\n```\n\n```text\n\"dev\": \"NODE_OPTIONS=--openssl-legacy-provider next -p 4000\"\n```\n\n```text\necho $NODE_OPTIONS\n```\n\n```text\nexport NODE_OPTIONS=--openssl-legacy-provider\n```\n\n```text\n/etc/ssl/openssl.cnf\n```\n\n========================================\n\nComments:\n- Did you tried to delete your `node_modules`, reinstall with yarn/pnpm to check some errors? Also, do you have the `package.json` before and after? Mind sharing the `nuxt.config.js` file too?\n- Yes i did that, yes sure, i will my nuxt config file\n- What about the rest?\n- Does this answer your question? Error message \"error:0308010C:digital envelope routines::unsupported\"\n- NO deleting the node_modules doesnt fix the problem, @kissu what rest? are you refering to, thats my entire nuxt.config file.\n- Worked for me. On windows you just uninstall node.js 18 as per usual, then download/install 16.\n- Consider the warnings in this - stackoverflow.com/a/73027407/1459653 - answer before doing this.\n- that's not the fix. You need to upgrade the outdated libs that use an outdated SSL instead not the other way around. In my case it was an older version of webpack. @MarkGavagan comment has the link that describes the correct solution.\n- Downgrade Node to 17.\n- You don't necessarily need to uninstall v18, you can just install v16 `nvm install 16` and then use the command `nvm use 16`. Using `16.0.0` would prevent you from upgrading to the latest minor and hotfix versions\n- This works for me and is a great solution, much easier than downgrading your global node version or messing around with NVM.\n- yes, this is cleaner approach to solve the problem.\n- Its woring for me and Thanks alot.\n- Nvm install 16 is worked for me!\n- this solution works best for me using node v18 lts in ubuntu 22.04\n- Just to confirm, this fix also work on macOS 13 Ventura with Node v20.3.1\n- faced same issue in Ionic Angular based project. This fixed issue for MacOS Ventura for me also\n- Can I ask where to add this env argument please....thanks\n- @Paul updated the reponse which an example\n- A more bash-compatible way to write the npm command is using `\"ng\": \"NODE_OPTIONS=--openssl-legacy-provider && ng\"` and `\"start\": \"NODE_OPTIONS=--openssl-legacy-provider && ng serve\"`\n- Shouldn't 'next' in the command 'NODE_OPTIONS=--openssl-legacy-provider next -p 4000' be 'nuxt' instead?","metadata":{"transformedAt":"2026-08-18T18:33:07.828Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":312,"estimatedTokens":2262}}15{"id":"stack-57944894","source":"stackoverflow","questionId":57944894,"title":"How to format Vuetify data table date column?","tags":["javascript","html","vue.js","nuxt.js","vuetify.js"],"text":"Title: How to format Vuetify data table date column?\nTags: javascript, html, vue.js, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nI have a simple data table using *Vuetify* data table. One of the column is a `createdOn` (date time), I want to format it. How can I do it ?\n\nThis is what i get now:\n\n```\n\n \n \n \n \n\n headers: [\n { text: \"Time\", value: \"createdOn\", dataType: \"Date\" },\n { text: \"Event Source\", value: \"eventSourceName\" },\n { text: \"Event Details\", value: \"eventDetails\" },\n { text: \"User\", value: \"user\" }\n ],\n items: [],\n\n```\n\n========================================\n\nTop Answer:\nI found out a way to format cell values using dynamic slot names and a function in the header object:\n\nIn the `` I did:\n\n```\n header.hasOwnProperty('formatter'))\" v-slot:[`item.${header.value}`]=\"{ header, value }\">\n {{ header.formatter(value) }}\n\n```\n\nand in the vue `data` property I did:\n\n```\nheaders: [\n // ...\n { text: 'Value for example', value: '10000', formatter: formatCurrency },\n // ...\n]\n```\n\nAnd finally in the `methods` prop I did:\n\n```\nformatCurrency (value) {\n return \"$ \" + (value / 100).toFixed(2);\n}\n```\n\nHere's a sandbox to see it in action:\nhttps://codesandbox.io/s/vuetify-datatable-value-formatter-jdtxj?file=/src/App.vue\n\n### EDIT:\n\nIn this specific case you could use `momentjs` or javascript's `Date()`. I've added a momentjs example to the codesandbox.\n\n========================================\n\nCode:\n```text\n<template>\n <v-layout>\n <v-data-table :headers=\"headers\" :items=\"logs\">\n </v-data-table>\n <v-layout>\n</template>\n<script>\n headers: [\n { text: \"Time\", value: \"createdOn\", dataType: \"Date\" },\n { text: \"Event Source\", value: \"eventSourceName\" },\n { text: \"Event Details\", value: \"eventDetails\" },\n { text: \"User\", value: \"user\" }\n ],\n items: [],\n</script>\n```\n\n```text\ncreatedOn\n```\n\n```html\n<v-data-table :headers=\"headers\" :items=\"logs\">\n <template v-slot:item.createdOn=\"{ item }\">\n <span>{{ new Date(item.createdOn).toLocaleString() }}</span>\n </template>\n</v-data-table>\n```\n\n```text\ncustom row cell\n```\n\n```html\n<template v-for=\"header in headers.filter((header) => header.hasOwnProperty('formatter'))\" v-slot:[`item.${header.value}`]=\"{ header, value }\">\n {{ header.formatter(value) }}\n</template>\n```\n\n```js\nheaders: [\n // ...\n { text: 'Value for example', value: '10000', formatter: formatCurrency },\n // ...\n]\n```\n\n```js\nformatCurrency (value) {\n return \"$ \" + (value / 100).toFixed(2);\n}\n```\n\n```text\n<v-data-table>\n```\n\n```text\ndata\n```\n\n```text\nmethods\n```\n\n```text\nmomentjs\n```\n\n```text\nDate()\n```\n\n```text\n<v-data-table :headers=\"headers\" :items=\"logs\">\n <template v-slot:item.createdOn=\"{ item }\">\n <span>{{ item.createdOn | myGlobalDateFilter }}</span>\n </template>\n</v-data-table>\n```\n\n```text\n<template v-for=\"slot in slots\" v-slot:[`item.${slot.slotName}`]=\"{ item }\">\n <slot :name=\"slot.slotName\" :variable=\"item\"></slot>\n</template>\n\nexport default {\nprops:\nslots:{\n type:Array,\n default:null\n},\n```\n\n```text\n<Datatable\n :headers=\"headers\"\n :items=\"stokhareketleri\"\n :title=\"title\"\n :slots=\"slots\">\n<template v-slot:column_name=\"{ variable }\">\n <v-chip\n color=\"green\"\n dark\n >\n {{variable.column_name}}\n </v-chip>\n</template>\n </Datatable>\n\n\ndata () {\n return {\n slots:[{ \n Id: 1, slotName: 'column_name'\n }],\n```\n\n```js\n<v-data-table :headers=\"headers\" :items=\"logs\">\n <template v-slot:body=\"{ items }\">\n <tbody>\n <tr v-for=\"item in items\" :key=\"logs.id\">\n <td> {{ new Date(item.createdOn).toLocaleString() }} </td>\n ...\n </tr>\n </tbody>\n </template>\n</v-data-table>\n```\n\n```text\nbody\n```\n\n```text\nv-data-table\n```\n\n```html\n<template>\n <v-data-table :headers=\"headers\" :items=\"logs\">\n <template #item.createdOn=\"{ item }\">\n {{ date.format(item.createdOn, 'fullDateTime24h') }}\n </template>\n </v-data-table>\n</template>\n\n<script setup>\nimport { useDate } from 'vuetify';\nconst date = useDate();\n</script>\n```\n\n```text\n3.4.0+\n```\n\n========================================\n\nComments:\n- how do you want to format it?\n- hi @Boussadjra Brahim I get \"2019-09-14T17:03:24.3949548\" format now. I want to make it \"2019-09-14 3:24 AM\". Is there a way to do it like pipes in angular?\n- You may have a typo, I needed to use singular item.createdOn as the v-slot attribute, plural items.createdOn did not work.\n- For me there is an issue: If I pass '2020-07-01' it gets rendered as \"1.7.2020, 02:00:00\", which is most often not what you want. Javascript takes the given value as UTC and displays it with the offset of the user.\n- @MathiasF i think the problem is with your locale, i answered the question with the given input `2019-09-14T17...` i recommend to ask a new question with more details\n- This answer could be updated to avoid the \"'v-slot' directive doesn't support any modifier\" error by changing `` to ``. See 'v-slot' directive doesn't support any modifier.\n- thank you for your comment, it could be updated to what?\n- That called a dynamic slot, for example you could do `v-slot:[someprop]=\"{}\"` knowing that `someprop` is a property defined in script or template that represent a string of a valid slot\n- for some reason you want a dynamic timestamp based on a condition returned from a computed property `myTimestamp(){return this.updated?'updatedOn':'createdOn'}` then in template you could do `v-slot:[myTimestamp]=\"{item}\"`\n- Yes - great work @SneakyLenny! Saved me like 2 hrs. Got this to work for a more generic \"customize every column\" approach: ` {{ formatCell(value) }} `\n- can use still sort/filter on date columns irrespective of chosen format after that? i.e. does the table use the underlying Dates or the newly formatted strings for its internal sorting/filtering algorithm after that?\n- @niko Sorting is based on the data given, otherwise you could have formatted the data beforehand. Example: if the data would be 4 - 2 - 1 - 3 and a formatter would add random letters to the format the display is sorted as y1 - x2 - u3 - a4. If that makes sense.\n- This is also useful to create based on the data dynamically, say if you have \"dynamic headers\", then you can inspect the headers and create templates. Very useful, thanks!","metadata":{"transformedAt":"2026-08-18T18:33:07.829Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":242,"estimatedTokens":1572}}16{"id":"stack-66325582","source":"stackoverflow","questionId":66325582,"title":"Nuxt.js Cannot find module '@babel/preset-env/lib/utils'","tags":["vue.js","babeljs","nuxt.js"],"text":"Title: Nuxt.js Cannot find module '@babel/preset-env/lib/utils'\nTags: vue.js, babeljs, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm getting this error when trying to run `yarn run dev --port=4000`\n\nHere is the error:\n\n```\nModule build failed (from ./node_modules/babel-loader/lib/index.js): friendly-errors 16:52:26\nError: /Users/jacob/code/artistrepublik/elite-reviews/.nuxt/client.js: Cannot find module '@babel/preset-env/lib/utils'\nRequire stack:\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/@nuxt/babel-preset-app/src/polyfills-plugin.js\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/@nuxt/babel-preset-app/src/index.js\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/core/lib/config/files/module-types.js\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/core/lib/config/files/configuration.js\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/core/lib/config/files/index.js\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/core/lib/index.js\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/nuxt-route-meta/dist/index.js\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/@nuxt/core/dist/core.js\n at Function.Module._resolveFilename (internal/modules/cjs/loader.js:965:15)\n at Function.Module._load (internal/modules/cjs/loader.js:841:27)\n at Module.require (internal/modules/cjs/loader.js:1025:19)\n at n (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/jiti/dist/v8cache.js:2:2364)\n at PluginPass.Program (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@nuxt/babel-preset-app/src/polyfills-plugin.js:15:34)\n at newFn (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/visitors.js:175:21)\n at NodePath._call (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/path/context.js:55:20)\n at NodePath.call (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/path/context.js:42:17)\n at NodePath.visit (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/path/context.js:92:31)\n at TraversalContext.visitQueue (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/context.js:116:16)\n at TraversalContext.visitSingle (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/context.js:85:19)\n at TraversalContext.visit (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/context.js:144:19)\n at Function.traverse.node (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/index.js:82:17)\n at traverse (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/index.js:62:12)\n at transformFile (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/core/lib/transformation/index.js:107:29)\n at transformFile.next ()\n friendly-errors 16:52:26\n @ multi ./node_modules/eventsource-polyfill/dist/browserify-eventsource.js (webpack)-hot-middleware/client.js?reload=true&timeout=30000&ansiColors=&overlayStyles=&path=%2F__webpack_hmr%2Fclient&name=client ./.nuxt/client.js\n```\n\nHere is my package.json:\n\n```\n{\n \"name\": \"my-project\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt -r dotenv/config\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"test\": \"jest\"\n },\n \"dependencies\": {\n \"@nuxtjs/axios\": \"^5.12.5\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"@nuxtjs/pwa\": \"^3.3.4\",\n \"@paypal/paypal-js\": \"^1.0.5\",\n \"@vue/babel-preset-app\": \"^4.5.10\",\n \"core-js\": \"^3.8.3\",\n \"es6-promise\": \"^4.1.1\",\n \"lodash\": \"^4.17.20\",\n \"moment\": \"latest\",\n \"moment-timezone\": \"^0.5.32\",\n \"noty\": \"^3.2.0-beta\",\n \"nuxt\": \"^2.14.12\",\n \"nuxt-i18n\": \"^6.18.0\",\n \"nuxt-route-meta\": \"^1.0.3\",\n \"nuxt\": \"^2.14.6\",\n \"nuxt-i18n\": \"^6.15.1\",\n \"nuxt-route-meta\": \"^1.0.1\",\n \"nuxt-stripe-module\": \"^3.0.1\",\n \"object-to-formdata\": \"^4.1.0\",\n \"pluralize\": \"latest\",\n \"vee-validate\": \"^3.4.5\",\n \"sib-api-v3-sdk\": \"github:sendinblue/APIv3-nodejs-library\",\n \"vue-carousel\": \"^0.18.0\",\n \"vue-chartist\": \"^2.2.1\",\n \"vue-material-design-icons\": \"^4.11.0\",\n \"vuejs-noty\": \"^0.1.3\",\n \"vue-plyr\": \"^7.0.0\",\n \"vuetify-media-player\": \"^0.8.1\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.12.10\",\n \"@mdi/font\": \"^5.9.55\",\n \"@nuxt/types\": \"^2.14.12\",\n \"@nuxtjs/style-resources\": \"^1.0.0\",\n \"@nuxtjs/vuetify\": \"^1.11.3\",\n \"@vue/test-utils\": \"^1.1.2\",\n \"babel-jest\": \"^26.6.3\",\n \"babel-plugin-component\": \"^1.1.0\",\n \"cross-env\": \"^5.2.0\",\n \"dotenv\": \"^8.2.0\",\n \"jest\": \"^26.6.3\",\n \"material-design-icons-iconfont\": \"^6.1.0\",\n \"node-sass\": \"^4.14.1\",\n \"nodemon\": \"^1.18.9\",\n \"sass-loader\": \"^7.3.1\",\n \"vue-jest\": \"^3.0.4\"\n }\n}\n```\n\nAnd here is my .babelrc:\n\n```\n{\n \"env\": {\n \"test\": {\n \"presets\": [\n [\n \"@babel/preset-env\",\n {\n \"targets\": {\n \"node\": \"current\"\n }\n }\n ]\n ]\n }\n }\n}\n```\n\nI have tried deleting the node_modules folder along with removing the yarn.lock file with no luck. The babel version looks correct. This error only popped up after me playing around with some code (not the package.json) - which is an unrelated error.\n\nAny help would be appreciated!\n\n========================================\n\nTop Answer:\nThis issue drove me crazy for a few hours too.\n\nThe solution is to add to `nuxt.config.js` into `build` section:\n\n```\n/*\n ** Build configuration\n */\n build: {\n babel: {\n presets(env, [ preset, options ]) {\n return [\n [ \"@babel/preset-env\", options ]\n ]\n }\n },\n```\n\nMake sure you have that thing installed:\n`npm install --save-dev @babel/preset-env`\n\nor in your case with yarn\n\n**Updated:**\n\nThen I encountered another error\n\n*regeneratorRuntime is not defined*\n\nHere is working part from my `config.nuxt.js`\n\n```\nbuild: {\n babel: {\n presets({isServer}) {\n const targets = isServer ? { node: 'current' } : { ie: 11 }\n return [\n [ require.resolve(\"@babel/preset-env\"), { targets } ]\n ]\n },\n plugins: [\n \"@babel/syntax-dynamic-import\",\n \"@babel/transform-runtime\",\n \"@babel/transform-async-to-generator\"\n ]\n },\n```\n\n========================================\n\nCode:\n```text\nModule build failed (from ./node_modules/babel-loader/lib/index.js): friendly-errors 16:52:26\nError: /Users/jacob/code/artistrepublik/elite-reviews/.nuxt/client.js: Cannot find module '@babel/preset-env/lib/utils'\nRequire stack:\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/@nuxt/babel-preset-app/src/polyfills-plugin.js\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/@nuxt/babel-preset-app/src/index.js\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/core/lib/config/files/module-types.js\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/core/lib/config/files/configuration.js\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/core/lib/config/files/index.js\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/core/lib/index.js\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/nuxt-route-meta/dist/index.js\n- /Users/jacob/code/artistrepublik/elite-reviews/node_modules/@nuxt/core/dist/core.js\n at Function.Module._resolveFilename (internal/modules/cjs/loader.js:965:15)\n at Function.Module._load (internal/modules/cjs/loader.js:841:27)\n at Module.require (internal/modules/cjs/loader.js:1025:19)\n at n (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/jiti/dist/v8cache.js:2:2364)\n at PluginPass.Program (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@nuxt/babel-preset-app/src/polyfills-plugin.js:15:34)\n at newFn (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/visitors.js:175:21)\n at NodePath._call (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/path/context.js:55:20)\n at NodePath.call (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/path/context.js:42:17)\n at NodePath.visit (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/path/context.js:92:31)\n at TraversalContext.visitQueue (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/context.js:116:16)\n at TraversalContext.visitSingle (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/context.js:85:19)\n at TraversalContext.visit (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/context.js:144:19)\n at Function.traverse.node (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/index.js:82:17)\n at traverse (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/traverse/lib/index.js:62:12)\n at transformFile (/Users/jacob/code/artistrepublik/elite-reviews/node_modules/@babel/core/lib/transformation/index.js:107:29)\n at transformFile.next (<anonymous>)\n friendly-errors 16:52:26\n @ multi ./node_modules/eventsource-polyfill/dist/browserify-eventsource.js (webpack)-hot-middleware/client.js?reload=true&timeout=30000&ansiColors=&overlayStyles=&path=%2F__webpack_hmr%2Fclient&name=client ./.nuxt/client.js\n```\n\n```text\n{\n \"name\": \"my-project\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt -r dotenv/config\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"test\": \"jest\"\n },\n \"dependencies\": {\n \"@nuxtjs/axios\": \"^5.12.5\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"@nuxtjs/pwa\": \"^3.3.4\",\n \"@paypal/paypal-js\": \"^1.0.5\",\n \"@vue/babel-preset-app\": \"^4.5.10\",\n \"core-js\": \"^3.8.3\",\n \"es6-promise\": \"^4.1.1\",\n \"lodash\": \"^4.17.20\",\n \"moment\": \"latest\",\n \"moment-timezone\": \"^0.5.32\",\n \"noty\": \"^3.2.0-beta\",\n \"nuxt\": \"^2.14.12\",\n \"nuxt-i18n\": \"^6.18.0\",\n \"nuxt-route-meta\": \"^1.0.3\",\n \"nuxt\": \"^2.14.6\",\n \"nuxt-i18n\": \"^6.15.1\",\n \"nuxt-route-meta\": \"^1.0.1\",\n \"nuxt-stripe-module\": \"^3.0.1\",\n \"object-to-formdata\": \"^4.1.0\",\n \"pluralize\": \"latest\",\n \"vee-validate\": \"^3.4.5\",\n \"sib-api-v3-sdk\": \"github:sendinblue/APIv3-nodejs-library\",\n \"vue-carousel\": \"^0.18.0\",\n \"vue-chartist\": \"^2.2.1\",\n \"vue-material-design-icons\": \"^4.11.0\",\n \"vuejs-noty\": \"^0.1.3\",\n \"vue-plyr\": \"^7.0.0\",\n \"vuetify-media-player\": \"^0.8.1\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.12.10\",\n \"@mdi/font\": \"^5.9.55\",\n \"@nuxt/types\": \"^2.14.12\",\n \"@nuxtjs/style-resources\": \"^1.0.0\",\n \"@nuxtjs/vuetify\": \"^1.11.3\",\n \"@vue/test-utils\": \"^1.1.2\",\n \"babel-jest\": \"^26.6.3\",\n \"babel-plugin-component\": \"^1.1.0\",\n \"cross-env\": \"^5.2.0\",\n \"dotenv\": \"^8.2.0\",\n \"jest\": \"^26.6.3\",\n \"material-design-icons-iconfont\": \"^6.1.0\",\n \"node-sass\": \"^4.14.1\",\n \"nodemon\": \"^1.18.9\",\n \"sass-loader\": \"^7.3.1\",\n \"vue-jest\": \"^3.0.4\"\n }\n}\n```\n\n```text\n{\n \"env\": {\n \"test\": {\n \"presets\": [\n [\n \"@babel/preset-env\",\n {\n \"targets\": {\n \"node\": \"current\"\n }\n }\n ]\n ]\n }\n }\n}\n```\n\n```text\nyarn run dev --port=4000\n```\n\n```text\n/*\n ** Build configuration\n */\n build: {\n babel: {\n presets(env, [ preset, options ]) {\n return [\n [ \"@babel/preset-env\", options ]\n ]\n }\n },\n```\n\n```text\nbuild: {\n babel: {\n presets({isServer}) {\n const targets = isServer ? { node: 'current' } : { ie: 11 }\n return [\n [ require.resolve(\"@babel/preset-env\"), { targets } ]\n ]\n },\n plugins: [\n \"@babel/syntax-dynamic-import\",\n \"@babel/transform-runtime\",\n \"@babel/transform-async-to-generator\"\n ]\n },\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nbuild\n```\n\n```text\nnpm install --save-dev @babel/preset-env\n```\n\n```text\nconfig.nuxt.js\n```\n\n```text\nnpm i @babel/preset-env@7.12.17 -S\n```\n\n```text\nnpm uninstall @babel/preset-env\nnpm install @babel/preset-env@7.12.17\n```\n\n```text\n// package.json\n\"devDependencies\": {\n + \"@babel/preset-env\": \"7.12.17\",\n \"cross-env\": \"^5.2.0\",\n \"css-loader\": \"^3.2.0\",\n \"node-sass\": \"^4.14.1\",\n\n\n \"sass-loader\": \"^8.0.2\",\n \"style-loader\": \"^1.0.0\"\n },\n\n// package-lock.json\n \"@babel/preset-env\": {\n +\"version\": \"7.12.17\",\n ...,\n \"@nuxt/babel-preset-app\": {\n \"requires\": {\n \"@babel/preset-env\": \"7.12.17\",\n ...\n }\n }\n }\n```\n\n```text\nError: /var/app/current/.nuxt/client.js: Cannot find module '@babel/preset-env/lib/utils'\n```\n\n========================================\n\nComments:\n- does not work I did the same thing you metioned\n- Like Raymond Chong said, just downgrade @babel/preset-env module to v7.12.17, then it works. `npm i @babel/preset-env@7.12.17`\n- please add your `config.nuxt.js` the `build` part to the question\n- @EricChang mine is `\"@babel/preset-env\": \"^7.13.0\",` works fine with config above\n- @Shirker because nuxt team releases emergency fix hours ago, so this question no longer exits.\n- extra babel option in nuxt.config.js > build did it for me, ty\n- Cannot assign to read only property 'exports' of object '#', error I'm getting\n- Use npm-shrinkwrap or Yarn Selective dependency resolutions if `@babel/preset-env` is a dependency of a dependency\n- This was fixed in Nuxt 2.15.2 as mentioned in nuxtjs.org/docs/release-notes#v2.15.2. So there shouldn't be a need to use the older version of @babel/preset-env given you can upgrade Nuxt.\n- Unless you can't upgrade to the newer version of Nuxt\n- an explanation is often helpful\n- working solution\n- I needed to delete the package-lock.json and re-run a npm update in order to work with the updated version.","metadata":{"transformedAt":"2026-08-18T18:33:07.829Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":405,"estimatedTokens":3500}}17{"id":"stack-64612031","source":"stackoverflow","questionId":64612031,"title":"setup Google Analytics 4 in nuxt.js","tags":["google-analytics","nuxt.js","google-analytics-4"],"text":"Title: setup Google Analytics 4 in nuxt.js\nTags: google-analytics, nuxt.js, google-analytics-4\nSource: Stack Overflow\n\nQuestion:\nI'm having issues setting up a new Google Analytics 4 (GA4) account with Nuxt. Everything seems configured ok based on tutorials, however my traffic doesn't show up in GA (dev & production)\n\nIn nuxt.config.js I have the following\n\n```\nbuildModules: [\n '@nuxtjs/tailwindcss','@nuxtjs/google-analytics'\n ],\n googleAnalytics: {\n id: 'G-HWW3B1GM6W'\n },\n```\n\nThe google id is a GA4 Data Stream id with my production website. I tried 2 different streams, with www and without, but the traffic doesn't show up in GA4.\n\n========================================\n\nTop Answer:\nI had the same problem, and I solved it by just using the vanilla JavaScript:\n\n*/static/js/ga.js*\n\n```\nwindow.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\ngtag('js', new Date());\n\ngtag('config', 'G-XXXXXXXXXX');\n```\n\n*/nuxt.config.js*\n\n```\nexport default {\n head: {\n script: [\n {\n src: \"https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX\",\n async: true,\n },\n {\n src: \"js/ga.js\",\n }\n ]\n },\n}\n```\n\n========================================\n\nCode:\n```text\nbuildModules: [\n '@nuxtjs/tailwindcss','@nuxtjs/google-analytics'\n ],\n googleAnalytics: {\n id: 'G-HWW3B1GM6W'\n },\n```\n\n```text\nimport Vue from 'vue'\nimport VueGtag from 'vue-gtag'\n\nVue.use(VueGtag, {\n config: { id: 'G-XXXXXXXXXX' }\n})\n```\n\n```text\nplugins: ['@/plugins/gtag']\n```\n\n```text\nbuildModules: [\n '@nuxtjs/tailwindcss','@nuxtjs/google-analytics'\n ],\n googleAnalytics: {\n id: 'UA-XXXXXXXX-X'\n },\n```\n\n```text\nUA-XXXXXXXXX-X\n```\n\n```text\nG-HWW3B1GM6W\n```\n\n```text\nShow advanced options\n```\n\n```text\nimport Vue from 'vue'\nimport VueGtag from 'vue-gtag'\n\nVue.use(VueGtag, {\n config: { id: 'G-XXXXXXXXXX' }\n})\n```\n\n```text\nplugins: ['@/plugins/gtag']\n```\n\n```text\nvue-gtag\n```\n\n```text\npublicRuntimeConfig: {\n googleAnalytics: {\n id: process.env.GOOGLE_ANALYTICS_ID,\n debug: {\n sendHitTask: true\n }\n }\n },\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm start\n```\n\n```text\ndebug: { sendHitTask: true }\n```\n\n```text\nwindow.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\ngtag('js', new Date());\n\ngtag('config', 'G-XXXXXXXXXX');\n```\n\n```text\nexport default {\n head: {\n script: [\n {\n src: \"https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX\",\n async: true,\n },\n {\n src: \"js/ga.js\",\n }\n ]\n },\n}\n```\n\n```text\nimport VueGtag, { trackRouter } from 'vue-gtag-next'\nexport default defineNuxtPlugin((nuxtApp) => {\n nuxtApp.vueApp.use(VueGtag, {\n property: {\n id: 'GA_MEASUREMENT_ID'\n }\n })\n trackRouter(useRouter())\n})\n```\n\n```text\nnpm add --dev vue-gtag-next\n```\n\n```text\nplugins/vue-gtag.client.js\n```\n\n```text\nisEnabled\n```\n\n```text\nexport default {\n ...\n head: {\n ...\n script: [\n {\n vmid: 'g-tag',\n src: 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXX',\n async: true,\n callback: () => {\n window.dataLayer = window.dataLayer || []\n function gtag() {\n window.dataLayer.push(arguments)\n }\n gtag('js', new Date())\n\n gtag('config', 'G-XXXXXXXX')\n },\n },\n ],\n ...\n },\n ...\n}\n```\n\n```text\nexport default defineNuxtConfig({\n modules: ['nuxt-gtag'],\n})\n```\n\n```text\nexport default defineNuxtConfig({\n modules: ['nuxt-gtag'],\n gtag: {\n enabled: process.env.NODE_ENV === 'production',\n id: process.env.GTAG_ID_MAINDOMAIN || 'G-XXXXXX'\n config: {\n anonymize_ip: true\n }\n },\n})\n```\n\n========================================\n\nComments:\n- @nuxtjs/google-analytics only accepts Universal Analytics IDs which is officially being done away with by Google and in addition the author of @nuxtjs/google-analytics no longer supports the module and recommends switching to vue-gtag. The issue with that is that vue-gtag requires Vue 3 which is not currently available in a stable version of Nuxt.\n- Hi! Do you know if installing this way will allow route tracking? Thanks\n- vue-gtag has a hard requirement of Vue3 which is not available in a stable version of Nuxtjs (yet). If you are using Nuxt v2 this approach won't work.\n- if you're on Nuxt v2, you can install vue-gtag v1 and it works just fine... `npm install vue-gtag@1 --save`\n- As this is mostly only needed on the client (in production) you can check `if (process.env.NODE_ENV === \"production\")` in your Plugin & and configure the `mode` plugin option in your array of Plugins in `nuxt.config.js` as `{ src: \"@/plugins/g-analytics.js\", mode: \"client\" }`\n- does this work on nuxt 2 SSR?\n- Thank you! Don't forget to disable the tag on localhost\n- ^ for prod only pass { enable: process.env.NODE_ENV === 'production' }\n- @ihorbond - Isn't it `enabled`, rather than `enable`? matteo-gabriele.gitbook.io/vue-gtag/plugin-options\n- does it work on nuxt 2 in SSR mode?\n- A good solution if you don't want to use and manage yet another third-party plugin. Worked for my site.\n- This solution works best considering all these vue ga packages keep deprecating\n- the code in /static/js/ga.js can just be added as callback: option of the script, no need for a separate file\n- For \"vue-meta\": \"^2.4.0\" I had to add the `hid` property alongside the `callback` option. If not the later was not getting called.\n- @ihor.eth Could you post code as a callback option of script?\n- @sandalwoodsh here vue-meta.nuxtjs.org/api/#callback\n- Does anyone know a way to include the code of ga.js inline, without a separate file?\n- This is the only solution that worked for me, when using the regular `vue-gtag` make sure to use `config` instead of `property`\n- how will you reference this in your vue component if you want to enable it only after user has enabled tracking cookies?\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:07.829Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":256,"estimatedTokens":1543}}18{"id":"stack-74003458","source":"stackoverflow","questionId":74003458,"title":"Cannot find module 'pinia/dist/pinia.mjs' when using run dev","tags":["javascript","vue.js","nuxt.js","nuxt3.js","pinia"],"text":"Title: Cannot find module 'pinia/dist/pinia.mjs' when using run dev\nTags: javascript, vue.js, nuxt.js, nuxt3.js, pinia\nSource: Stack Overflow\n\nQuestion:\nI setup Pinia on top of fresh Nuxt3 app and start dev server, with exactly these commands in order:\n\n```\nnpx nuxi init nuxt-app\ncd nuxt-app\nnpm install\nnpm install @pinia/nuxt\nnpm run dev\n```\n\nDev server runs without any problem. Then, i put this line of code into \"nuxt.config.ts\";\n\n```\nexport default defineNuxtConfig({\n modules: [\"@pinia/nuxt\"],\n});\n```\n\nAnd, when I again try to connect to dev server, it gives me this error message in terminal:\n\n```\nERROR Cannot start nuxt: Cannot find module 'pinia/dist/pinia.mjs' 12:03:55\nRequire stack:\n- C:\\Users\\user\\Documents\\github2\\nuxt-app\\index.js\n```\n\n========================================\n\nTop Answer:\nAs I know this is a bug that will be fixed someday. Until then you can put\n\n```\nalias: {\n pinia: \"/node_modules/@pinia/nuxt/node_modules/pinia/dist/pinia.mjs\"\n},\n```\n\nin your `nuxt.config.ts` and it will work.\n\nFound from this VueSchool lesson on Pinia.\n\n========================================\n\nCode:\n```text\nnpx nuxi init nuxt-app\ncd nuxt-app\nnpm install\nnpm install @pinia/nuxt\nnpm run dev\n```\n\n```js\nexport default defineNuxtConfig({\n modules: [\"@pinia/nuxt\"],\n});\n```\n\n```text\nERROR Cannot start nuxt: Cannot find module 'pinia/dist/pinia.mjs' 12:03:55\nRequire stack:\n- C:\\Users\\user\\Documents\\github2\\nuxt-app\\index.js\n```\n\n```bash\nnpm i pinia -f\n```\n\n```js\nalias: {\n pinia: \"/node_modules/@pinia/nuxt/node_modules/pinia/dist/pinia.mjs\"\n},\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nyarn add @pinia/nuxt\n```\n\n```text\n@pinia/nuxt\n```\n\n```text\nnode_modules\n```\n\n```text\npackage-lock.json\n```\n\n```text\nmodules: ['a', 'b', 'c', '@pinia/nuxt'],\n```\n\n```text\nnpm install\n```\n\n```text\npinia\n```\n\n```text\n@pinia/nuxt\n```\n\n```text\nnpm i pinia\n```\n\n```text\n\"overrides\": {\n \"vue\": \"latest\"\n}\n```\n\n```text\npackage.json\n```\n\n```js\n\"devDependencies\": {\n \"@nuxt/devtools\": \"latest\",\n \"nuxt\": \"^3.9.0\",\n \"nuxt-primevue\": \"^0.2.2\",\n \"vue\": \"^3.4.14\",\n \"vue-router\": \"^4.2.5\"\n },\n \"dependencies\": {\n \"primeflex\": \"^3.3.1\",\n \"primeicons\": \"^6.0.1\",\n \"primevue\": \"^3.46.0\"\n }\n```\n\n```js\n// Nuxt 3\nexport default defineNuxtConfig({\n modules: ['@pinia/nuxt'],\n})\n```\n\n```text\nERROR Cannot find module 'pinia/dist/pinia.mjs'\n```\n\n```text\nnpm install pinia @pinia/nuxt\n```\n\n```text\nalias: {\n pinia: \"pinia/dist/pinia.mjs\"\n}\n```\n\n========================================\n\nComments:\n- Can you try that one? github.com/vuejs/pinia/issues/1542#issuecomment-1238820465\n- @kissu thank you, this works. I've seen this one but it felt not the best way to init Pinia, because Pinia's nuxt3 setup page doesn't mention this. But it turns out there's no any other way actually. This is a big mess to take energy of a junior dev so i'll give the info i took from every doc-forum in the bottom message\n- What do you mean by \"init pinia\"? I can recommend giving a try to yarn too, works better for me.\n- @kissu A good finding. As much as I'd like to stick to default pm, I always end up using yarn, just because it works where npm fails\n- @EstusFlask yeah, for me it's usually PNPM > yarn > npm (PNPM being the best). It works nicely, better output and you don't have to mess up with peerDeps or related stuff just getting into your way.\n- @kissu I wasn't able to handle this problem with yarn too. Nvm thank you so much. I wrote everything about this unnecessary challenge that i've gained experience throughout the week\n- this works. forcing it can lead to further conflicts or package problems, but looks like it's the only working way for now.\n- What about production server?\n- If you run `npm i pinia -f` locally, I'm pretty sure some of your files may change, like the `package-lock.json` or alike. In production, your `node_modules` are always wiped, if it's not the case you should probably run a cache reset of some sort (depends where you do host your app). @kanuos\n- How can this still be necessary today? Is this something the pinia project could work around?\n- @katerlouis there is probably a Github issue open for that one.\n- Got an official source for that bug?\n- No. I found it in video lesson here: vueschool.io/lessons/global-state-management-with-pinia and it works for me.\n- Oh, I don't have a paid subscription but it's a legit link and a nice source indeed!\n- you may have to surround key pinia with quotes alias: { 'pinia': \"/node_modules/@pinia/nuxt/node_modules/pinia/dist/pinia.mjs‌​\" },\n- still not fixed in feb 2023 :(\n- @katerlouis at least the fix is simple.\n- this is still the fix in 2024, thanks\n- as of Sept 2024, this is still the fix\n- @CraftedGaming you can probably report it to the project with a PR or some kind of feedback. It might be more useful than complaining here and gonna push things forward.\n- This was fixed as of version 0.6.0: github.com/vuejs/pinia/commit/…\n- This is the correct answer! I tried: 1. npm install pinia -f - No joy 2 Aliasing pinia - still no joy 3. yarn (a full refresh before trying yarn) - same error 4. this answer - it works! I wish I had tried this first\n- Pretty much this answer: stackoverflow.com/a/74801367/8816585\n- This was fixed as of version 0.6.0: github.com/vuejs/pinia/commit/…","metadata":{"transformedAt":"2026-08-18T18:33:07.829Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":192,"estimatedTokens":1343}}19{"id":"stack-70180990","source":"stackoverflow","questionId":70180990,"title":"Getting : npm WARN using --force Recommended protections disabled","tags":["node.js","vue.js","npm","nuxt.js","package.json"],"text":"Title: Getting : npm WARN using --force Recommended protections disabled\nTags: node.js, vue.js, npm, nuxt.js, package.json\nSource: Stack Overflow\n\nQuestion:\nI have an old Nuxt.js package that was developed in Node 12 and I want to use it now with Node 16 (the latest stable) but when I try to install my packages by `npm install` I'm getting the versions difference errors.\n\nBut I know the packages are up to date. So, I'm trying to force clear my npm cache by `sudo npm cache clean -f` but I'm getting this error:\n\nnpm WARN using --force Recommended protections disabled.\n\nThe environment is `ubuntu 20.04` and this is my `package.json` file:\n\n```\n{\n \"name\": \"frontend\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"@nuxtjs/auth\": \"^4.9.1\",\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"@nuxtjs/google-adsense\": \"^1.4.0\",\n \"@nuxtjs/gtm\": \"^2.4.0\",\n \"@nuxtjs/router\": \"^1.6.1\",\n \"better-vue-input-tag\": \"^1.1.0\",\n \"bootstrap\": \"^5.1.3\",\n \"bootstrap-vue\": \"^2.21.2\",\n \"core-js\": \"^3.19.2\",\n \"eslint\": \"^8.3.0\",\n \"jquery\": \"^3.6.0\",\n \"laravel-vue-pagination\": \"^2.3.1\",\n \"node-sass\": \"^6.0.1\",\n \"nuxt\": \"^2.15.8\",\n \"popper.js\": \"^1.16.1\",\n \"sass-loader\": \"^12.3.0\",\n \"vform\": \"^2.1.2\",\n \"vue-autosuggest\": \"^2.2.0\",\n \"vue-gtag\": \"^1.16.1\",\n \"vue-infinite-loading\": \"^2.4.5\",\n \"vue2-google-maps-withscopedautocomp\": \"^0.12.1\"\n },\n \"devDependencies\": {\n \"eslint-config-prettier\": \"^8.3.0\",\n \"eslint-plugin-prettier\": \"^4.0.0\",\n \"ip\": \"^1.1.5\",\n \"prettier\": \"^2.5.0\"\n }\n}\n```\n\nHow can I use the force flag without getting errors?\n\n**Edit:**\n\nThe errors that I'm getting for versions difference:\nhttps://i.sstatic.net/8cipY.png\n\n========================================\n\nTop Answer:\nIt seems to be an issue with the current version of Node installed on your device. If you try to reinstall on top of the previous installation, or use the @latest command it won't work. Please uninstall Node then reinstall again from the offical website.\n\n========================================\n\nCode:\n```json\n{\n \"name\": \"frontend\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"@nuxtjs/auth\": \"^4.9.1\",\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"@nuxtjs/google-adsense\": \"^1.4.0\",\n \"@nuxtjs/gtm\": \"^2.4.0\",\n \"@nuxtjs/router\": \"^1.6.1\",\n \"better-vue-input-tag\": \"^1.1.0\",\n \"bootstrap\": \"^5.1.3\",\n \"bootstrap-vue\": \"^2.21.2\",\n \"core-js\": \"^3.19.2\",\n \"eslint\": \"^8.3.0\",\n \"jquery\": \"^3.6.0\",\n \"laravel-vue-pagination\": \"^2.3.1\",\n \"node-sass\": \"^6.0.1\",\n \"nuxt\": \"^2.15.8\",\n \"popper.js\": \"^1.16.1\",\n \"sass-loader\": \"^12.3.0\",\n \"vform\": \"^2.1.2\",\n \"vue-autosuggest\": \"^2.2.0\",\n \"vue-gtag\": \"^1.16.1\",\n \"vue-infinite-loading\": \"^2.4.5\",\n \"vue2-google-maps-withscopedautocomp\": \"^0.12.1\"\n },\n \"devDependencies\": {\n \"eslint-config-prettier\": \"^8.3.0\",\n \"eslint-plugin-prettier\": \"^4.0.0\",\n \"ip\": \"^1.1.5\",\n \"prettier\": \"^2.5.0\"\n }\n}\n```\n\n```text\nnpm install\n```\n\n```text\nsudo npm cache clean -f\n```\n\n```text\nubuntu 20.04\n```\n\n```text\npackage.json\n```\n\n```text\nPS C:\\code> npm cache clean --force\nnpm WARN using --force Recommended protections disabled.\nPS C:\\code> npm cache verify\nCache verified and compressed (~\\AppData\\Local\\npm-cache\\_cacache)\nContent verified: 0 (0 bytes)\nIndex entries: 0\nFinished in 0.008s\nPS C:\\code>\n```\n\n```text\nnpm cache verify\n```\n\n```text\nHeroProject % npm cache verify\nnpm ERR! code EACCES\nnpm ERR! syscall unlink\nnpm ERR! path /Users/hero/.npm/_cacache/content-v2/sha512/04/b2/374e5d535b73ef97bd25df2ab763ae22f9ac29c17aac181616924a8cb676d782b303fb28fbae15b492e103c7325a6171a3116e6881aa4a34c10a34c8e26c\nnpm ERR! errno -13\nnpm ERR! \nnpm ERR! Your cache folder contains root-owned files, due to a bug in\nnpm ERR! previous versions of npm which has since been addressed.\nnpm ERR! \nnpm ERR! To permanently fix this problem, please run:\nnpm ERR! sudo chown -R 501:20 \"/Users/hero/.npm\"\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /Users/hero/.npm/_logs/2023-02-23T08_40_35_499Z-debug-0.log\n```\n\n```text\nHeroProject % npm cache verify \nCache verified and compressed (~/.npm/_cacache)\nContent verified: 263 (3665196 bytes)\nContent garbage-collected: 20 (1357860 bytes)\nMissing content: 8\nIndex entries: 263\nFinished in 0.439s\n```\n\n```text\nnpm cache verify\n```\n\n```text\nsudo chown -R 501:20 \"/Users/hero/.npm\"\n```\n\n```text\nnpm cache verify\n```\n\n```text\nsudo chown -R $(whoami):$(id -gn) /Users/nithinkhan/.npm\n```\n\n```text\nls -la ~/.npm\n```\n\n```text\nnpm cache clean --force\n```\n\n```text\n$(whoami)\n```\n\n```text\nnithinkhan\n```\n\n```text\n$(id -gn)\n```\n\n```text\nstaff\n```\n\n```text\n-R\n```\n\n```text\n.npm\n```\n\n```text\n.npm\n```\n\n========================================\n\nComments:\n- What are those `I'm getting the versions difference errors`? Also, using `sudo` with `npm` is usually not a good idea. Some packages are maybe just not compatible with node 16. Last time I checked (few days ago), it was still v14 if I'm not mistaken. There are some results on Google with the given error, maybe give it a read. Also, if you do have issues with NPM and it's annoying to debug, I'd say to give a try to yarn or PNPM at that point.\n- @kissu Thank you first of all. I googled and checked the links but the problem is not solved yet. No, the latest version is 16 so, I need to use node 16 for my other projects in my system. I will try by yarn or PNPM by the way. thanks.\n- Those are warnings and not errors.\n- @kissu I want to force clear the cache. How can I do this?\n- I have the same problem but when I try to do `npm cache verify`, `npm` answers me `Not found: verify`, so what to do in this case?","metadata":{"transformedAt":"2026-08-18T18:33:07.829Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":234,"estimatedTokens":1481}}20{"id":"stack-49665571","source":"stackoverflow","questionId":49665571,"title":"[Vue warn]: Unknown custom element: - When running jest unit tests","tags":["vue.js","jestjs","vue-router","nuxt.js","vue-test-utils"],"text":"Title: [Vue warn]: Unknown custom element: - When running jest unit tests\nTags: vue.js, jestjs, vue-router, nuxt.js, vue-test-utils\nSource: Stack Overflow\n\nQuestion:\n**Problem**\n\nI'm using nuxt 1.4 with routing using Jest to do unit testing. My application doesn't throw errors and seems to work perfectly. However when running my unit test `npm run unit` (which runs jest) it throws an error in the terminal: `[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the \"name\" option.`\n\n**Expected**\n\nI would expect it to not throw this error since my application is working.\n\n**Files**\n\n`package.json`:\n\n```\n{\n \"name\": \"vue-starter\",\n \"version\": \"1.0.0\",\n \"description\": \"Nuxt.js project\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"precommit\": \"npm run lint\",\n \"test\": \"npm run lint && npm run unit\",\n \"unit\": \"jest\",\n \"unit:report\": \"jest --coverage\"\n },\n \"dependencies\": {\n \"babel-jest\": \"^22.4.1\",\n \"jest-serializer-vue\": \"^1.0.0\",\n \"node-sass\": \"^4.7.2\",\n \"npm\": \"^5.7.1\",\n \"nuxt\": \"^1.0.0\",\n \"sass-loader\": \"^6.0.7\",\n \"vue-jest\": \"^2.1.1\"\n },\n \"devDependencies\": {\n \"@vue/test-utils\": \"^1.0.0-beta.12\",\n \"babel-eslint\": \"^8.2.1\",\n \"eslint\": \"^4.15.0\",\n \"eslint-friendly-formatter\": \"^3.0.0\",\n \"eslint-loader\": \"^1.7.1\",\n \"eslint-plugin-vue\": \"^4.0.0\",\n \"jest\": \"^22.4.2\"\n },\n \"browserslist\": [\n \"> 1%\",\n \"last 2 versions\",\n \"not ie /node_modules/babel-jest\",\n \".*\\\\.(vue)$\": \"/node_modules/vue-jest\"\n },\n \"snapshotSerializers\": [\n \"/node_modules/jest-serializer-vue\"\n ]\n }\n}\n```\n\nThe component that I test:\n\n```\n\n \n {{item.name}}\n {{ btnText }}\n \n\n // import nuxtLink from '../.nuxt/components/nuxt-link';\n\n const connectionStatusMap = [\n 'Connect',\n 'Connected',\n 'Pending',\n 'Cancel',\n ];\n\n export default {\n /*components: {\n 'nuxt-link': nuxtLink,\n },*/\n props: {\n item: {\n type: Object\n }\n },\n ...\n }\n\n```\n\nMy test script:\n\n```\nimport TestItem from '../components/TestItem';\nimport { shallow, mount, createLocalVue } from '@vue/test-utils';\nimport Vuex from 'vuex';\nimport VueRouter from 'vue-router';\n\nconst localVue = createLocalVue()\n\nlocalVue.use(Vuex)\nlocalVue.use(VueRouter)\n\n...\nit(`should show the entity`, () => {\n const wrapper = mount(TestItem, {\n propsData: { item },\n localVue,\n store,\n // stubs: ['nuxt-link'],\n })\n expect(wrapper.find('.name').text()).toBe(item.name);\n });\n\n it(`should show allow me to connect if I'm not yet connected`, () => {\n const wrapper = shallow(TestItem, {\n propsData: { item },\n localVue,\n store,\n stubs: ['nuxt-link'],\n })\n expect(wrapper.find('.connect').text()).toBe('Connect');\n });\n ...\n```\n\n**I tried**\n\nI tried creating a localVue and also stubbing the component as suggested in this github comment\nI also tried `shallow`/`mount` but that did not seem to work either.\n\n========================================\n\nTop Answer:\nThis is how I was able to get rid of the annoying warning:\n\nInclude RouterLinkStub, eg.:\n\n```\nimport { shallowMount, createLocalVue, RouterLinkStub } from '@vue/test-utils';\n```\n\nMap NuxtLink stub to RouterLinkStub\n\n```\nconst wrapper = shallowMount(TestItem, {\n ...\n stubs: {\n NuxtLink: RouterLinkStub\n }\n})\n```\n\nAnd in case you were checking nuxt-link text or something, change:\n\n```\nconst link = wrapper.find('nuxt-link');\n```\n\nto\n\n```\nconst link = wrapper.find(RouterLinkStub);\n```\n\nFound this gold on https://onigra.github.io/blog/2018/03/19/vue-test-utils-router-link-stub/\n\nGood thing you don't need to know japanese to read code...\n\n========================================\n\nCode:\n```json\n{\n \"name\": \"vue-starter\",\n \"version\": \"1.0.0\",\n \"description\": \"Nuxt.js project\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"precommit\": \"npm run lint\",\n \"test\": \"npm run lint && npm run unit\",\n \"unit\": \"jest\",\n \"unit:report\": \"jest --coverage\"\n },\n \"dependencies\": {\n \"babel-jest\": \"^22.4.1\",\n \"jest-serializer-vue\": \"^1.0.0\",\n \"node-sass\": \"^4.7.2\",\n \"npm\": \"^5.7.1\",\n \"nuxt\": \"^1.0.0\",\n \"sass-loader\": \"^6.0.7\",\n \"vue-jest\": \"^2.1.1\"\n },\n \"devDependencies\": {\n \"@vue/test-utils\": \"^1.0.0-beta.12\",\n \"babel-eslint\": \"^8.2.1\",\n \"eslint\": \"^4.15.0\",\n \"eslint-friendly-formatter\": \"^3.0.0\",\n \"eslint-loader\": \"^1.7.1\",\n \"eslint-plugin-vue\": \"^4.0.0\",\n \"jest\": \"^22.4.2\"\n },\n \"browserslist\": [\n \"> 1%\",\n \"last 2 versions\",\n \"not ie <= 8\"\n ],\n \"jest\": {\n \"moduleFileExtensions\": [\n \"js\",\n \"vue\"\n ],\n \"transform\": {\n \"^.+\\\\.js$\": \"<rootDir>/node_modules/babel-jest\",\n \".*\\\\.(vue)$\": \"<rootDir>/node_modules/vue-jest\"\n },\n \"snapshotSerializers\": [\n \"<rootDir>/node_modules/jest-serializer-vue\"\n ]\n }\n}\n```\n\n```html\n<template>\n <div>\n <nuxt-link class=\"name\" :to=\"{ path: `entity/${item.id}`, params: { id: item.id }}\">{{item.name}}</nuxt-link>\n <button class=\"connect\" @click=\"connect\">{{ btnText }}</button>\n </div>\n</template>\n\n<script>\n // import nuxtLink from '../.nuxt/components/nuxt-link';\n\n const connectionStatusMap = [\n 'Connect',\n 'Connected',\n 'Pending',\n 'Cancel',\n ];\n\n export default {\n /*components: {\n 'nuxt-link': nuxtLink,\n },*/\n props: {\n item: {\n type: Object\n }\n },\n ...\n }\n</script>\n```\n\n```js\nimport TestItem from '../components/TestItem';\nimport { shallow, mount, createLocalVue } from '@vue/test-utils';\nimport Vuex from 'vuex';\nimport VueRouter from 'vue-router';\n\nconst localVue = createLocalVue()\n\nlocalVue.use(Vuex)\nlocalVue.use(VueRouter)\n\n...\nit(`should show the entity`, () => {\n const wrapper = mount(TestItem, {\n propsData: { item },\n localVue,\n store,\n // stubs: ['nuxt-link'],\n })\n expect(wrapper.find('.name').text()).toBe(item.name);\n });\n\n it(`should show allow me to connect if I'm not yet connected`, () => {\n const wrapper = shallow(TestItem, {\n propsData: { item },\n localVue,\n store,\n stubs: ['nuxt-link'],\n })\n expect(wrapper.find('.connect').text()).toBe('Connect');\n });\n ...\n```\n\n```text\nnpm run unit\n```\n\n```text\n[Vue warn]: Unknown custom element: <nuxt-link> - did you register the component correctly? For recursive components, make sure to provide the \"name\" option.\n```\n\n```text\npackage.json\n```\n\n```text\nshallow\n```\n\n```text\nmount\n```\n\n```js\nconst wrapper = mount(TestItem, {\n propsData: { item },\n localVue,\n store,\n stubs: {\n NuxtLink: true,\n // Any other component that you want stubbed\n },\n});\n```\n\n```js\n...\nimport NuxtLink from '../.nuxt/components/nuxt-link.js'\n\n...\nTestItem.components = TestItem.components || {};\nTestItem.components.NuxtLink = NuxtLink;\nconst wrapper = shallow(TestItem, {\n ...\n});\n...\n```\n\n```js\nimport { shallow } from '@vue/test-utils'; \nimport ContentCard from '../../components/ContentCard.vue'; \nimport NuxtLink from '../../.nuxt/components/nuxt-link'; \n\nconst createComponent = propsData => shallow(ContentCard, { propsData }); \n\ndescribe('ContentCard', () => { \n let component; \n\n beforeEach(() => {\n ContentCard.components = ContentCard.components || {}; \n ContentCard.components.NuxtLink = NuxtLink; \n }); \n\n describe('Properties', () => {\n it('has an imgSrc property', () => { \n component = createComponent({ imgSrc: 'X' }); \n expect(component.props().imgSrc).toBe('X'); \n }); \n }); \n});\n```\n\n```text\nUnknow custom element: <router-link>\n```\n\n```text\nmount\n```\n\n```text\nshallow\n```\n\n```js\nimport NuxtLink from \"path to nuxt-link.js\"\n\nMycomponent.components.NuxtLink = NuxtLink\n```\n\n```js\ntransformIgnorePatterns: [\n \"path to nuxt-link.js\"\n],\n```\n\n```js\nmount(Mycomponent, {stubs: [\"nuxt-link\"]})\n```\n\n```js\nimport { shallowMount, createLocalVue, RouterLinkStub } from '@vue/test-utils';\n```\n\n```js\nconst wrapper = shallowMount(TestItem, {\n ...\n stubs: {\n NuxtLink: RouterLinkStub\n }\n})\n```\n\n```js\nconst link = wrapper.find('nuxt-link');\n```\n\n```js\nconst link = wrapper.find(RouterLinkStub);\n```\n\n```js\nimport { mount, createLocalVue } from '@vue/test-utils'\nimport Component from '@/components/Component.vue'\n\nconst localVue = createLocalVue()\n\nlocalVue.component('nuxt-link', {\n props: ['to'],\n template: '<a href=\"#\"><slot>NuxtLink</slot></a>',\n})\n\ndescribe('Test Component', () => {\n\n const wrapper = mount(Component, {\n stubs: ['nuxt-link'],\n localVue\n })\n})\n```\n\n```js\n// path: ./test/jest.setup.js\n\nimport Vue from 'vue'\nimport VueTestUtils from '@vue/test-utils'\n\n// Mock Nuxt components\nVueTestUtils.config.stubs['nuxt-link'] = '<a><slot /></a>'\nVueTestUtils.config.stubs['no-ssr'] = '<span><slot /></span>'\n```\n\n```js\n// path: ./jest.config.js\n\nmodule.exports = {\n // ... other stuff\n setupFilesAfterEnv: ['./test/jest.setup.js']\n}\n```\n\n```js\n// test/jestSetup.js\n\nimport Vue from 'vue'\nimport Vuetify from 'vuetify'\nimport { config } from '@vue/test-utils'\n\nVue.use(Vuetify)\n\nconfig.stubs.NuxtLink = { template: '<a><slot /></a>' }\n```\n\n```text\nconst wrapper = mount(TestItem, {\n props,\n global: {\n stubs: {\n NuxtLink: true,\n },\n },\n});\n```\n\n```text\nwrapper = mount(TestItem, {\n props,\n global: {\n components: {\n NuxtLink: {\n template: '<a><slot/></a>',\n },\n },\n },\n});\n```\n\n```text\nwrapper = shallowMount(TestItem, {\n props,\n global: {\n stubs: {\n NuxtLink: false,\n },\n components: {\n NuxtLink: {\n template: '<a><slot/></a>',\n },\n },\n },\n});\n```\n\n```text\n<NuxtLink\n to=\"www.example.com\"\n class=\"item-class\"\n><div>ItemContent</div></NuxtLink>\n```\n\n```text\n<a to=\"www.example.com\" class=\"item-class\"><div>ItemContent</div></a>\n```\n\n========================================\n\nComments:\n- Thanks for your reply. I now get this error `console.error node_modules/vue/dist/vue.runtime.common.js:589 [Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the \"name\" option. (found in )` But I don't have any router-link element in my app, only `nuxt-link`\n- @Anima-t3d did you find a solution to the \"router-link\" error?. I have the exact same issue.\n- @Oldenborg I did not yet have the time to try out the solutions. But glad you found yours.\n- This has been renamed `shallowMount` now","metadata":{"transformedAt":"2026-08-18T18:33:07.830Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":529,"estimatedTokens":2851}}21{"id":"stack-55997850","source":"stackoverflow","questionId":55997850,"title":"Error in running nuxt project: \"'nuxt' is not recognized as an internal or external command\"","tags":["vue.js","nuxt.js"],"text":"Title: Error in running nuxt project: \"'nuxt' is not recognized as an internal or external command\"\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhen I tried to run `npm run dev` in my nuxt project, my console returned this message:\n\n```\n'nuxt' is not recognized as an internal or external command, \noperable program or batch file.\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\nnpm ERR! andromeda@1.0.0 dev: `nuxt`\nnpm ERR! Exit status 1\nnpm ERR!\nnpm ERR! Failed at the andromeda@1.0.0 dev script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n```\n\n========================================\n\nTop Answer:\nMake sure `nuxt` is installed in your Nuxt project:\n\n```\n$ cd /path/to/nuxt-project\n$ npm list nuxt\nnuxt-project@1.0.0 /path/to/nuxt-project\n└── nuxt@2.6.3\n```\n\nHere */path/to/nuxt-project* contains your *package.json* and *node-modules*.\n\nIf it isn't installed, add `nuxt` to your project by doing:\n\n```\n$ npm install --save nuxt\n```\n\nOr put it in your project's *package.json* then do `npm install`:\n\n```\n\"dependencies\": {\n \"nuxt\": \"^2.0.0\"\n },\n```\n\n**UPDATE**:\n\nIf you are still getting \"nuxt not recognized\" problems, try to use explicit path to `nuxt` from your *node_modules* directory.\n\nGiven this directory (after doing `npm install --save nuxt`):\n\n```\nnuxt-project\n|- node_modules\n |- .bin\n |- nuxt\n|- package.json\n```\n\nUpdate the `dev` command in *package.json* with:\n\n```\n\"scripts\": {\n \"dev\": \"node_modules/.bin/nuxt\"\n},\n```\n\n========================================\n\nCode:\n```text\n'nuxt' is not recognized as an internal or external command, \noperable program or batch file.\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\nnpm ERR! andromeda@1.0.0 dev: `nuxt`\nnpm ERR! Exit status 1\nnpm ERR!\nnpm ERR! Failed at the andromeda@1.0.0 dev script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm cache clean --force\n```\n\n```text\nrm -rf node_modules\n```\n\n```text\npackage-lock.json\n```\n\n```text\nnpm install\n```\n\n```text\nnpm start\n```\n\n```text\n$ cd /path/to/nuxt-project\n$ npm list nuxt\nnuxt-project@1.0.0 /path/to/nuxt-project\n└── nuxt@2.6.3\n```\n\n```text\n$ npm install --save nuxt\n```\n\n```text\n\"dependencies\": {\n \"nuxt\": \"^2.0.0\"\n },\n```\n\n```text\nnuxt-project\n|- node_modules\n |- .bin\n |- nuxt\n|- package.json\n```\n\n```text\n\"scripts\": {\n \"dev\": \"node_modules/.bin/nuxt\"\n},\n```\n\n```text\nnuxt\n```\n\n```text\nnuxt\n```\n\n```text\nnpm install\n```\n\n```text\nnuxt\n```\n\n```text\nnpm install --save nuxt\n```\n\n```text\ndev\n```\n\n```text\n\"scripts\": {\n \"dev\": \"cross-env nuxt\",\n \"build\": \"cross-env nuxt build\",\n \"start\": \"cross-env nuxt start\",\n \"generate\": \"cross-env nuxt generate\",\n \"lint\": \"eslint --ext .js,.vue --ignore-path .gitignore .\"\n},\n```\n\n```text\nnpm install -g cross-env\n```\n\n```text\nnode_modules/.bin\n```\n\n```text\n.bashrc\n```\n\n```text\n.zshrc\n```\n\n```text\nexport PATH=node_modules/.bin:$PATH\n```\n\n```text\n\"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n```\n\n```text\n\"scripts\": {\n \"dev\": \"node_modules/.bin/nuxt\",\n \"build\": \"node_modules/.bin/nuxt build\",\n \"start\": \"node_modules/.bin/nuxt start\",\n \"generate\": \"node_modules/.bin/nuxt generate\"\n },\n```\n\n```text\nnpm install nuxt\n```\n\n```text\nNuxt 2\n```\n\n```text\nNuxt 3\n```\n\n```text\nscripts\n```\n\n```text\npackage.json\n```\n\n```text\nnuxt-ts\n```\n\n```text\nnuxt\n```\n\n```text\n\"dev\": \"nuxt-ts\",\n```\n\n```text\n\"dev\": \"nuxt dev\",\n```\n\n```text\n\"generate\": \"nuxt-ts generate\",\n```\n\n```text\n\"generate\": \"nuxt generate\",\n```\n\n========================================\n\nComments:\n- What version of node, npm and nuxt do you have?\n- Have you run `npm install`?\n- I tried run npm install alrady. nuxt@2.6.1 node v10.15.3 npm 6.4.1\n- Possible duplicate of npm ERR! code ELIFECYCLE\n- It still has the same error. My dependencies: \"dependencies\": { \"nuxt\": \"^2.4.0\", \"cross-env\": \"^5.2.0\", \"bootstrap-vue\": \"^2.0.0-rc.11\", \"bootstrap\": \"^4.1.3\", \"@nuxtjs/axios\": \"^5.3.6\" },\n- @Marquezz Just to be sure, you are running `npm install` and `npm run dev` under the project directory? What do you get when you do `npm list nuxt`?\n- I am sure that i'm on the right directory.and when i run npm list nuxt i get this: `-- nuxt@2.6.1 I search on google and i found some people having problems with nuxt + windows 10\n- @Marquezz Oh OK. I updated my answer. Try to change the `dev` command to use the explicit node_modules path for `nuxt`.\n- I followed these steps and this error went away for me. But, I had to use `yarn install` after this to link the dependencies properly and do `npm run dev`\n- This answer also solved the similar problem I had with `nuxt-ts`. Thank you !\n- what does cross-env have to do with nuxt being undefined?","metadata":{"transformedAt":"2026-08-18T18:33:07.830Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":37,"totalLines":269,"estimatedTokens":1205}}22{"id":"stack-51556126","source":"stackoverflow","questionId":51556126,"title":"How to access to the vue store in the asyncData function of nuxt","tags":["vuejs2","nuxt.js"],"text":"Title: How to access to the vue store in the asyncData function of nuxt\nTags: vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nin a component i want to acces to the store with the asyncData function like so :\n\n```\nasyncData({ app, params }) {\nvar url = `https://myapi/news/${app.$store.state.market}/detail/${params.id}`;\nreturn app.$axios.get(url).then(response => {\n return { actu: response.data };\n});\n```\n\n}\n\nbut i received \"Cannot read property 'state' of undefined\"\n\nis there another to receive the state of the store here ?\n\n========================================\n\nTop Answer:\nThis worked for me\n\nStore/index.js\n\n```\n...\n\nstate: {\n loadedPages: []\n}\n...\n```\n\nPage\n\n```\nasync asyncData(context) {\n...\nconsole.log(context.store.state.loadedPages)\n...\n\n}\n```\n\n========================================\n\nCode:\n```text\nasyncData({ app, params }) {\nvar url = `https://myapi/news/${app.$store.state.market}/detail/${params.id}`;\nreturn app.$axios.get(url).then(response => {\n return { actu: response.data };\n});\n```\n\n```text\nasyncData({ app, params, store }) {\n var url = `https://myapi/news/${store.state.market}/detail/${params.id}`;\n return app.$axios.get(url).then(response => {\n return { actu: response.data };\n});\n```\n\n```text\n...\n\nstate: {\n loadedPages: []\n}\n...\n```\n\n```text\nasync asyncData(context) {\n...\nconsole.log(context.store.state.loadedPages)\n...\n\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.830Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":84,"estimatedTokens":346}}23{"id":"stack-73298776","source":"stackoverflow","questionId":73298776,"title":"What's the difference between Nuxt and Vite?","tags":["javascript","vue.js","nuxt.js","vite"],"text":"Title: What's the difference between Nuxt and Vite?\nTags: javascript, vue.js, nuxt.js, vite\nSource: Stack Overflow\n\nQuestion:\nI'm learning Vue, and it's ecosystem, and now I read about nuxt.js.\n\nAs I understand, this is tool which help us to build Vue apps, but don't we do the same with vite.js?\n\nWhat's the difference between them?\n\n========================================\n\nComments:\n- I recommend working with Vue quite a bit before going to Nuxt btw. Don't rush the steps and learn the basics of Vue well.\n- Google search engine is reading JavaScript files on page. So you will have well indexed SPA page. But you won't have nice cards on Facebook and other sites and apps with may crawl your page.\n- @Mises even if it works somewhat, it's far from being good enough hence why I'm simplifying by saying it just doesn't. Google is asking you to go the extra mile nowadays, so an SPA is not good enough.\n- Would love to know what does the \"not as powerful\" mean specifically, that would be a good insight for people deciding whether to use nuxt or vite as those two are what vue ssr docs mention as options.\n- @Klesun as explained above, Vite is a bundler so it will only manage that part. Nuxt on the other side, is a powerful Vue app on steroids with a lot things around it (SSR baked in, routes, advanced life cycle hooks etc...) + a huge ecosystem. You can do all of this with Vite but it will require more time/work/knowledge overall. Also, Nuxt is specific to Vue while Vite can be used by any kind of Framework (React, Svelte, Astro etc...).","metadata":{"transformedAt":"2026-08-18T18:33:07.830Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":19,"estimatedTokens":388}}24{"id":"stack-56476413","source":"stackoverflow","questionId":56476413,"title":"Custom elements in iteration require 'v-bind:key' directives","tags":["vue.js","nuxt.js","v-for"],"text":"Title: Custom elements in iteration require 'v-bind:key' directives\nTags: vue.js, nuxt.js, v-for\nSource: Stack Overflow\n\nQuestion:\nIn my Nuxt app I have the following line that triggers the error mentioned in the title of this question:\n\n```\n\n \n```\n\nI tried to have the `:key` attribute on the `template` element and I also tried to use just `index` as the key, to no avail.\n\nAny idea?\n\n========================================\n\nCode:\n```text\n<template v-for=\"(project, index) in existingProjects\">\n <span :key=\"project.projectId\"></span>\n```\n\n```text\n:key\n```\n\n```text\ntemplate\n```\n\n```text\nindex\n```\n\n```text\n<template v-for=\"(project, index) in existingProjects\">\n <span :key=\"project.projectId\">foo</span>\n <div :key=\"project.projectId\">bar</div>\n</template>\n```\n\n```text\n<div v-for=\"(project, index) in existingProjects\" :key=\"project.projectId\">\n <span>foo</span>\n <div>bar</div>\n</div>\n```\n\n```text\ntemplate\n```\n\n```text\nkey\n```\n\n```text\ntemplate\n```\n\n```text\n<template> cannot be keyed. Place the key on real elements instead.\n```\n\n```text\ntemplate\n```\n\n```text\nkey\n```\n\n========================================\n\nComments:\n- You'd have to key *all* elements inside the template. If you have more than just the `span`, those elements would also need unique keys. Consider moving those elements into a component.\n- May be use, looping (v-for) on a div instead of template and put keys then.\n- The first solution results in a warning `Duplicate keys detected: 'ABC'. This may cause an update error.` Can add a suffix like `:key=\"project.projectId + '-span'\"` to make each key unique","metadata":{"transformedAt":"2026-08-18T18:33:07.830Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":80,"estimatedTokens":401}}25{"id":"stack-50943966","source":"stackoverflow","questionId":50943966,"title":"Configure nuxt.js application to work in a subdirectory on a webserver","tags":["vue.js","nuxt.js"],"text":"Title: Configure nuxt.js application to work in a subdirectory on a webserver\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to deploy a static nuxt.js application (built with `nuxt generate`) to a subdirectory of a webserver. nuxt places the generated files in the `dist` directory by default:\n\nhttps://i.sstatic.net/2EFOb.png\n\nIf I start a webserver on the *parent directory* of the `dist` folder and open the page with:\n\n`http://localhost:34360/dist/`\n\nthe site fails to load the script files from the domain root directory:\n\nhttps://i.sstatic.net/tHjDy.png\n\nI've tried setting the `publicPath` property in the nuxt config:\n\n```\nbuild: {\n publicPath: '/dist/'\n}\n```\n\nThe appplication compiles to:\n\nhttps://i.sstatic.net/yNIaf.png\n\nNow, nuxt moves the script files one level lower (/dist/dist) and searches on root level again (/dist), thus still not finding the files\n\nhttps://i.sstatic.net/kwEF0.png\n\n**How can I configure the site, such that scripts and assets are loaded and it is self contained, no matter on which directory on my server I put it?**\n\nThe issue has been covered on GitHub but the suggested hints (using publicPath) didn't work, as shown above.\n\nSidenote: I do not want to specify the publicPath absolut (i.e. `http://localhost:8080/dist`), which would work but creates new problems.\n\n========================================\n\nTop Answer:\nTo complete @Aldarund answer, I use :\n\n```\nexport default {\n[…] // some code\n router: {\n base:\n process.env.NODE_ENV === \"development\" ? process.env.BASE_URL : \"//\"\n } // where is the subfolder!\n};\n```\n\n========================================\n\nCode:\n```text\nbuild: {\n publicPath: '/dist/'\n}\n```\n\n```text\nnuxt generate\n```\n\n```text\ndist\n```\n\n```text\ndist\n```\n\n```text\nhttp://localhost:34360/dist/\n```\n\n```text\npublicPath\n```\n\n```text\nhttp://localhost:8080/dist\n```\n\n```text\nrouter: {\n base: '/dist/'\n}\n```\n\n```js\nexport default {\n[…] // some code\n router: {\n base:\n process.env.NODE_ENV === \"development\" ? process.env.BASE_URL : \"/<subfolder>/\"\n } // where <subfolder> is the subfolder!\n};\n```\n\n```text\napp.baseURL\n```\n\n```text\nNUXT_APP_BASE_URL\n```\n\n========================================\n\nComments:\n- This is what I was searching for! Thank you! And is there a way to configure this generically, i.e. in a the app could be moved to /xyz/ without requiring changing the config and rebuilding?\n- without rebuilding i dont think so. maybe only via some 3rd party module. As for dynamically you could do it in nuxt.config build.extend\n- Thank you, I will fo with your solution for now!\n- for future needs, here is the documentation about router base configuration nuxtjs.org/docs/2.x/configuration-glossary/configuration-rou‌​ter\n- This is what I was looking for. Ty.","metadata":{"transformedAt":"2026-08-18T18:33:07.830Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":119,"estimatedTokens":692}}26{"id":"stack-49599274","source":"stackoverflow","questionId":49599274,"title":"How to submit a form in Vue, redirect to a new route and pass the parameters?","tags":["javascript","node.js","vue.js","nuxt.js"],"text":"Title: How to submit a form in Vue, redirect to a new route and pass the parameters?\nTags: javascript, node.js, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using Nuxt and Vue and I am trying to submit a form, redirect the user to a new route including the submitted params, send an API request to get some data and then render that data.\n\nI achieved this by simply setting the form action to the new path and manually adding all the URL parameters to the API request.\n\nFirst I create a simple form with the route `/search`.\n\n```\n\n \n Submit\n\n```\n\nWhen submitting the form the user leaves the current page and gets redirected to the new page. The URL would now look like this: `http://www.example.com/search?foobar=test`. Now I fetch the `foobar` parameter by using `this.$route.query.foobar` and send it to my API.\n\nHowever the problem in my approach is when submitting the form the user leaves the current page and a new page load will occur. This is not what we want when building progressive web apps.\n\nSo my question is how can I submit a form in Nuxt/Vue and redirect to a new route including the submitted parameters?\n\n========================================\n\nTop Answer:\n```\nsubmitClick(){\n this.$router.push({path: '/search', query:{key: value}})\n }\n```\n\n\r\n\n```\n\n \n Search\n\n```\n\n\r\n\r\n\r\n\nThis is the right way to achieve a SPA with form submit. it supports enter key and in submitClick, there can be any logic before submitting\n\n========================================\n\nCode:\n```text\n<form action=\"/search\">\n <input type=\"text\" name=\"foobar\">\n <button type=\"submit\">Submit</button>\n</form>\n```\n\n```text\n/search\n```\n\n```text\nhttp://www.example.com/search?foobar=test\n```\n\n```text\nfoobar\n```\n\n```text\nthis.$route.query.foobar\n```\n\n```html\n<form>\n <input type=\"text\" name=\"foobar\" v-model=\"foobar\">\n <button type=\"submit\" @click.stop.prevent=\"submit()\">Submit</button>\n</form>\n```\n\n```js\nexport default {\n data(){\n return {\n foobar : null\n }\n },\n methods: {\n submit(){\n //if you want to send any data into server before redirection then you can do it here\n this.$router.push(\"/search?\"+this.foobar);\n }\n }\n}\n```\n\n```text\n<form>\n```\n\n```text\nonsubmit\n```\n\n```text\n<form>\n```\n\n```text\nrouter module\n```\n\n```text\n<form>\n```\n\n```text\n.stop.prevent\n```\n\n```text\n<form>\n```\n\n```text\nevent.stopPropagation();\n```\n\n```text\nevent.preventDefault();\n```\n\n```text\nfoobar\n```\n\n```text\nsubmit\n```\n\n```text\nthis.$router.push\n```\n\n```text\nthis.$router.push\n```\n\n```text\n<form @submit.prevent=\"false\">\n <div class=\"form-group\">\n\n </div> \n </form>\n```\n\n```js\nsubmitClick(){\n this.$router.push({path: '/search', query:{key: value}})\n }\n```\n\n```html\n<form @submit.stop.prevent=\"submitClick\">\n <input v-model=\"keyword\">\n <button type=\"submit\">Search</button>\n</form>\n```\n\n========================================\n\nComments:\n- You should prefer using `` as it will also catch submitting by pressing enter in any field.\n- Exactly, use `@submit` on the `` instead. Also, `.stop` is useless here, because nested forms are not allowed in HTML anyway.\n- How can do post method in form ? now its visible in url\n- Wow! I looked for the documents, but couldn't put the pieces together. Thanks for great example and nice explanation.","metadata":{"transformedAt":"2026-08-18T18:33:07.830Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":177,"estimatedTokens":822}}27{"id":"stack-50260260","source":"stackoverflow","questionId":50260260,"title":"VueJS: variable is undefined inside computed only","tags":["vue.js","nuxt.js"],"text":"Title: VueJS: variable is undefined inside computed only\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make async autocomplete input with Vue, Nuxt, Axios and Buefy. It basically works, but I need to have different strings when user just starts typing and there's yet nothing to show, and when there is nothing found for such request.\n\nI'm checking in computed variable if input value isn't empty and axios returns empty array to handle if the request address cannot be found. But it causes error \n\n Cannot read property 'length' of undefined\n\nThe weird thing is that `address` variable is successfully used in other parts of my component.\n\nMy vue file below:\n\n```\n\nb-field(label=\"Your address?\")\n b-autocomplete(\n rounded,\n v-model=\"address\",\n :data=\"data\",\n placeholder=\"Start typing\",\n icon=\"magnify\",\n @input=\"getAsyncData\",\n @select=\"option => selected = option\",\n :loading=\"isFetching\"\n )\n template(slot=\"empty\") {{ dummyText }}\n\nimport axios from 'axios'\nimport debounce from 'lodash/debounce'\n\nexport default {\n data() {\n return {\n data: [],\n address: '',\n selected: null,\n isFetching: false,\n nothingFound: false,\n test: false\n }\n },\n\n computed: {\n dummyText: () => {\n if (this.address.length > 0 && this.nothingFound) { // This will return error\n return 'There is no such address'\n } else {\n return 'Keep typing'\n }\n }\n },\n\n methods: {\n getAsyncData: debounce(function () {\n this.isFetching = true\n\n axios.post('https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/address', {\n \"query\": this.address,\n \"count\": 8\n }, {\n headers: {\n 'Authorization': 'Token sometoken',\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n }\n })\n .then(response => {\n this.isFetching = false\n this.data = Object.values(response.data.suggestions)\n if (response.data.suggestions.length===0) this.nothingFound = true\n console.log(this.address.length) // This will work\n })\n .catch(error => {\n this.isFetching = false\n console.log(error);\n })\n }, 300)\n }\n}\n\n```\n\nThis is not about ssr, I've tried to init component inside mounted hook. Think I'm missing out something obvious, but I've already spent hours trying to fix this without success\n\n========================================\n\nTop Answer:\nYou can also use es2015 shorthand for a method function:\n\n```\ncomputed: {\n dummyText() {\n return this.address.length > 0 && this.nothingFound ? 'There is no such address' : 'Keep typing';\n }\n}\n```\n\n========================================\n\nCode:\n```text\n<template lang=\"pug\">\nb-field(label=\"Your address?\")\n b-autocomplete(\n rounded,\n v-model=\"address\",\n :data=\"data\",\n placeholder=\"Start typing\",\n icon=\"magnify\",\n @input=\"getAsyncData\",\n @select=\"option => selected = option\",\n :loading=\"isFetching\"\n )\n template(slot=\"empty\") {{ dummyText }}\n</template>\n\n<script>\nimport axios from 'axios'\nimport debounce from 'lodash/debounce'\n\nexport default {\n data() {\n return {\n data: [],\n address: '',\n selected: null,\n isFetching: false,\n nothingFound: false,\n test: false\n }\n },\n\n computed: {\n dummyText: () => {\n if (this.address.length > 0 && this.nothingFound) { // This will return error\n return 'There is no such address'\n } else {\n return 'Keep typing'\n }\n }\n },\n\n methods: {\n getAsyncData: debounce(function () {\n this.isFetching = true\n\n axios.post('https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/address', {\n \"query\": this.address,\n \"count\": 8\n }, {\n headers: {\n 'Authorization': 'Token sometoken',\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n }\n })\n .then(response => {\n this.isFetching = false\n this.data = Object.values(response.data.suggestions)\n if (response.data.suggestions.length===0) this.nothingFound = true\n console.log(this.address.length) // This will work\n })\n .catch(error => {\n this.isFetching = false\n console.log(error);\n })\n }, 300)\n }\n}\n</script>\n```\n\n```text\naddress\n```\n\n```text\ncomputed: {\n dummyText: function () { // change to function () {}\n if (this.address.length > 0 && this.nothingFound) { // This will return error\n return 'There is no such address'\n } else {\n return 'Keep typing'\n }\n }\n},\n```\n\n```text\n()=>{}\n```\n\n```text\ncomputed\n```\n\n```text\nfunction () {}\n```\n\n```text\nmethods\n```\n\n```text\nwatch\n```\n\n```text\ncomputed: {\n dummyText() {\n return this.address.length > 0 && this.nothingFound ? 'There is no such address' : 'Keep typing';\n }\n}\n```\n\n```text\ndummyText: function () {\n console.log(this.address)\n}\n```\n\n```text\ndummyText() {\n console.log(this.address)\n}\n```\n\n```text\ndummyText : ctx => console.log(ctx.address)\n```\n\n========================================\n\nComments:\n- Are you allowed to have a data field named 'data'? Sounds like you might be accidentally clearing wiping out other data fields on accident, which is why address is undefined until it is set with the v-model?\n- @AaronPool Just tried renaming 'data', no effect\n- Eslint expects this: `Expected method shorthand`","metadata":{"transformedAt":"2026-08-18T18:33:07.830Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":241,"estimatedTokens":1382}}28{"id":"stack-58733960","source":"stackoverflow","questionId":58733960,"title":"Copy url to clipboard via button click in a vuejs component","tags":["javascript","vue.js","vuejs2","vue-component","nuxt.js"],"text":"Title: Copy url to clipboard via button click in a vuejs component\nTags: javascript, vue.js, vuejs2, vue-component, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have following component, and I would like to have a button that copies the `link_url` to the clipboard on click.\n\nI have javascript code that works when selecting an id, however the links do not have an id.\nCan I accomplish the selection of the `a-tag` via refs in the component itself, or what would be the best way to get this done.\n\nI was also thinking about generating an a-tag with the this.link_url in the `copyURL()` dynamically but I guess that would be very dirty.. I am looking for the vuejs way.\n\n```\n\n \n {{ link_name }}\n copy url from a tag\n \n\nexport default {\n props: [\"link_url\", \"link_name\"],\n methods: {\n copyURL() {\n var Url = document.getElementById('myid'); /*GET vuejs el reference here (via $ref) but how?*/\n Url.innerHTML = window.location.href;\n console.log(Url.innerHTML)\n Url.select();\n document.execCommand(\"copy\");\n }\n }\n}\n\n```\n\n========================================\n\nTop Answer:\nYou can use navigator object with clipboard in javascript.\n\nNote: navigator.clipboard.writeText is asynchronous.\n\n```\nmethods: {\n async copyURL(mytext) {\n try {\n await navigator.clipboard.writeText(mytext);\n alert('Copied');\n } catch($e) {\n alert('Cannot copy');\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\n<template>\n <li class=\"list-group-item\">\n <a :href=\"link_url\" \n class=\"text-dark\" \n target=\"_blank\" \n rel=\"noopener noreferrer\">{{ link_name }}</a>\n <button @click=\"copyUrl\">copy url from a tag</button>\n </li> \n</template>\n\n<script>\nexport default {\n props: [\"link_url\", \"link_name\"],\n methods: {\n copyURL() {\n var Url = document.getElementById('myid'); /*GET vuejs el reference here (via $ref) but how?*/\n Url.innerHTML = window.location.href;\n console.log(Url.innerHTML)\n Url.select();\n document.execCommand(\"copy\");\n }\n }\n}\n</script>\n\n<style>\n</style>\n```\n\n```text\nlink_url\n```\n\n```text\na-tag\n```\n\n```text\ncopyURL()\n```\n\n```html\n<a :href=\"link_url\" class=\"text-dark\" target=\"_blank\" rel=\"noopener noreferrer\" ref=\"mylink\">\n {{ link_name }}\n</a>\n```\n\n```js\nmethods: {\n copyURL() {\n var Url = this.$refs.mylink;\n Url.innerHTML = window.location.href;\n console.log(Url.innerHTML)\n Url.select();\n document.execCommand(\"copy\");\n }\n }\n```\n\n```js\nmethods: {\n copyUrl() {\n const el = document.createElement('textarea'); \n el.value = this.link_url; \n el.setAttribute('readonly', ''); \n el.style.position = 'absolute'; \n el.style.left = '-9999px'; \n document.body.appendChild(el); \n const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; \n el.select(); \n document.execCommand('copy'); \n document.body.removeChild(el); \n if (selected) { \n document.getSelection().removeAllRanges(); \n document.getSelection().addRange(selected); \n }\n }\n}\n```\n\n```text\nref\n```\n\n```text\nref\n```\n\n```text\n<input type=\"hidden\" id=\"testing-code\" :value=\"testingCode\">\n\ncopyTestingCode () {\n let testingCodeToCopy = document.querySelector('#testing-code')\n testingCodeToCopy.setAttribute('type', 'text') \n testingCodeToCopy.select()\n\n try {\n var successful = document.execCommand('copy');\n var msg = successful ? 'successful' : 'unsuccessful';\n alert('Testing code was copied ' + msg);\n } catch (err) {\n alert('Oops, unable to copy');\n }\n\n /* unselect the range */\n testingCodeToCopy.setAttribute('type', 'hidden')\n window.getSelection().removeAllRanges()\n },\n```\n\n```text\nconst clipboardData =\n event.clipboardData ||\n window.clipboardData ||\n event.originalEvent?.clipboardData ||\n navigator.clipboard;\n\n clipboardData.writeText(message);\n```\n\n```text\nmethods: {\n async copyURL(mytext) {\n try {\n await navigator.clipboard.writeText(mytext);\n alert('Copied');\n } catch($e) {\n alert('Cannot copy');\n }\n }\n}\n```\n\n```js\nasync copy(mytext) {\n var input = document.createElement('input');\n input.setAttribute('value', mytext);\n input.value = mytext; \n document.body.appendChild(input);\n try {\n input.select(); \n input.click(); \n input.focus();\n var successful = document.execCommand('copy');\n var msg = successful ? 'successful' : 'unsuccessful';\n console.log('Testing code was copied ' + successful + ' ' + msg);\n \n } catch (err) {\n console.log('Oops, unable to copy');\n }\n document.body.removeChild(input); \n }\n```\n\n```text\n<template>\n<input ref=\"pixCodeInput\" type=\"text\">\n<button @click=\"copyPixCodeClick()\" type=\"button\">copiar código</button>\n</template>\n\n<script setup>\nimport { ref } from 'vue';\n\nconst pixCodeInput = ref(null);\n\nfunction copyPixCodeClick() {\n navigator.clipboard.writeText(pixCodeInput.value.value);\n}\n</script>\n```\n\n```html\n<template>\n <button @click=\"copyMe('Copied')\">Copy Your Code</button>\n</template>\n\n<script setup>\nimport { ref } from 'vue'\nfunction copyMe(){\n navigator.clipboard.writeText(\"Copy Clipboard\");\n}\n</script>\n```\n\n```text\n<v-btn @click='copyToClipboard()' class='mx-2'>btn text</v-btn>\n```\n\n```text\nmethod:{\ncopyToClipboard() {\nlet val = window.location.href\nnavigator.clipboard.writeText(val)\n.then(() => {\n this.$snackbar.showMessage({\n content:'coppied',\n color: 'success',\n timeout: '1000'\n });\n })\n .catch(err => {\n console.log(err);\n });\n \n },\n }\n```\n\n```text\n<q-input\n ref=\"keypixcopy\"\n class=\"col-12 col-md-2 q-mt-sm\"\n label=\"keypix\"\n v-model=\"stt.payload_pix_cc\"\n/>\n```\n\n```text\n<q-btn\n class=\"q-pr-sm q-pl-sm\"\n rounded\n outline\n label=\"Copy Paste\"\n color=\"primary\"\n @click=\"copy\"\n/>\n```\n\n```text\nconst keypixcopy = ref(null);\n```\n\n```text\nasync function copy() {\n await keypixcopy.value.focus();\n await keypixcopy.value.select();\n document.execCommand(\"copy\");\n}\n```\n\n========================================\n\nComments:\n- Thanks for the answer @fabruex. I have many links on a page, would $ref refer only to the link within the component or is the scope of $refs global, thus referring to all links then? Would I need a unique ref for each link component?\n- If you have multiple `ref=\"foo\"` within the same component `$refs.foo` will refer to the last one in the DOM. If you a have `ref=\"foo\"` in an element with the `v-for` attribute `$refs.foo` will be an array. Check this: blog.logrocket.com/…\n- So this is not a viable vuejs solution. However, I like the other proposed solution you posted!\n- Yes, you can add the url to copy as method parameter and for every link something like this in the template: `{{ link_name }}Copy URL`\n- `document.execCommand` is deprecated. Please do not use it: developer.mozilla.org/en-US/docs/Web/API/Document/execComman‌​d . Use `navigator.clipboard` instead: developer.mozilla.org/en-US/docs/Web/API/Clipboard\n- Just a heads up, this will not work on a non HTTPS connection\n- Please don't post \"try this\" answers. If you tested the code, why should they have to try? Instead, explain why you offer this alternative for all existing answers.","metadata":{"transformedAt":"2026-08-18T18:33:07.830Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":308,"estimatedTokens":1989}}29{"id":"stack-46058544","source":"stackoverflow","questionId":46058544,"title":"\"document is not defined\" in Nuxt.js","tags":["javascript","vue.js","vuejs2","nuxt.js"],"text":"Title: \"document is not defined\" in Nuxt.js\nTags: javascript, vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to use Choices.js within a Vue component. The component compiles successfully, but then an error is triggered:\n\n [vue-router] Failed to resolve async component default:\n ReferenceError: document is not defined\n\nIn the browser I see:\n\n ReferenceError document is not defined\n\nI think this has something to do with the SSR in Nuxt.js? I only need Choices.js to run on the client, because it's a client only aspect I guess.\n\n**nuxt.config.js**\n\n```\nbuild: {\n vendor: ['choices.js']\n}\n```\n\n**AppCountrySelect.vue**\n\n```\n\nimport Choices from 'choices.js'\n\nexport default {\n name: 'CountrySelect',\n created () {\n console.log(this.$refs, Choices)\n const choices = new Choices(this.$refs.select)\n console.log(choices)\n }\n}\n\n```\n\nIn classic Vue, this would work fine, so I'm very much still getting to grips with how I can get Nuxt.js to work this way.\n\nAny ideas at all where I'm going wrong?\n\nThanks.\n\n========================================\n\nTop Answer:\nThe accepted answer (while correct) was too short for me to understand it and use it correctly, so I wrote a more detailed version. I was looking for a way to use plotly.js + nuxt.js, but it should be the same as the OP's problem of Choice.js + nuxt.js.\n\n**MyComponent.vue**\n\n```\n\n \n \n \n \n \n\nexport default {\n components: {\n // this different (webpack) import did the trick together with :\n 'my-chart': () => import('@/components/MyChart.vue')\n }\n}\n\n```\n\n**MyChart.vue**\n\n```\n\n \n \n\nimport Plotly from 'plotly.js/dist/plotly'\nexport default {\n mounted () {\n // exists only on client:\n console.log(Plotly)\n },\n components: {\n Plotly\n }\n}\n\n```\n\nUpdate: There is `` tag instead of ` in Nuxt v>2.9.0, see @Kaz's comment.\n\n========================================\n\nCode:\n```text\nbuild: {\n vendor: ['choices.js']\n}\n```\n\n```text\n<script>\nimport Choices from 'choices.js'\n\nexport default {\n name: 'CountrySelect',\n created () {\n console.log(this.$refs, Choices)\n const choices = new Choices(this.$refs.select)\n console.log(choices)\n }\n}\n</script>\n```\n\n```text\n<template>\n <div>\n <no-ssr placeholder=\"loading...\">\n <your-component>\n </no-ssr>\n </div>\n</template>\n```\n\n```text\n<template>\n <div>\n <client-only placeholder=\"loading...\">\n <your-component>\n </client-only>\n </div>\n</template>\n```\n\n```text\nwindow.document\n```\n\n```text\nwindow.document\n```\n\n```text\n<no-ssr>\n```\n\n```text\n<client-only>\n```\n\n```text\n<no-ssr>\n```\n\n```text\n<script>\nimport Choices from 'choices.js'\n\nexport default {\n name: 'CountrySelect',\n created () {\n if(process.client) {\n console.log(this.$refs, Choices)\n const choices = new Choices(this.$refs.select)\n console.log(choices)\n }\n }\n}\n</script>\n```\n\n```text\n<template>\n <div>\n <client-only>\n <my-chart></my-chart>\n </client-only>\n </div>\n</template>\n<script>\nexport default {\n components: {\n // this different (webpack) import did the trick together with <no-ssr>:\n 'my-chart': () => import('@/components/MyChart.vue')\n }\n}\n</script>\n```\n\n```text\n<template>\n <div>\n </div>\n</template>\n<script>\nimport Plotly from 'plotly.js/dist/plotly'\nexport default {\n mounted () {\n // exists only on client:\n console.log(Plotly)\n },\n components: {\n Plotly\n }\n}\n</script>\n```\n\n```text\n<client-only>\n```\n\n```text\n<no-ssr>\n```\n\n```text\n<client-only>\n <chart-component></chart-component>\n </client-only>\n```\n\n```js\nplugins: [\n { src: '~/plugins/choices.js' } // both sides\n { src: '~/plugins/client-only.js', mode: 'client' }, // only on client side\n { src: '~/plugins/server-only.js', mode: 'server' } // only on server side\n],\n```\n\n```text\nimport Vue from 'vue'\nimport VueStarRating from 'vue-star-rating'\n\nVue.component('vue-star-rating', VueStarRating); //<--- the name you used to register the plugin will be the same to use when in the component (vue-star-rating)\n```\n\n```text\nplugins: [{\n src: '~/plugins/vue-star-rating', // <--- file name\n mode: 'client'\n },\n //you can simply keep adding plugins like this:\n {\n src: '~/plugins/vue-slider-component',\n mode: 'client'\n }]\n```\n\n```text\n<client-only placeholder=\"loading...\">\n <vue-star-rating />\n</client-only>\n```\n\n```text\nvue-star-rating\n```\n\n```text\njs\n```\n\n```text\nvue-star-rating.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n<client-only>\n```\n\n```text\nvue-star-rating\n```\n\n```text\nplugins: [\n { src: '~/plugins/lightgallery.js', mode: 'client' }\n ],\n```\n\n```text\nimport Vue from 'vue'\nimport lightGallery from 'lightgallery.js/dist/js/lightgallery.min.js'\nimport 'lightgallery.js/dist/css/lightgallery.min.css'\n\nVue.use(lightGallery)\n```\n\n```text\n<template>\n <section class=\"image-gallery-container\">\n <div class=\"image-gallery-row\">\n <div\n ref=\"lightgallery\"\n class=\"image-gallery\"\n >\n <a\n v-for=\"image in group.images\"\n :key=\"image.mediaItemUrl\"\n :href=\"image.mediaItemUrl\"\n class=\"image-gallery__link\"\n >\n <img\n :src=\"image.sourceUrl\"\n :alt=\"image.altText\"\n class=\"image-gallery__image\"\n >\n </a>\n </div>\n </div>\n </section>\n</template>\n\n<script>\nexport default {\n name: 'ImageGallery',\n props: {\n group: {\n type: Object,\n required: true\n }\n },\n mounted() {\n let vm = this;\n\n if (this.group && vm.$refs.lightgallery !== 'undefined') {\n window.lightGallery(this.$refs.lightgallery, {\n cssEasing: 'cubic-bezier(0.680, -0.550, 0.265, 1.550)'\n });\n }\n }\n}\n</script>\n```\n\n```text\nconst d = typeof document === 'undefined' ? null : document\n```\n\n```js\nexport default {\n plugins: [\n '~/plugins/foo.client.js', // only in client side\n '~/plugins/bar.server.js', // only in server side\n '~/plugins/baz.js' // both client & server\n ]\n}\n```\n\n```text\nprocess.client\n```\n\n```text\n<client-only>\n```\n\n```text\nconst Ace = await import('ace-builds/src-noconflict/ace')\n```\n\n```text\ncomponents: { [process.client && 'VueEditor']: () => import('vue2-editor') }\n```\n\n```text\ndocument\n```\n\n```text\ncreated\n```\n\n```text\ncreated\n```\n\n```text\nmounted\n```\n\n========================================\n\nComments:\n- Thanks for this! Any idea how I could then output the element itself with SSR? As in, some JS needs to act on the client-side for a select list, but I'd still like to render the actual select list on the server.\n- How should the `` file look like? I have YourComponent.vue: ` import Plotly from 'plotly.js/dist/plotly' export default {} ` and it still ends with `document is not defined`\n- nuxtjs.org/guide/plugins#client-side-only `plugins: [ { src: '~/plugins/vue-notifications', mode: 'client' } ]` I would suggest this for those that are still struggling like I was to find a solution.\n- @JeffBluemel Your solution saved my day. I had to add this in my nuxt.config.js `{ src: '~/plugins/vue-izitoast', mode: 'client' }`\n- @JeffBluemel, Yours is the only solution worked for me after banging my head for half a day for a solution. I literally tried everything I could find on the internet.\n- If you are using a Nuxt version of > **v2.9.0**, use `` instead of ``. As `` is deprecated from Nuxt **v2.9.0**\n- This worked in my case when I was using evodiaaut.github.io/vue-marquee-text-component. Mostly no-ssr tag is enough but with this library, I had to import the way as mentioned above. @michal. Can you explain the reason behind this kind of import\n- @BaldeepSinghKwatra unfortunately, I came to this solution by trial/error, as far as I remember\n- If you are using a Nuxt version of > **v2.9.0**, use `` instead of ``. As `` is deprecated from Nuxt **v2.9.0**\n- `` is deprecated from Nuxt version **v2.9.0**.\n- now the syntax looks like this { src: '~/plugins/client-only.js', mode: 'client' }, // only on client side { src: '~/plugins/server-only.js', mode: 'server' } // only on server side\n- Thanks for the pointer @ArifIkhsanudin I just update the Answer.\n- I'm not sure this will solve the problem.","metadata":{"transformedAt":"2026-08-18T18:33:07.830Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":405,"estimatedTokens":2030}}30{"id":"stack-63731076","source":"stackoverflow","questionId":63731076,"title":"What do the hash marks (#) mean in Vue?","tags":["javascript","vue.js","vuetify.js","nuxt.js"],"text":"Title: What do the hash marks (#) mean in Vue?\nTags: javascript, vue.js, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI rather new to Vue, and cannot figure out exactly what the hash symbol `#` (i.e. `#item.active`) means in Vue.\n\nAs the hash symbol is a difficult term to search on the web!\n\n```\n\n \n mdi-minus\n mdi-close\n \n\n```\n\nThank you in advance for any help!\n\n========================================\n\nCode:\n```html\n<template #item.active=\"{ value }\">\n <div :aria-label=\"String(value)\" class=\"text-center\">\n <v-icon v-if=\"value === null\">mdi-minus</v-icon>\n <v-icon v-else color=\"red\">mdi-close</v-icon>\n </div>\n</template>\n```\n\n```text\n#\n```\n\n```text\n#item.active\n```\n\n```text\n#\n```\n\n```text\nv-slot\n```\n\n```text\n<template>\n```\n\n```text\nv-slot\n```\n\n========================================\n\nComments:\n- It's shorthand for the `v-slot` attribute.\n- Really? Thanks Edric!\n- \"Googling a # isn't an easy thing to do.\" I agree, thanks for the question !\n- Drop me an upvote then!\n- \"Googling a # isn't an easy thing to do\" -> Googling for this was really a nightmare actually. Even after reading this, I still can't find where the docs mention this, apart from saying \"shorthand: #\" next to v-slot... Many thanks for asking the answer and wording it in such a way that it was searchable\n- Yeah the vue docs kinda suck really.\n- Thank you sir! I will mark you as the answer. Of course now that i know what to google i find it everywhere!","metadata":{"transformedAt":"2026-08-18T18:33:07.831Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":66,"estimatedTokens":364}}31{"id":"stack-46396291","source":"stackoverflow","questionId":46396291,"title":"How to set data into nuxt.js nuxt-link?","tags":["javascript","vue.js","vue-component","nuxt.js"],"text":"Title: How to set data into nuxt.js nuxt-link?\nTags: javascript, vue.js, vue-component, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to pass data into nuxt-link but nuxt-link is just returning a 404 error when I click on the link. It doesn't seem to be getting and loading the file....\n\nThe second 2 links that use :href and hardcoding works\n\n```\n\n \n\n### Nuxt View Menu\n\n \n\n### Vue View Menu\n\n \n\n### HardCode View Menu\n\nexport default {\n layout: 'default',\n data () {\n return {\n filePath: 'files/officialMenu.pdf'\n }\n }\n}\n\n```\n\n========================================\n\nTop Answer:\nIf you use post way to send data another route in vuejs or nuxtjs.\nHere, if route name is = /user\nSo, you have to write the following nuxt-link\n\n```\nUser\n```\n\nand for receive data next componet, means on \"/user\" route you have to write inside created or any other place and check console.\n\n```\ncreated() {\n console.log(this.$route.params)\n console.log(this.$route.params.userId)\n console.log(this.$nuxt._route.params)\n console.log(this.$nuxt._route.params.userId)\n}\n```\n\n========================================================\nif you use Get way to send data another route in vuejs or nuxtjs.\nHere, if route name is = /register\nso, you have to write the following nuxt-link\n\n```\nRegister\n```\n\nand for receive data next componet, means on \"/register\" route you have to write inside created or any other place and check console.\n\n```\ncreated() {\n console.log(this.$route.query)\n console.log(this.$route.query.plan)\n console.log(this.$nuxt._route.query)\n console.log(this.$nuxt._route.query.plan)\n}\n```\n\n### Now, you can use this data anywhere like data, mounted, method etc...\n\nHow to define route name?????\n\nAdd the following code into \"nuxt.config.js\" file to add route name.\n\n```\nrouter: {\n base: '/',\n extendRoutes(routes, resolve) {\n routes.push({\n name: 'user',\n path: '/user',\n component: resolve(__dirname, 'pages/user.vue')\n })\n }\n },\n```\n\nHere,\n\n- Name property is the name of route that you want to provide as route name.\n\n- In Path property you have to provide route path.\n\n- Component property is the component path of that component need to load in this route.\n\n========================================\n\nCode:\n```html\n<template>\n <h2 class=\"subtitle\"><nuxt-link :to=\"{path: filePath}\" exact>Nuxt View Menu</nuxt-link></h2>\n <h2 class=\"subtitle\"><a :href=\"filePath\">Vue View Menu</a></h2>\n <h2 class=\"subtitle\"><a href=\"files/officialMenu.pdf\">HardCode View Menu</a></h2>\n</template>\n\n<script>\nexport default {\n layout: 'default',\n data () {\n return {\n filePath: 'files/officialMenu.pdf'\n }\n }\n}\n</script>\n```\n\n```html\n<!-- named route -->\n<nuxt-link :to=\"{ name: 'user', params: { userId: 123 }}\">User</nuxt-link>\n\n<!-- with query, resulting in `/register?plan=private` -->\n<nuxt-link :to=\"{ path: 'register', query: { plan: 'private' }}\">Register</nuxt-link>\n```\n\n```text\n<nuxt-link :to=\"{ name: 'user', params: { userId: 123 }}\">User</nuxt-link>\n```\n\n```text\ncreated() {\n console.log(this.$route.params)\n console.log(this.$route.params.userId)\n console.log(this.$nuxt._route.params)\n console.log(this.$nuxt._route.params.userId)\n}\n```\n\n```text\n<nuxt-link :to=\"{ path: 'register', query: { plan: 'private' }}\">Register</nuxt-link>\n```\n\n```text\ncreated() {\n console.log(this.$route.query)\n console.log(this.$route.query.plan)\n console.log(this.$nuxt._route.query)\n console.log(this.$nuxt._route.query.plan)\n}\n```\n\n```text\nrouter: {\n base: '/',\n extendRoutes(routes, resolve) {\n routes.push({\n name: 'user',\n path: '/user',\n component: resolve(__dirname, 'pages/user.vue')\n })\n }\n },\n```\n\n```text\n<NuxtLink to=\"/files/officialMenu.pdf\" external>\n Nuxt View Menu\n </NuxtLink>\n```\n\n========================================\n\nComments:\n- I don't believe this is the case... I'm trying to pass the filePath into nuxt-link... no where does the documentation provide a way to pass a static asset path to the URL.\n- Ahh that case you could just use 2nd and 3rd one. Since when we use nuxt-link or router-link it should be something that in reach within the routes you defined.\n- Thanks for the commented example; that's what I needed to see.","metadata":{"transformedAt":"2026-08-18T18:33:07.831Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":184,"estimatedTokens":1062}}32{"id":"stack-52640587","source":"stackoverflow","questionId":52640587,"title":"Pass custom data to `$router.push()` in vue-router","tags":["javascript","vuejs2","vue-router","nuxt.js"],"text":"Title: Pass custom data to `$router.push()` in vue-router\nTags: javascript, vuejs2, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIs there a way to pass additional data to `$router.push()` that is not registered as param or query in the route's path. This will allow me to recognize on the next page that it has been accessed via programmatic navigation as there is no way to pass it via URL. Something like:\n\n```\nthis.$router.push({\n path: '/next-page', \n params: {...}, \n query: {...}, \n moreData: {foo: 1}\n})\n```\n\nAnd then in `/next-page`:\n\n```\nthis.$route.moreData.foo // 1\n```\n\nCurrently I am using the `$store` to handle `moreData`\n\n========================================\n\nTop Answer:\nIn my case I was using the name redirect, but couldn't receive the custom params because the target route had a redirect by path - in this case the provided params were lost.\n\nSo it was required to change from the 'path redirect' to the 'named redirect', but since 'path redirect' contained an additional data in the path, I now need to pass that data via the 'name redirect' as well using params.\n\nSo I ended up with a helper \"redirectByName\" function that preserves the params in this case:\n\nredirectByName.js\n\n```\n//redirects by preserving params\nexport default (name, params = {}) => {\n return (route) => ({\n ...route,\n name,\n params: {\n ...route.params,\n ...params\n }\n })\n}\n```\n\nAnd here is an example how to use it:\n\nmyRoutes.js\n\n```\nimport redirectByName from \"./redirectByName\";\n ...\n export default return [\n {\n path:'some/path',\n name: 'targetRouteName',\n redirect:redirectByName('redirectRouteName', {tab: 'general'}), //optional additional parameters for redirection\n }, \n {\n path:'some/path/:tab', \n name: 'redirectRouteName'\n }]\n```\n\nThe `redirectByName` basically takes the target `route` object to preserve all the passed data, overrides its `name` parameter with the provided one and merges the params. Then it passes the final route object back to accomplish the redirect.\n\n========================================\n\nCode:\n```text\nthis.$router.push({\n path: '/next-page', \n params: {...}, \n query: {...}, \n moreData: {foo: 1}\n})\n```\n\n```text\nthis.$route.moreData.foo // 1\n```\n\n```text\n$router.push()\n```\n\n```text\n/next-page\n```\n\n```text\n$store\n```\n\n```text\nmoreData\n```\n\n```text\n$router.push({name: 'next-page', params: {foo: 1}})\n\n// in /next-page\n$route.params.foo // 1\n```\n\n```text\nparams\n```\n\n```text\npath\n```\n\n```text\nname\n```\n\n```text\nparams\n```\n\n```text\nname\n```\n\n```text\n//redirects by preserving params\nexport default (name, params = {}) => {\n return (route) => ({\n ...route,\n name,\n params: {\n ...route.params,\n ...params\n }\n })\n}\n```\n\n```text\nimport redirectByName from \"./redirectByName\";\n ...\n export default return [\n {\n path:'some/path',\n name: 'targetRouteName',\n redirect:redirectByName('redirectRouteName', {tab: 'general'}), //optional additional parameters for redirection\n }, \n {\n path:'some/path/:tab', \n name: 'redirectRouteName'\n }]\n```\n\n```text\nredirectByName\n```\n\n```text\nroute\n```\n\n```text\nname\n```\n\n========================================\n\nComments:\n- Can you try `meta` instead of `moreData`?\n- I tried `.push({meta: {foo: 1}})` but after the transition `$route.meta` is empty object ( `{}`)\n- And why cant you make it via a query?\n- Cuz the parameter is private\n- @slim, And what is the url for this route name? Is data passed through URL?\n- @AkshayDeshmukh No, its not passed through the url but is accessible via `$route.params`. The url is that one that corresponds to the route with that name. There should be only one route with that name as it is considered a unique identifier. Of course if I navigate to a route `{ name: 'users-id', params: {id: 1}}` that has a `path = '/users/:id'` the id will be present in the url as well.\n- Phew, what a frustrating bug of theirs that params only work with named route, this took me forever to figure out, thanks!\n- @Kevin its not really a bug. They simply use single source of truth. If you pass `path` they must extract the params from there. Otherwise they look for a `params` object :) Though, they should probably always try to merge both with a higher priority on `path` in case of name collision.\n- Also please be aware that if you have multiple languages you need to use `localePath` function or any function language aware as the route names are generated with a suffix.","metadata":{"transformedAt":"2026-08-18T18:33:07.831Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":182,"estimatedTokens":1134}}33{"id":"stack-52573962","source":"stackoverflow","questionId":52573962,"title":"Vuetify - How to trigger method when clear a v-text-field","tags":["vue.js","vuetify.js","nuxt.js"],"text":"Title: Vuetify - How to trigger method when clear a v-text-field\nTags: vue.js, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIs there a way to call a method while clearing a text-field with Vuetify?\n\n```\n\n```\n\n```\nonClear() {\n doSomethingHere()\n}\n```\n\n========================================\n\nTop Answer:\nUse the `clear-icon-cb` prop. This allows you to use a custom callback function when the clear icon when clicked.\n\n```\n\nonClearClicked () {\n // do something\n}\n```\n\n========================================\n\nCode:\n```html\n<v-text-field\n class=\"mt-2 mb-0\"\n clearable\n solo\n v-model=\"searchQuery\"\n append-icon=\"search\"\n @click:append-outer=\"searchCos\"\n label=\"Nom de compagnies ou mots-clés\">\n</v-text-field>\n```\n\n```js\nonClear() {\n doSomethingHere()\n}\n```\n\n```text\n@click:clear=\"()\"\n```\n\n```text\n<v-text-field\n clearable\n :clear-icon-cb=\"onClearClicked\">\n</v-text-field>\n\nonClearClicked () {\n // do something\n}\n```\n\n```text\nclear-icon-cb\n```\n\n```text\n<v-text-field\n ref=\"inputRef\"\n class=\"mt-2 mb-0\"\n clearable\n .....\n >\n</v-text-field>\n<v-btn text @click=\"clearInput\">clear</v-btn>\n\n<script>\n export default {\n ......\n methods:{\n .....\n clearInput() {\n this.$refs.inputRef.clearableCallback()\n }\n }\n\n }\n```\n\n```text\n<v-text-field v-model=\"search\" @input=\"sendSearch\" clearable hide-details></v-text-field>\n```\n\n```text\nmethods: {\n sendSearch(){\n this.$emit(\"send-search\",this.search);\n }\n}\n```\n\n```html\n<v-text-field\n v-model=\"myValue\"\n append-icon=\"mdi-close\"\n @clear:append=\"myValue = 1\">\n</v-text-field>\n```\n\n```html\n<v-text-field ref=\"inputRef\"></v-text-field>\n<v-btn @click=\"clearInput\">clear</v-btn>\n\n<script>\n export default {\n methods:{\n clearInput() {\n this.$refs.inputRef.reset()\n }\n }\n }\n</script>\n```\n\n========================================\n\nComments:\n- Is there anyway to prevent the clearing of the text. Like if I want to add a confirmation for the user prior to clearing the text? Is there an 'event' I can capture and then add preventDefault() or something like that?\n- :clear-icon-cb is now depreciated. now use @click:clear\n- This the best answer in my opinion.\n- Best way to do it! But use reset() instead of clearableCallback()","metadata":{"transformedAt":"2026-08-18T18:33:07.831Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":134,"estimatedTokens":571}}34{"id":"stack-54472617","source":"stackoverflow","questionId":54472617,"title":"How can I turn off SSR for only certain pages in Nuxt.js to use them as SPA application?","tags":["vue.js","nuxt.js","server-side-rendering"],"text":"Title: How can I turn off SSR for only certain pages in Nuxt.js to use them as SPA application?\nTags: vue.js, nuxt.js, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nI want to develop an application with Nuxt.js that uses SSR for only certain pages (like artist page user page), so the pages without SSR will be used like an SPA. Is it possible to do it using Nuxt.js?\n\n========================================\n\nTop Answer:\nYou could do that via server middleware. Add following file under `~/server-middleware/check-spa.js`, for example. Do not use `middleware` directory as it is for route middleware and gets copied to the client code.\n\n```\nexport default function(req, res, next) {\n const paths = ['/', '/a']\n\n if (paths.includes(req.originalUrl)) {\n // Will trigger the \"traditional SPA mode\"\n res.spa = true\n }\n // Don't forget to call next in all cases!\n // Otherwise, your app will be stuck forever :|\n next()\n}\n```\n\nThen, in `nuxt.config.js` enable serverMiddleware like this\n\n```\nserverMiddleware: ['~/server-middleware/check-spa']\n```\n\nMore info here: https://nuxtjs.org/docs/configuration-glossary/configuration-servermiddleware/\n\nhttps://blog.lichter.io/posts/nuxt-dynamic-ssr-spa-handling/\n\n========================================\n\nCode:\n```text\n.client\n```\n\n```text\n.server\n```\n\n```text\ncomments.client.vue\n```\n\n```text\nartist.server.vue\n```\n\n```text\n<client-only></client-only>\n```\n\n```text\n<no-ssr></no-ssr>\n```\n\n```js\nexport default function(req, res, next) {\n const paths = ['/', '/a']\n\n if (paths.includes(req.originalUrl)) {\n // Will trigger the \"traditional SPA mode\"\n res.spa = true\n }\n // Don't forget to call next in all cases!\n // Otherwise, your app will be stuck forever :|\n next()\n}\n```\n\n```js\nserverMiddleware: ['~/server-middleware/check-spa']\n```\n\n```text\n~/server-middleware/check-spa.js\n```\n\n```text\nmiddleware\n```\n\n```text\nnuxt.config.js\n```\n\n```html\n<template>\n <div>\n <sidebar />\n <client-only placeholder=\"Loading...\">\n <!-- this component will only be rendered on client-side -->\n <comments />\n </client-only>\n </div>\n</template>\n```\n\n```text\n<client-only>\n```\n\n```text\n<no-ssr>\n```\n\n```text\nLoading...\n```\n\n```text\n<client-only>\n```\n\n```text\n<client-only>\n```\n\n```text\nplugins:[\n { src: your-plugin, ssr: false }\n]\n```\n\n```text\n<no-ssr> <your-component /> </no-ssr>\n```\n\n```text\n<client-only> </client-only>\n```\n\n```text\nnuxt.connfig\n```\n\n```text\nexport default defineNuxtConfig({\n routeRules: {\n // Static page generated on-demand, revalidates in background\n '/blog/**': { swr: true },\n // Static page generated on-demand once\n '/articles/**': { static: true },\n // Set custom headers matching paths\n '/_nuxt/**': { headers: { 'cache-control': 's-maxage=0' } },\n // Render these routes with SPA\n '/admin/**': { ssr: false },\n // Add cors headers\n '/api/v1/**': { cors: true },\n // Add redirect headers\n '/old-page': { redirect: '/new-page' },\n '/old-page2': { redirect: { to: '/new-page', statusCode: 302 } }\n }\n})\n```\n\n========================================\n\nComments:\n- nuxtjs.org/api/components-no-ssr#the-lt-no-ssr-gt-component\n- As one of the answers below says: If your Nuxt version >v2.9.0, then use `` instead of ``\n- The question concerns Nuxt pages, not component templates\n- This is set the whole application to SPA. nuxtjs.org/docs/2.x/configuration-glossary/configuration-ssr","metadata":{"transformedAt":"2026-08-18T18:33:07.831Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":170,"estimatedTokens":855}}35{"id":"stack-52452501","source":"stackoverflow","questionId":52452501,"title":"How to add a polyfill to nuxt 2.0?","tags":["nuxt.js","nuxt-edge"],"text":"Title: How to add a polyfill to nuxt 2.0?\nTags: nuxt.js, nuxt-edge\nSource: Stack Overflow\n\nQuestion:\nIn Nuxt `1.4.2`, I had the following in my `nuxt.config.js`:\n\n```\nbuild: {\n vendor: ['babel-polyfill'],\n babel: {\n presets: [\n ['vue-app', {\n useBuiltIns: true,\n targets: { ie: 11, uglify: true },\n },\n ],\n ],\n },\n},\n```\n\nIt seems that all of this is broken in Nuxt `2.0`. At a minimum I'm looking to polyfill enough to get IE 11 working. Here's what I've tried:\n\n### Using vendor as I used to\n\nRemoving `build.babel` allowed the build process to work:\n\n```\nbuild: {\n vendor: ['babel-polyfill'],\n},\n```\n\nBut I *think* `build.vendor` is just ignored now, so this seems to do nothing.\n\n### Using polyfill.io\n\nI tried adding:\n\n```\nscript: [\n { src: 'https://cdn.polyfill.io/v2/polyfill.min.js' },\n],\n```\n\nto my `head`, along with:\n\n```\nrender: {\n resourceHints: false,\n},\n```\n\nto disable the `preload` hints (I'm unsure if this matters). This results in a page which looks correct - `polyfill.min.js` is loaded before all other scripts. Somehow, when I test on ie11, `Object.entries` is undefined and the page explodes.\n\n========================================\n\nTop Answer:\nI tried all the above approaches and nothing at all worked. However, I found that I could get my code to work with IE11 by creating a plugin and adding it to nuxt.config.js as follows:\n\n// nuxt.config.js\n\n```\nplugins: [\n { src: '~/plugins/polyfills', mode: 'client' },\n ],\n```\n\n// plugins/polyfills.js\n\n```\nimport 'core-js/fn/object/entries'\nimport 'core-js/fn/array/includes'\nimport 'core-js/fn/array/find'\nimport 'core-js/fn/array/from'\nimport 'core-js/es6/promise'\nimport 'core-js/fn/object/assign'\nimport 'core-js/es6/symbol'\nimport 'whatwg-fetch'\n```\n\nI removed any special babel config. That's all it took. I know this means my code will always run the polyfills, but there are no 3rd party dependencies (polyfill.io for example). You may edit the list of required polyfills as needed. Hope this helps someone!\n\n========================================\n\nCode:\n```text\nbuild: {\n vendor: ['babel-polyfill'],\n babel: {\n presets: [\n ['vue-app', {\n useBuiltIns: true,\n targets: { ie: 11, uglify: true },\n },\n ],\n ],\n },\n},\n```\n\n```text\nbuild: {\n vendor: ['babel-polyfill'],\n},\n```\n\n```text\nscript: [\n { src: 'https://cdn.polyfill.io/v2/polyfill.min.js' },\n],\n```\n\n```text\nrender: {\n resourceHints: false,\n},\n```\n\n```text\n1.4.2\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n2.0\n```\n\n```text\nbuild.babel\n```\n\n```text\nbuild.vendor\n```\n\n```text\nhead\n```\n\n```text\npreload\n```\n\n```text\npolyfill.min.js\n```\n\n```text\nObject.entries\n```\n\n```js\nconst features = [\n 'fetch',\n 'Object.entries',\n 'IntersectionObserver',\n].join('%2C');\n\nhead: {\n script: [\n { src: `https://polyfill.io/v3/polyfill.min.js?features=${features}`, body: true },\n ],\n},\n```\n\n```text\n2.2.0\n```\n\n```text\nbuild.vendor\n```\n\n```text\nbuild.babel\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nbuild.vendor\n```\n\n```text\nbuild.babel\n```\n\n```text\nvue-app\n```\n\n```text\n@nuxtjs/apollo\n```\n\n```text\nvue-apollo\n```\n\n```text\napollo-boost\n```\n\n```text\ncore-js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nbody: true\n```\n\n```text\nhead\n```\n\n```text\nIntersectionObserver\n```\n\n```text\ndefault\n```\n\n```text\ncore-js\n```\n\n```text\ncore-js\n```\n\n```text\ndefault\n```\n\n```text\npolyfill.io\n```\n\n```text\npolyfill.io\n```\n\n```text\nnpm install nuxt-polyfill\n```\n\n```text\nexport default {\n\n // Configure polyfills:\n polyfill: {\n features: [\n /* \n Feature without detect:\n\n Note: \n This is not recommended for most polyfills\n because the polyfill will always be loaded, parsed and executed.\n */\n {\n require: 'url-polyfill' // NPM package or require path of file\n },\n\n /* \n Feature with detect:\n\n Detection is better because the polyfill will not be \n loaded, parsed and executed if it's not necessary.\n */\n {\n require: 'intersection-observer',\n detect: () => 'IntersectionObserver' in window,\n },\n\n /*\n Feature with detect & install:\n\n Some polyfills require a installation step\n Hence you could supply a install function which accepts the require result\n */\n {\n require: 'smoothscroll-polyfill',\n\n // Detection found in source: https://github.com/iamdustan/smoothscroll/blob/master/src/smoothscroll.js\n detect: () => 'scrollBehavior' in document.documentElement.style && window.__forceSmoothScrollPolyfill__ !== true,\n\n // Optional install function called client side after the package is required:\n install: (smoothscroll) => smoothscroll.polyfill()\n }\n ]\n },\n\n // Add it to the modules section:\n modules: [\n 'nuxt-polyfill',\n ]\n}\n```\n\n```text\nplugins: [\n { src: '~/plugins/polyfills', mode: 'client' },\n ],\n```\n\n```text\nimport 'core-js/fn/object/entries'\nimport 'core-js/fn/array/includes'\nimport 'core-js/fn/array/find'\nimport 'core-js/fn/array/from'\nimport 'core-js/es6/promise'\nimport 'core-js/fn/object/assign'\nimport 'core-js/es6/symbol'\nimport 'whatwg-fetch'\n```\n\n```text\nbuild: { transpile: ['vue-cli-plugin-apollo'] }\n```\n\n```text\nnuxt 2.x\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- Try to remove babel from build config at all. It should work automatically\n- @Aldarund thanks - I tried that as well. I can see (via build -a) that `core-js` is included, but I still see the same errors when testing. I wonder if `core-js` just isn't being hoisted properly in the build. But even if that were true, I don't understand why `polyfill.io` would fail.\n- Can't you just require the polyfil in a plugin?\n- @Imre_G I believe the polyfill is actually being included, and it works fine in a simple app. Once packages are included (in my case @nuxtjs/apollo), then it seems to break. When I have an update from the nuxt devs, I'll post my findings here.\n- Thanks for the detailed explanation. Hopefully the core team adresses this soon\n- @Merc This is a high priority issue for me. As I learn more, I'll be sure to add it here.\n- @Merc I've added some improvements based on continued experimentation. Please read the latest version of step 3 in my answer.\n- For anyone using this options, I needed enter a detect method (in my case for Array.from: `detect: () => !Array.from`) for it to work, otherwise it wasn't loaded at all I think, or it assumed the native implementation was there on the server side so it didn't include it on the client side.\n- @Lumocra Could you your whole solution ? We cannot seem to be able to make it work for `Array.from`\n- @Lumocra @Scriptodude If you do not supply a detect function, the polyfill will always be included and ran. But keep in mind that this happens when the first plugins start to run. So you need to make sure you only use the polyfill in `default exported functions` of plugins, `computed properties` or `methods` of components, any `getter, mutation or action` of vuex stores, etc. You can't just use it in the global path of the script because it's not polyfilled at that time.\n- @Scriptodude In nuxt.config.js: `polyfill: { features: [ ..., { require: 'array-from', detect: () => !Array.from }, ... ] },`\n- But I still have to manually add each polyfill? It can't detect which are needed based on the features in my code?\n- @Oli Unfortunately that's not possible in a language which is as dynamic as JavaScript. Fortunately though, you only have to set this up once!\n- @Tim Can you an example using nuxt-polyfill with a bundle from polyfill.io as a package and not a URL ???","metadata":{"transformedAt":"2026-08-18T18:33:07.831Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":42,"totalLines":357,"estimatedTokens":1965}}36{"id":"stack-51900326","source":"stackoverflow","questionId":51900326,"title":"How to get axios baseUrl in nuxt?","tags":["vue.js","axios","nuxt.js"],"text":"Title: How to get axios baseUrl in nuxt?\nTags: vue.js, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have axios module in my Nuxt.js project.\n\nI also set up my baseUrl (for API) in `localhost:4040/api` while my client is running on port 3000.\n\nWhen I fetch image data in the API, it returns a relative path to the api server which is like '/upload/1.png'\n\n`{\n \"src\":\"/upload/1.png\"\n}`\n\nSo, I need to get the axios baseUrl and concat it with it to make full path to the image.\n\nIs there any way to do it other than hardcoding it?\n\n========================================\n\nTop Answer:\nYou can access axios config like this to get your api base URL:\n\n```\nthis.$axios.defaults.baseURL\n```\n\n========================================\n\nCode:\n```text\nlocalhost:4040/api\n```\n\n```text\n{\n \"src\":\"/upload/1.png\"\n}\n```\n\n```text\naxios: {\n baseURL:\"localhost:4040/api/\"\n}\n```\n\n```text\n:src=\"`${$axios.defaults.baseURL}upload/1.png`\"\n```\n\n```text\nthis.$axios.defaults.baseURL\n```\n\n```text\naxios: {\n baseURL: 'http: // localhost: 8080/api'\n }\n```\n\n```text\nexport const actions = {\n // nuxt server Init only works on store/index.js\n async nuxtServerInit ({dispatch}) {\n let response = await dispatch ('member / list', {page: 1});\n console.log (response);\n }\n}\n```\n\n```text\nasync list ({commit}, payload) {\n return await this. $ axios. $ post ('/ user / list', payload) .then ((response) => {\n commit ('fetchSuccess', response);\n return response;\n })\n .catch (error => {\n return error.response.data;\n });\n },\n```\n\n```text\naxios: {\n baseURL: 'http://localhost:9020/api'\n },\n```\n\n```text\naxios: {\n baseURL: '/'\n}\n```\n\n```text\nlocalhost:3000/api\n```\n\n```text\nany-domain.com/api\n```\n\n```text\naxios: {\n baseURL: \"http://localhost:8000/api/\",\n},\n```\n\n```text\neachpost: {\n ....\n user: {\n ....,\n avatar: 'users/default.png'\n }\n}\n```\n\n```text\n<img :src=\"`${$axios.defaults.baseURL.slice(0,22)}storage/${eachPost.user.avatar}`\" :alt=\"`${eachPost.user.name}`\">\n```\n\n```text\nwindow.location.origin\n```\n\n========================================\n\nComments:\n- what do you want to do with `\"src\":\"/upload/1.png\"`\n- @Helpinghand I want to display the image, since they run on different port (the api and the client), I can't use relative path\n- upvoted, very curious question if axios already has a baseUrl by default, why would you set it explicitly in nuxt config.js i have seen almost every piece of nuxt example do this\n- This should have more upvotes. Handling baseUrl in nuxt at runtime is tedious indeed.\n- For me it calls `http:/api/user` when I try that >:-(","metadata":{"transformedAt":"2026-08-18T18:33:07.831Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":135,"estimatedTokens":676}}37{"id":"stack-63336570","source":"stackoverflow","questionId":63336570,"title":"What's the real difference between target: 'static' and target: 'server' in Nuxt 2.14 universal mode?","tags":["vue.js","static","nuxt.js","netlify","jamstack"],"text":"Title: What's the real difference between target: 'static' and target: 'server' in Nuxt 2.14 universal mode?\nTags: vue.js, static, nuxt.js, netlify, jamstack\nSource: Stack Overflow\n\nQuestion:\nin the latest version of Nuxt (2.14) they introduced an optimization for building the app when no code is changed (for drastically improve build times).\n\nI make websites in jamstack, deploy on netlify with `nuxt generate` and, until now, with `target: 'server'`. I tried the new `target: 'static'` in order to take advantage of this new feature, but my code won't build as it seems that in this mode the app can't access to `this.$route` in order to generate dynamic pages.\n\nSo, my question is: how is this different from each other? When I switch `target` to what I have to pay attention?\n\n========================================\n\nTop Answer:\ntarget:static\ntarget:server\n\nssr:true (universal)\nSSG(pure static site pages generated at build time)), can be deployed in storage service like s3. Even API data is prefetched and cached\nSSR(With server populating the template at each request), deployed to a compute service like GCP Cloud run\n\nssr:false (spa)\nSPA bundle/CSR (client side output: static spa with js updating each web page), can be deployed in storage service like s3 and CloudFront\nMixed(Nuxt will not fully render the HTML for each page - leaving that task to the browser. ) deployed to a compute service like GCP Cloud run\n\nRight now, in a project I work in, we use target:server, ssr:false, the mixed one. We disable ssr because we wanna offload the work to client side. We still use server cause we need the flexibility to update the website anytime. **I don't agree with @Martin Makarsky regarding it is client side navigation.** The only client side navigation should be SPA. target:server, ssr:false is like a mixed mode, combing the benefits of lower response and flexibility. When deploy,\n\n- nuxt build ( rendering-on-the-fly and built into production-ready bundle)\n\n- nuxt start (start the server)\n\nAs for ssg, ssr and spa, I think there are a lot of docs explaining them.\n\n**SSG** is purely static website with even API call cached. The typical framework of SSG is Gatsby.js.\n\n**With SSR,** When a user visits a specific route, the Node.js server will quickly fetch the data, render it, and send it as a static HTML page to the client. Soon after, the application gets hydrated and becomes a single page application and SSR is no longer required\n\n**SPA** is under the category of CSR(Client Side Rendering). It is slow for the initial js bundle downloading and not friendly to SEO\nGood thing about it is Time to Interactive (TTI)\n\nI have only used the target:server, ssr:false. For other combinations, it is based on my research and past experience. If there is any error, welcome to update my answer!!\n\n**References:**\n\n- https://nuxtjs.org/announcements/going-full-static/#current-issues\n\n- https://fauna.com/blog/comparing-spas-to-ssg-and-ssr\n\n- https://nuxtjs.org/docs/features/rendering-modes\n\n- https://nuxtjs.org/docs/features/deployment-targets/\n\n- https://nuxt.com/docs/getting-started/deployment\n\n========================================\n\nCode:\n```text\nnuxt generate\n```\n\n```text\ntarget: 'server'\n```\n\n```text\ntarget: 'static'\n```\n\n```text\nthis.$route\n```\n\n```text\ntarget\n```\n\n```js\nimport axios from 'axios'\n\nexport default {\n generate: {\n routes() {\n return axios.get('https://my-api/users').then(res => {\n return res.data.map(user => {\n return '/users/' + user.id\n })\n })\n }\n }\n}\n```\n\n```text\nmode: 'universal'\n```\n\n```text\nmode: 'spa'\n```\n\n```text\nssr: true\n```\n\n```text\nssr: false\n```\n\n```text\ntarget: 'static'\n```\n\n```text\nssr: true\n```\n\n```text\nmode: 'universal'\n```\n\n```text\nssr: true\n```\n\n```text\nssr: false\n```\n\n```text\nmode: 'spa'\n```\n\n```text\ntarget: 'static'\n```\n\n```text\ntarget\n```\n\n```text\ntarget: 'server'\n```\n\n```text\nmode\n```\n\n```text\nstatic\n```\n\n```text\nserver\n```\n\n```text\nuniversal\n```\n\n```text\nspa\n```\n\n```text\nuniversal\n```\n\n```text\nspa\n```\n\n```text\nserver\n```\n\n```text\nstatic\n```\n\n```text\n2.13\n```\n\n```text\nserver\n```\n\n```text\nstatic\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nstatic\n```\n\n```text\nuniversal\n```\n\n```text\nnuxt generate\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\ngenerate.routes\n```\n\n========================================\n\nComments:\n- is ssr: true or false?\n- Hey! I found your article! xD\n- I've been trying to get my head round target vs. rendering mode for some time now, as there seems (at least to me) significant overlap in implied concepts. This answer excellently sheds some light on this murkiness - thank you.\n- One thing I'm still struggling with is, how can target = static and ssr = true make any sense? Static = CDN hosting; SSR = server-side rendering. But there's no server-side rendering environment with CDN hosting - that would need a real server. Am I missing something?\n- From my understanding ssr: true only expresses \"at build time\" - where (and when) the document (DOM) is created - whether on client (SPA) or on the server at build time. TL;DR; it's just a static site - something like gatsby does - just bunch of html, css, and js bundled together and served by CND, that's it.\n- @MartinMakarsky @mitya yep, this is it: `ssr: true` + `target: static` is basically bundling the HTML files on the server but during the build time only. It'll be totally fine with a CDN because the build will already be done. If you choose `target: server`, it means that no server-side content will be generated ahead of time, hence you'll need to render it when you reach the website.\n- Btw, I realized a huge issue here. `ssr: false` and `target: static` is actually totally doable!\n- @kissu - feel free to update my answer or add a new one :)\n- Fantastic clarification! Maybe you could clarify a related post: stackoverflow.com/questions/71071684/… @kissu\n- With target=static and ssr=true, my SEO is dead :( I don't understand how to get good SEO and dynamic METAS :(\n- How to understand: Server+SSR:false/client side navigation SSR:False == Client side rendering. Then why do we still need a Server?\n- @MartinMakarsky I think ssr: true expresses \"rendering at server side\", when target is server, it renders when page is requested from client side. otherwise it render at *build time* when the target is static\n- I think ssr: true, static:true is equavelent of ssg, right?","metadata":{"transformedAt":"2026-08-18T18:33:07.831Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":39,"totalLines":241,"estimatedTokens":1606}}38{"id":"stack-47327119","source":"stackoverflow","questionId":47327119,"title":"How to listen to scroll events in vue nuxtjs?","tags":["vue.js","nuxt.js"],"text":"Title: How to listen to scroll events in vue nuxtjs?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI've search for a solution and came up with this code\n\n```\nmethods: {\n handleScroll () {\n console.log(window.scrollY)\n }\n},\ncreated () {\n window.addEventListener('scroll', this.handleScroll);\n},\ndestroyed () {\n window.removeEventListener('scroll', this.handleScroll);\n}\n```\n\nUnfortunately, this doesn't work for me. I also tried to change window to document.body. \n\nThe error message was `Window is not defined`\n\n========================================\n\nTop Answer:\nUsing `window` or any other browser-specific API in `created` or `beforeCreate` will lead to problems because platform-specific APIs like `document` or `window` are not available on the server (where SSR happens). Instead, move the logic from created into `beforeMount`. Leaving it in created and checking it via `process.browser` would work as well but is not as clean and can lead to confusion easily.\n\n```\nexport default {\n methods: {\n handleScroll () {\n // Your scroll handling here\n console.log(window.scrollY)\n }\n },\n beforeMount () {\n window.addEventListener('scroll', this.handleScroll)\n },\n beforeDestroy () {\n window.removeEventListener('scroll', this.handleScroll)\n }\n}\n```\n\nOnly `created` and `beforeCreate` are executed on both sides, server and client. Therefore you don't need guarding ifs in `beforeMount` or `beforeDestroy`.\n\nFurther read about ssr-ready Vue components\n\n========================================\n\nCode:\n```text\nmethods: {\n handleScroll () {\n console.log(window.scrollY)\n }\n},\ncreated () {\n window.addEventListener('scroll', this.handleScroll);\n},\ndestroyed () {\n window.removeEventListener('scroll', this.handleScroll);\n}\n```\n\n```text\nWindow is not defined\n```\n\n```text\nmethods: {\n handleScroll () {\n console.log(window.scrollY)\n }\n},\ncreated () {\n if (process.client) { \n window.addEventListener('scroll', this.handleScroll);\n }\n},\ndestroyed () {\n if (process.client) { \n window.removeEventListener('scroll', this.handleScroll);\n }\n}\n```\n\n```text\nwindow\n```\n\n```text\nprocess.client\n```\n\n```js\nexport default {\n methods: {\n handleScroll () {\n // Your scroll handling here\n console.log(window.scrollY)\n }\n },\n beforeMount () {\n window.addEventListener('scroll', this.handleScroll)\n },\n beforeDestroy () {\n window.removeEventListener('scroll', this.handleScroll)\n }\n}\n```\n\n```text\nwindow\n```\n\n```text\ncreated\n```\n\n```text\nbeforeCreate\n```\n\n```text\ndocument\n```\n\n```text\nwindow\n```\n\n```text\nbeforeMount\n```\n\n```text\nprocess.browser\n```\n\n```text\ncreated\n```\n\n```text\nbeforeCreate\n```\n\n```text\nbeforeMount\n```\n\n```text\nbeforeDestroy\n```\n\n```text\nbeforeMount () {\n window.addEventListener('wheel', this.handleScroll)\n },\n \n beforeDestroy() {\n window.removeEventListener('wheel', this.handleScroll);\n },\n```\n\n========================================\n\nComments:\n- I get an error: `Unexpected window in created nuxt/no-globals-in-created`\n- ^which comes from the nuxt eslint plugin 🙊🙌🏻 See my answer below.\n- Instead of `process.browser` now is `process.client`\n- The supplied link is dead. I think this is the place to link to now: v2.nuxt.com/docs/concepts/server-side-rendering","metadata":{"transformedAt":"2026-08-18T18:33:07.831Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":176,"estimatedTokens":816}}39{"id":"stack-68276674","source":"stackoverflow","questionId":68276674,"title":"Vercel Serverless Function has timed out error","tags":["server","nuxt.js","serverless","serverless-framework","vercel"],"text":"Title: Vercel Serverless Function has timed out error\nTags: server, nuxt.js, serverless, serverless-framework, vercel\nSource: Stack Overflow\n\nQuestion:\nI have a Nuxt.js server side website deployed on Vercel. I've noticed that, on some occasions, I get a `504: GATEWAY_TIMEOUT` error, with the code `FUNCTION_INVOCATION_TIMEOUT` and the message \"This Serverless Function has timed out\".\n\nWhy am I seeing this error?\n\nhttps://i.sstatic.net/oF1k0.jpg\n\n========================================\n\nTop Answer:\nAs of 7 September 2022, the Hobby plan on Vercel supports Serverless Function Execution Timeout for 10 seconds. Pro for 60 seconds. Enterprise for 900 seconds.\nhttps://i.sstatic.net/CfdNL.png\n\nHere is a link to their pricing plans: https://vercel.com/pricing\n\n========================================\n\nCode:\n```text\n504: GATEWAY_TIMEOUT\n```\n\n```text\nFUNCTION_INVOCATION_TIMEOUT\n```\n\n```text\nvercel.json\n```\n\n========================================\n\nComments:\n- Ran in to this issue today and I found that hosting a database in Australia and trying to use graphQL with a few hits to the database per request definitely causes the issue every time.\n- @DejanVasic I think I discovered the issue. I found that since I was using heroku on the free tier. The server sleeps after some due to inactivity, that is mostly when the issue arises. I also noticed in another project where the server is always active that I do not have that issue there.\n- makes total sense, since my API is on Heroku free plan, and it times out once in a while\n- I won't be surprised, they did it before (back when the company name was Zeit) when they deprecated API v1 without consulting their customers or giving them much time to upgrade their websites. Migration wasn't even easy and they had to drop using Docker. Many developers complained about having to migrate all of their websites on the planform to keep using their service.\n- Seems like Netlify is the way to go\n- useful link to deploy next 13 to AWS: reddit.com/r/nextjs/comments/yps1zh/comment/ivkvqpw/…\n- Those are the default timeouts now, but if are in the pro plan, you can extend the limit in your functions up to 5 minutes for execution time: vercel.com/changelog/…\n- Do you know of any FREE providers with a longer execution timeout?\n- Definitely depends on the framework, i think you can still use vercel but with slightly different set up\n- The last time i failed with vercel: ML model was too large. Here is freecodecamp article on alternatives freecodecamp.org/news/…\n- closest I could get to Iowa (the database location) was Cleveland (the Vercel region). Still no dice.\n- Heyy Lee is this still true?\n- Yes! This is still accurate.\n- I switched from netlify to vercel for this.\n- I’ve spent a few days now getting a nextjs 14 app using NextAuth v5 with google as an OAuth provider, a jwt strategy, persisting to mongodb working and when I deploy to production I cannot sign in on the hobby plan because it times out every time. This is really disappointing. I would be happy to pay maybe $5 a month to extend this one call but Vercel has made it impossible to run what I would consider a minimal app on the hobby plan.","metadata":{"transformedAt":"2026-08-18T18:33:07.831Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":52,"estimatedTokens":798}}40{"id":"stack-43040692","source":"stackoverflow","questionId":43040692,"title":"Global components in Vue (nuxt)","tags":["javascript","ecmascript-6","vuejs2","nuxt.js"],"text":"Title: Global components in Vue (nuxt)\nTags: javascript, ecmascript-6, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhile building a Vue application we re-use certain Vue components in every template. Our grid system exists out of .region, .layout, .grid, .column elements. All of them are separate Vue components (, ...). \n\nWe now end up doing this in every template: \n\n```\nimport BlMain from '~components/frame/main/Main.vue'\nimport BlRegion from '~components/frame/region/Region.vue'\nimport BlLayout from '~components/frame/layout/Layout.vue'\nimport BlGrid from '~components/frame/grid/Grid.vue'\nimport BlColumn from '~components/frame/column/Column.vue'\n```\n\nIs there a way to import Vue Components globally in your project? \nIs it an option to create a component Frame.vue that contains the imports above and add the Frame component in every template?\nHow do other FE frameworks tackle this?\n\nWe are using Nuxt JS upon Vue.\n\n========================================\n\nTop Answer:\n!!! Always name your components starting with `Base`, for example: `BaseIcon.vue`\n\n1. First, you need to create a plugin in your plugin folder, I called mine global.js\n\n2. Install lodash: npm install lodash\n\n3. Inside global.js add this code:\n\n```\nimport Vue from 'vue'\nimport upperFirst from 'lodash/upperFirst'\nimport camelCase from 'lodash/camelCase'\n\nconst requireComponent = require.context(\n '~/components',\n false,\n /Base[A-Z]\\w+\\.(vue|js)$/\n)\n\nrequireComponent.keys().forEach((fileName) => {\n const componentConfig = requireComponent(fileName)\n\n const componentName = upperFirst(\n camelCase(fileName.replace(/^\\.\\/(.*)\\.\\w+$/, '$1'))\n )\n\n Vue.component(componentName, componentConfig.default || componentConfig)\n})\n```\n\n- Inside your nuxt.config.js add `plugins: ['@plugins/global.js']`\n\n- Now you can use your base components only by typing ``\n\n========================================\n\nCode:\n```text\nimport BlMain from '~components/frame/main/Main.vue'\nimport BlRegion from '~components/frame/region/Region.vue'\nimport BlLayout from '~components/frame/layout/Layout.vue'\nimport BlGrid from '~components/frame/grid/Grid.vue'\nimport BlColumn from '~components/frame/column/Column.vue'\n```\n\n```text\n// plugins/bl-components.js\n\nimport Vue from 'vue'\nimport BlMain from '~components/frame/main/Main.vue'\nimport BlRegion from '~components/frame/region/Region.vue'\nimport BlLayout from '~components/frame/layout/Layout.vue'\nimport BlGrid from '~components/frame/grid/Grid.vue'\nimport BlColumn from '~components/frame/column/Column.vue'\n \nconst components = { BlMain, BlRegion, ... }\n \nObject.entries(components).forEach(([name, component]) => {\n Vue.component(name, component)\n})\n```\n\n```text\n// nuxt.config.js\n\nexport default {\n plugins: ['~plugins/bl-components']\n}\n```\n\n```text\nimport Vue from 'vue'\nimport upperFirst from 'lodash/upperFirst'\nimport camelCase from 'lodash/camelCase'\n\nconst requireComponent = require.context(\n '~/components',\n false,\n /Base[A-Z]\\w+\\.(vue|js)$/\n)\n\nrequireComponent.keys().forEach((fileName) => {\n const componentConfig = requireComponent(fileName)\n\n const componentName = upperFirst(\n camelCase(fileName.replace(/^\\.\\/(.*)\\.\\w+$/, '$1'))\n )\n\n Vue.component(componentName, componentConfig.default || componentConfig)\n})\n```\n\n```text\nBase\n```\n\n```text\nBaseIcon.vue\n```\n\n```text\nplugins: ['@plugins/global.js']\n```\n\n```text\n<BaseIcon />\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ncomponents\n```\n\n```text\ntrue\n```\n\n```text\nimport Vue from 'vue'\n\n/** form */\nimport Email from '~/components/elements/form/Email'\nimport Mobile from '~/components/elements/form/Mobile.vue'\nimport Password from '~/components/elements/form/Password'\nimport TextInput from '~/components/elements/form/TextInput.vue'\nimport FormLayout from '~/components/elements/form/FormLayout.vue'\nimport SelectInput from '~/components/elements/form/SelectInput.vue'\nimport ConfirmPassword from '~/components/elements/form/ConfirmPassword'\n\n/** snackbar */\nimport Snackbar from '~/components/elements/Snackbar.vue'\n\n/** skeleton */\nimport PageListing from '~/components/skeleton/PageListing'\n\n/** slots */\nimport OneRow from '~/components/slots/layouts/OneRow'\nimport LoginWrapper from '~/components/slots/layouts/LoginWrapper'\n\n/** slots tab */\nimport TabHolder from '~/components/slots/layouts/TabHolder'\nimport TabHolderHeading from '~/components/slots/layouts/TabHolderHeading.vue'\n\n/** gallery */\nimport GalleryInput from '~/components/gallery/GalleryInput.vue'\nimport GalleryDialog from '~/components/gallery/GalleryDialog.vue'\n\nconst components = { TabHolderHeading, TabHolder, GalleryInput, GalleryDialog, Snackbar, LoginWrapper, PageListing, OneRow, Password, FormLayout, ConfirmPassword, Email, Mobile, TextInput, SelectInput }\n\nObject.entries(components).forEach(([name, component]) => {\n Vue.component(name, component)\n})\n```\n\n```text\nplugins: [\n { src: '~/plugins/import-design-elements' }\n],\n```\n\n========================================\n\nComments:\n- The most common way I've seen is you can create a file that exports all of them and then you can reduce the imports to one file like this: stackoverflow.com/a/29722646\n- I understand how it works with ES6 classes, yet I can't seem to get it working with Vue components..\n- There is a WARNING note in nuxt documentation related to this way of component registration, that it will cause memory leaking on the server side as mentioned here: nuxtjs.org/docs/directory-structure/plugins/…\n- @AbdulrahmanHashem The note says `Don't use Vue.component() inside the function exported by your plugin.` which is not the case in the code snippet above so it shouldn't create a memory leak.\n- This will only save you the typing. The components will still be imported each time and additionally your build, and therefore hot reload times, will increase dramatically. I recently had to disable this feature and manually import all components because dev hmr times become unbearable. It just isn't worth it.","metadata":{"transformedAt":"2026-08-18T18:33:07.832Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":197,"estimatedTokens":1494}}41{"id":"stack-54120496","source":"stackoverflow","questionId":54120496,"title":"Nuxt - asyncData with multiple requests","tags":["javascript","vue.js","vuejs2","nuxt.js"],"text":"Title: Nuxt - asyncData with multiple requests\nTags: javascript, vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn my application I have a seller page which displays products listed by that seller. I am using asyncData to get all data required for the page (better for SEO)\n\n```\nasyncData ({params, app, error }) {\n\n return app.$axios.$get(`/seller/${params.username}`).then(async sellerRes => {\n\n let [categoriesRes, reviewsRes, productsRes] = await Promise.all([\n app.$axios.$get(`/categories`),\n app.$axios.$get(`/seller/${params.username}/reviews`),\n app.$axios.$get(`/seller/${params.username}/products`)\n ])\n\n return {\n seller: sellerRes.data,\n metaTitle: sellerRes.data.name,\n categories: categoriesRes.data,\n reviewsSummary: reviewsRes.summary,\n products: productsRes.data,\n }\n\n }).catch(e => {\n error({ statusCode: 404, message: 'Seller not found' })\n });\n},\n```\n\nAlthough this method does the job intended, I can't help but think I am doing this wrong.\n\nWhen navigating to the page the nuxt progress bar displays twice (which is odd).\n\nI've been searching for a while now to try and find examples of multiple requests in asyncData but there's not much out there.\n\nMaybe I'm not supposed to call multiple requests in asyncData?\n\n========================================\n\nTop Answer:\nActually, you can, using the `async await`, which, looks a lot cleaner too.\n\n```\n\n \n \n\n### Request 1:\n\n \n\n### {{ post.title }}\n\n {{ post.body }}\n \n\n \n\n### Request 2:\n\n \n\n### {{ todos.title }}\n\n {{ todos.completed }}\n \n\nimport axios from \"axios\";\n\nexport default {\n async asyncData({ params }) {\n // We can use async/await ES6 feature\n const posts = await axios.get(\n `https://jsonplaceholder.typicode.com/posts/${params.id}`\n );\n const todos = await axios.get(\n `https://jsonplaceholder.typicode.com/todos/${params.id}`\n );\n return { post: posts.data, todos: todos.data };\n },\n head() {\n return {\n title: this.post.title\n };\n }\n};\n\n```\n\nhere is a working sandbox of it. (don't forget to add a value for `:id` route param)\n\n========================================\n\nCode:\n```text\nasyncData ({params, app, error }) {\n\n return app.$axios.$get(`/seller/${params.username}`).then(async sellerRes => {\n\n let [categoriesRes, reviewsRes, productsRes] = await Promise.all([\n app.$axios.$get(`/categories`),\n app.$axios.$get(`/seller/${params.username}/reviews`),\n app.$axios.$get(`/seller/${params.username}/products`)\n ])\n\n return {\n seller: sellerRes.data,\n metaTitle: sellerRes.data.name,\n categories: categoriesRes.data,\n reviewsSummary: reviewsRes.summary,\n products: productsRes.data,\n }\n\n }).catch(e => {\n error({ statusCode: 404, message: 'Seller not found' })\n });\n},\n```\n\n```text\nasync asyncData ({ $axios }) {\n const [categoriesRes, articlesRes] = await Promise.all([ \n $axios.get('/fetch/categories'),\n $axios.get('/fetch/articles'),\n ])\n\n return {\n categories: categoriesRes.data,\n articles: articlesRes.data,\n }\n},\n```\n\n```text\nasyncData ({params, app, error }) {\n\n return app.$axios.$get(`/seller/${params.username}`).then(sellerRes => {\n return Promise.all([\n app.$axios.$get(`/categories`),\n app.$axios.$get(`/seller/${params.username}/reviews`),\n app.$axios.$get(`/seller/${params.username}/products`)\n ]).then((categoriesRes, reviewsRes, productsRes) => {\n return {\n seller: sellerRes.data,\n metaTitle: sellerRes.data.name,\n categories: categoriesRes.data,\n reviewsSummary: reviewsRes.summary,\n products: productsRes.data,\n }\n })\n }).catch(e => {\n error({ statusCode: 404, message: 'Seller not found' })\n });\n\n},\n```\n\n```text\nasyncData\n```\n\n```text\n<template>\n <div class=\"container\">\n <h1>Request 1:</h1>\n <h1>{{ post.title }}</h1>\n <pre>{{ post.body }}</pre>\n <br />\n <h1>Request 2:</h1>\n <h1>{{ todos.title }}</h1>\n <pre>{{ todos.completed }}</pre>\n </div>\n</template>\n\n<script>\nimport axios from \"axios\";\n\nexport default {\n async asyncData({ params }) {\n // We can use async/await ES6 feature\n const posts = await axios.get(\n `https://jsonplaceholder.typicode.com/posts/${params.id}`\n );\n const todos = await axios.get(\n `https://jsonplaceholder.typicode.com/todos/${params.id}`\n );\n return { post: posts.data, todos: todos.data };\n },\n head() {\n return {\n title: this.post.title\n };\n }\n};\n</script>\n```\n\n```text\nasync await\n```\n\n```text\n:id\n```\n\n========================================\n\nComments:\n- Have you tried to `await` for the app.$axis.$get instead of returning it?\n- it works, but synchronously - check the answer of Andrew Savetchuk below if you want to run it in parallel\n- When one of those request is failed, then it throws `'data' is undefined`\n- Also a issue to address here: Nuxt waits until a $axios promise resolves before loading the page. When your first call is fast and your second is slow, the page will already change state and the loading bar integrated in Nuxt will think that you are done and will disappear. Not really a neat feature if you have multiple calls waiting..\n- I think this answer deserves to be adopted\n- That's a really cool example. I was thinking that I was executing requests in paralell but no...This is the way! Thank a lot!\n- How if one of the request is failing? How to catch it?\n- Actually Promise.all is not the best choice here. If one promise rejects, no other promise will be resolved ...","metadata":{"transformedAt":"2026-08-18T18:33:07.832Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":219,"estimatedTokens":1411}}42{"id":"stack-45509472","source":"stackoverflow","questionId":45509472,"title":"how to write global router-function in nuxt.js","tags":["vue.js","vue-router","nuxt.js"],"text":"Title: how to write global router-function in nuxt.js\nTags: vue.js, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using Vue.js with Nuxt.js, but I got a problem in router's functions.\n\nIn the pure Vue, i can write in `main.js` like this:\n\n```\nval route = new Router({\n routes:{\n [...]\n }\n})\n\nroute.beforeEach(to,from,next){\n //do something to validate\n}\n```\n\nAnd how to do the same in nuxt.js ? I can not find any file like `main.js`.\n\nAlso, all i know is to deal with the `pages` folder to achieve router, I can not set the redirect path\n\nplease help, thx :)\n\n========================================\n\nTop Answer:\nIf anybody might be still interested, it's possible to setup global middleware in `nuxt.config.js` like this:\n\n```\nrouter: { middleware: ['foo'] },\n```\n\nthen in your `middleware/foo.js` you do whatever...\n\n```\nexport default function({ route, from, store, redirect }) {}\n```\n\n**Beware:** You can't use this for static sites (nuxt generate), because middleware is not executed on page load, but only on subsequent route changes. Thanks @ProblemsOfSumit for pointing that out.\n\n========================================\n\nCode:\n```text\nval route = new Router({\n routes:{\n [...]\n }\n})\n\nroute.beforeEach(to,from,next){\n //do something to validate\n}\n```\n\n```text\nmain.js\n```\n\n```text\nmain.js\n```\n\n```text\npages\n```\n\n```text\n// Nuxt <= 2.x\nexport default ({ app }) => {\n // Every time the route changes (fired on initialization too)\n app.router.afterEach((to, from) => {\n //do something to validate\n })\n}\n```\n\n```text\n// Nuxt >= 3.x\nexport default ({ app }) => {\n // Every time the route changes (fired on initialization too)\n app.$router.afterEach((to, from) => {\n //do something to validate\n })\n}\n```\n\n```text\nplugins: ['~/plugins/route']\n```\n\n```text\nplugins/route.js\n```\n\n```text\nnuxt.config.js\n```\n\n```js\nrouter: { middleware: ['foo'] },\n```\n\n```js\nexport default function({ route, from, store, redirect }) {}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nmiddleware/foo.js\n```\n\n```js\nexport default defineNuxtPlugin((nuxtApp) => {\n nuxtApp.$router.beforeEach((_to, _from) => {\n //..\n });\n});\n```\n\n========================================\n\nComments:\n- @JackyWong how do you do it with middleware?\n- Can't thank you enough for this helpful snippet of code. I was trying to make a middleware for this\n- Wish I could give you a hug. thank you so much for this. anyway, I use Nuxt3, the code needs a little adjustment to this: app.$router.afterEach\n- I guess if you use SPA mode, you don't have middleware, right?\n- For future reference: You can use middleware in SPA mode. For SPAs it is only executed on the client side. See this discussion on github for all the gotchas: github.com/nuxt/nuxt.js/issues/2653\n- For static sites, you can't use middleware because they are not executed on page load, only on subsequent route changes.\n- If you reload any of your routes directly, they are also not called\n- what is the difference between a nuxt plugin and router middleware, from what I see they seem to do the exact same thing?\n- Plugins have much broader scope of use as opposed to middlewares which are closely connected to routing.","metadata":{"transformedAt":"2026-08-18T18:33:07.832Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":139,"estimatedTokens":797}}43{"id":"stack-57659169","source":"stackoverflow","questionId":57659169,"title":"Vue/Nuxt: How to define a global method accessible to all components?","tags":["vue.js","plugins","mixins","nuxt.js"],"text":"Title: Vue/Nuxt: How to define a global method accessible to all components?\nTags: vue.js, plugins, mixins, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI just want to be able to call\n\n```\n{{ globalThing(0) }}\n```\n\nin templates, without needing to define globalThing in each .vue file.\n\nI've tried all manner of plugin configurations (or mixins? not sure if Nuxt uses that terminology.), all to no avail. It seems no matter what I do, `globalThing` and `this.globalThing` remain undefined.\n\nIn some cases, I can even debug in Chrome and see this `this.globalThing` is indeed defined... but the code crashes anyway, which I find very hard to explain.\n\nHere is one of my many attempts, this time using a plugin:\n\nnuxt.config.js:\n\n```\nplugins: [\n {\n src: '~/plugins/global.js',\n mode: 'client'\n },\n],\n```\n\nglobal.js:\n\n```\nimport Vue from 'vue';\nVue.prototype.globalFunction = arg => {\n console.log('arg', arg);\n return arg;\n};\n```\n\nand in the template in the .vue file:\n\n```\ngloabal test {{globalFunction('toto')}}\n```\n\nand... the result:\n\nTypeError\n_vm.globalFunction is not a function\n\nHere's a different idea, using Vuex store.\n\nstore/index.js:\n\n```\nexport const actions = {\n globalThing(p) {\n return p + ' test';\n }\n};\n```\n\n.vue file template:\n test result: {{test('fafa')}}\n\n.vue file script:\n\n```\nimport { mapActions } from 'vuex';\n\nexport default {\n\n methods: {\n ...mapActions({\n test: 'globalThing'\n }),\n }\n};\n```\n\naaaaaaaaand the result is.........\n\ntest result: [object Promise]\n\nOK, so at least the method exists this time. I would much prefer not to be forced to do this \"import mapActions\" dance etc. in each component... but if that's really the only way, whatever.\n\nHowever, all I get is a Promise, since this call is async. When it completes, the promise does indeed contain the returned value, but that is of no use here, since I need it to be returned from the method.\n\nEDIT\n\nOn the client, \"this\" is undefined, except that..... it isn't! That is to say, \n\n```\nconsole.log('this', this);\n```\n\nsays \"undefined\", but Chrome's debugger claims that, right after this console log, \"this\" is exactly what it is supposed to be (the component instance), and so is this.$store! \n\nI'm adding a screenshot here as proof, since I don't even believe my own eyes.\n\nhttps://i.sstatic.net/50ueW.png\n\n========================================\n\nTop Answer:\n- Use Nuxt's inject to get the method available everywhere\n\n```\nexport default ({ app }, inject) => {\n inject('myInjectedFunction', (string) => console.log('That was easy!', string))\n}\n```\n\n- Make sure you access that function as $myInjectedFunction (note *$*)\n\n- Make sure you added it in nuxt.config.js plugins section\n\nIf all else fails, wrap the function in an object and inject object so you'd have something like `$myWrapper.myFunction()` in your templates - we use objects injected from plugins all over the place and it works (e.g. in v-if in template, so pretty sure it would work from {{ }} too).\n\nfor example, our analytics.js plugin looks more less:\n\n```\nimport Vue from 'vue';\nconst analytics = {\n setAnalyticsUsersData(store) {...}\n ...\n}\n\n//this is to help Webstorm with autocomplete\nVue.prototype.$analytics = analytics;\n\nexport default ({app}, inject) => {\n inject('analytics', analytics);\n}\n```\n\nWhich is then called as `$analytics.setAnalyticsUsersData(...)`\n\nP.S. Just noticed something. You have your plugin in client mode. If you're running in universal, you have to make sure that this plugin (and the function) is not used anywhere during SSR. If it's in template, it's likely it actually is used during SSR and thus is undefined. Change your plugin to run in both modes as well.\n\n========================================\n\nCode:\n```text\n{{ globalThing(0) }}\n```\n\n```text\nplugins: [\n {\n src: '~/plugins/global.js',\n mode: 'client'\n },\n],\n```\n\n```text\nimport Vue from 'vue';\nVue.prototype.globalFunction = arg => {\n console.log('arg', arg);\n return arg;\n};\n```\n\n```text\n<div>gloabal test {{globalFunction('toto')}}</div>\n```\n\n```text\nexport const actions = {\n globalThing(p) {\n return p + ' test';\n }\n};\n```\n\n```text\nimport { mapActions } from 'vuex';\n\nexport default {\n\n methods: {\n ...mapActions({\n test: 'globalThing'\n }),\n }\n};\n```\n\n```text\nconsole.log('this', this);\n```\n\n```text\nglobalThing\n```\n\n```text\nthis.globalThing\n```\n\n```text\nthis.globalThing\n```\n\n```js\nexport default (context, inject) => {\n const hello = (msg) => console.log(`Hello ${msg}!`)\n // Inject $hello(msg) in Vue, context and store.\n inject('hello', hello)\n // For Nuxt <= 2.12, also add 👇\n context.$hello = hello\n}\n```\n\n```js\nexport default {\n plugins: ['~/plugins/hello.js']\n}\n```\n\n```js\n// store/index.js\n\nexport const state = () => ({\n globalThing: ''\n})\n\nexport const mutations = {\n setGlobalThing (state, value) {\n state.globalThing = value\n }\n}\n\n\n// .vue file script\n\nexport default {\n created() {\n this.$store.commit('setGlobalThing', 'hello')\n },\n};\n\n\n\n// .vue file template\n\n{{ this.$store.state.globalThing }}\n```\n\n```text\nexport default ({ app }, inject) => {\n inject('myInjectedFunction', (string) => console.log('That was easy!', string))\n}\n```\n\n```text\nimport Vue from 'vue';\nconst analytics = {\n setAnalyticsUsersData(store) {...}\n ...\n}\n\n//this is to help Webstorm with autocomplete\nVue.prototype.$analytics = analytics;\n\nexport default ({app}, inject) => {\n inject('analytics', analytics);\n}\n```\n\n```text\n$myWrapper.myFunction()\n```\n\n```text\n$analytics.setAnalyticsUsersData(...)\n```\n\n```text\nimport Pusher from \"pusher-js\";\n\nexport default defineNuxtPlugin((nuxtApp) => {\n const pusher = new Pusher(\"api_key\", {\n cluster: \"mt1\",\n forceTLS: false,\n httpHost: \"127.0.0.1\",\n wsPort: 6001,\n });\n\n return {\n provide: {\n pusher: pusher,\n },\n };\n});\n```\n\n```text\n<script setup lang=\"ts\">\nconst { $pusher } = useNuxtApp();\nconsole.log('🚀 ~ $pusher:', $pusher)\n\n...\n</script>\n```\n\n```text\nprovide\n```\n\n========================================\n\nComments:\n- `import Vue from 'vue'; Vue.prototype.globalThing = arg => { ... }` may you need this?\n- Tried that. didn't work.\n- Plugins is the thing you are looking for. Check nuxt documentation and try again. If that doesnt work, let us see your code somehow\n- Yep, that's what I thought, but I've been trying to use this plugin feature for a whole afternoon now, and I am no closer to my goal. Code added to reflect the case you described.\n- Is the the documentation you are referring to nuxtjs.org/guide/plugins ? Because this makes no mention of making calls from templates. Then there is the Vue plugins doc, here vuejs.org/v2/guide/plugins.html ... which is really quite divergent from the Nuxt docs. I don't know... maybe I'll just try doing what is described in the Vue docs, anyway.\n- Nope. This provides no way to pass a parameter to globalThing, as shown in the question: {{ globalFunction('toto') }}\n- Well, that almost worked. The plugin function is actually found and called, which is a small miracle, but now \"this.$store\" is undefined in that function. So... it seems that \"this\" is not what it's supposed to be, ie. the component instance. Finding the store instance is always an idiosyncratic pain in the neck... Why they didn't just make the store a global var, I don't think I'll ever understand. Oh, and good call about making the plugin available server-side. That was very much part of the problem.\n- So this rabbit hole just keeps getting curiouser. So on the server, \"this\" is undefined, which I guess is normal, and anyway, we wouldn't have any $store there, so who cares. But.... on the client, \"this\" is also undefined, except that..... it isn't! That is to say, console.log('this', this); says \"undefined\", but Chrome's debugger claims that, right after this console log, \"this\" is exactly what it is supposed to be, and so is this.$store! I'm adding a screenshot to the question as proof, since I don't even believe my own eyes.\n- This is only going to be available once the component is created so depends where you're trying to access it - for example, in beforeCreate hook this. will be undefined. The same applies to various Nuxt hooks. Maybe you'll find this series of posts of mine helpful? dev.to/lilianaziolek/…\n- In this specific case, you can access store by adding it to extract from Nuxt context, that is: `export default ({ app, store }, inject)`\n- Also, don't trust commands executed in Devtools context - they may operate in different context than you think. Trust log statements.\n- This \"If it's in template, it's likely it actually is used during SSR and thus is undefined.\" saved my day.","metadata":{"transformedAt":"2026-08-18T18:33:07.832Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":327,"estimatedTokens":2172}}44{"id":"stack-72848779","source":"stackoverflow","questionId":72848779,"title":"How to add a script block to head in Nuxt 3?","tags":["vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: How to add a script block to head in Nuxt 3?\nTags: vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI simply want to add a `script` block in the `head` tag.\n\n**Example**\n\n```\n\n alert('hello, world!');\n\n```\n\nI spent hours to figure out a solution for something as simple as this.\nThere are tons of answers about adding `inline` scripts, but none for the script `block` for `Nuxt 3`\n\nHow can we do this in `Nuxt 3`?\n\n========================================\n\nTop Answer:\nComplementing Moon's answer, there is another way to achieve this. This method allows you to import it globally into your app and gives you complete control over the tag itself:\n\n**Solution 4**\n\n```\nexport default defineNuxtConfig({\n css: ['./public/assets/style.css', 'primeicons/primeicons.css'],\n app: {\n head: {\n script: [{\n src: \"https://consent.cookiebot.com/uc.js\",\n \"data-cbid\": \"xxxxx\",\n type: \"text/javascript\",\n id: \"Cookiebot\",\n async: true\n }]\n }\n }\n})\n```\n\nThis approach also works with the `useHead({})` function if you want to add a script to a specific page.\n\n========================================\n\nCode:\n```js\n<script>\n alert('hello, world!');\n</script>\n```\n\n```text\nscript\n```\n\n```text\nhead\n```\n\n```text\ninline\n```\n\n```text\nblock\n```\n\n```text\nNuxt 3\n```\n\n```text\nNuxt 3\n```\n\n```text\n<template>\n <Script children=\"console.log('Hello, world!');\" />\n</template>\n```\n\n```text\n<script setup>\nuseHead({\n script: [{ children: \"console.log('Hello, world!');\" }],\n});\n</script>\n```\n\n```text\nimport { defineNuxtConfig } from 'nuxt';\n\nexport default defineNuxtConfig({\n app: {\n head: {\n script: [{ children: \"console.log('Hello, world!');\" }],\n },\n },\n});\n```\n\n```text\nexport default defineNuxtConfig({\n css: ['./public/assets/style.css', 'primeicons/primeicons.css'],\n app: {\n head: {\n script: [{\n src: \"https://consent.cookiebot.com/uc.js\",\n \"data-cbid\": \"xxxxx\",\n type: \"text/javascript\",\n id: \"Cookiebot\",\n async: true\n }]\n }\n }\n})\n```\n\n```text\nuseHead({})\n```\n\n========================================\n\nComments:\n- This was the solution for nuxt2. Here is the related topic for Nuxt3: github.com/nuxt/framework/issues/5565\n- The first one is maybe working but hacky as hell, the second one is the most recommended way overall. You're welcome for the third one!\n- why do we need a children's to object? and can you put a immediately invoked function there?\n- Solution 3 works amid webpage hard refresh\n- I just used app.head.script with `[{innerHTML: \"console.log('Hello, world!');\"}]`\n- Nuxt has released a dedicated scripts module since then. Quite more powerful and flexible.","metadata":{"transformedAt":"2026-08-18T18:33:07.832Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":135,"estimatedTokens":682}}45{"id":"stack-70302520","source":"stackoverflow","questionId":70302520,"title":"Nuxtjs v3 and Tailwindcss v3 PostCSS@8 not compatible","tags":["nuxt.js","tailwind-css","postcss"],"text":"Title: Nuxtjs v3 and Tailwindcss v3 PostCSS@8 not compatible\nTags: nuxt.js, tailwind-css, postcss\nSource: Stack Overflow\n\nQuestion:\ni'm trying to install Tailwindcss in my nuxt project\n\nI use fresh install from nuxt https://v3.nuxtjs.org/getting-started/installation\n\n```\nnpx nuxi init nuxt3-app\n```\n\nand tailwindcss installation\n\nhttps://tailwindcss.com/docs/guides/nuxtjs\n\nBut when i start the app `npm run dev` i got this error\n\n```\nERROR Cannot restart nuxt: postcss@8 is not compatible with current version of nuxt (0.0.0). Expected: >=2.15.3\n```\n\nI don't know how to fix it, and cannot find any answer online, i appreciate any help, thankyou\n\n========================================\n\nTop Answer:\nI had this problem too, as Nuxt 3 requires a different way to integrate Tailwind. The following is to install Tailwind as a Nuxt module, rather than independently. This is easier, as it requires a lot less configuration (no need to edit *postcss.config.js*, a bit less config required for *nuxt.config.js*).\n\nVersion 5.0 of the Nuxt Tailwind module brings in support for Nuxt 3. Full default installation is as follows:\n\n### Step 1\n\nTo install, we can dev install this (yarn add or npm install) with *@nuxtjs/tailwindcss@latest* or whichever version (after 5.1) you need.\n\n```\nyarn add -D @nuxtjs/tailwindcss@latest\n```\n\n### Step 2\n\nThen in **nuxt.config.js**, add the module to the modules array:\n\n```\nimport { defineNuxtConfig } from \"nuxt\"\n\nexport default defineNuxtConfig({\n modules: [\n '@nuxtjs/tailwindcss'\n ]\n})\n```\n\n### Step 3\n\nCreate a **tailwind.config.js** file either manually or by using the terminal command:\n\n```\nnpx tailwindcss init\n```\n\n### Step 4\n\nAdd the Tailwind directives to your main CSS file (./assets/css/tailwind.css by default, or configurable in your *nuxt.config.js* file).\n\n```\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n### Step 5\n\nAfter this, try running your dev or build commands, and it should be working correctly.\n\n========================================\n\nCode:\n```text\nnpx nuxi init nuxt3-app\n```\n\n```text\nERROR Cannot restart nuxt: postcss@8 is not compatible with current version of nuxt (0.0.0). Expected: >=2.15.3\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm install -D tailwindcss@latest postcss@latest autoprefixer@latest\nnpx tailwindcss init\n```\n\n```js\nmodule.exports = {\n content: [\n './assets/**/*.{vue,js,css}',\n './components/**/*.{vue,js}',\n './layouts/**/*.vue',\n './pages/**/*.vue',\n './plugins/**/*.{js,ts}',\n './nuxt.config.{js,ts}',\n ],\n variants: {\n extend: {},\n },\n plugins: [],\n};\n```\n\n```js\nmodule.exports = {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n}\n```\n\n```css\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```js\nimport { defineNuxtConfig } from 'nuxt3'\n\n// https://v3.nuxtjs.org/docs/directory-structure/nuxt.config\nexport default defineNuxtConfig({\n css: ['~/assets/css/tailwind.css'],\n build: {\n postcss: {\n postcssOptions: require('./postcss.config.js'),\n },\n }\n})\n```\n\n```html\n<script setup>\nimport '@/assets/css/tailwind.css'\n</script>\n```\n\n```text\n@nuxt/postcss8\n```\n\n```text\ntailwind.config.js\n```\n\n```text\npostcss.config.js\n```\n\n```text\nassets/css/tailwind.css\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\napp.vue\n```\n\n```text\nnpx nuxi init nuxt3-app\n```\n\n```js\nmodule.exports = {\n purge: [\n \"./components/**/*.{vue,js}\",\n \"./layouts/**/*.vue\",\n \"./pages/**/*.vue\",\n \"./plugins/**/*.{js,ts}\",\n \"./nuxt.config.{js,ts}\",\n \"./app.vue\",\n ],\n mode: 'jit',\n theme: {\n extend: {},\n },\n plugins: [],\n}\n```\n\n```text\ntailwind.config.js\n```\n\n```text\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\nmain.css\n```\n\n```text\ntailwind.css\n```\n\n```text\nimport { defineNuxtConfig } from \"nuxt\";\n\n// https://v3.nuxtjs.org/api/configuration/nuxt.config\nexport default defineNuxtConfig({\n css: [\"@/assets/css/main.css\"],\n postcss: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n },\n});\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nyarn add -D @nuxtjs/tailwindcss@latest\n```\n\n```text\nimport { defineNuxtConfig } from \"nuxt\"\n\nexport default defineNuxtConfig({\n modules: [\n '@nuxtjs/tailwindcss'\n ]\n})\n```\n\n```text\nnpx tailwindcss init\n```\n\n```text\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\nimport { defineNuxtConfig } from \"nuxt\";\n\n// https://v3.nuxtjs.org/api/configuration/nuxt.config\nexport default defineNuxtConfig({\n modules: [\n '@nuxtjs/tailwindcss'\n ],\n css: [\"@/assets/css/tailwind.css\"],\n postcss: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n },\n },\n});\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nnpm i -D @nuxtjs/tailwindcss@latest\n```\n\n```text\n// https://v3.nuxtjs.org/api/configuration/nuxt.config\nexport default defineNuxtConfig({\n modules: ['@nuxtjs/tailwindcss']\n})\n```\n\n```text\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\n<template>\n <div>\n <h1 class=\"text-3xl font-bold underline\">\n Hello world!\n </h1>\n </div>\n</template>\n```\n\n```text\nnpx tailwindcss init\n```\n\n```text\n/** @type {import('tailwindcss').Config} */\nmodule.exports = {\n content: [\"./src/**/*.{html,js}\"],\n theme: {\n extend: {},\n },\n plugins: [],\n}\n```\n\n```js\nmodule.exports = {\n content: [\n './app.vue',\n // ...rest of the list \n ],\n variants: {\n extend: {},\n },\n plugins: [],\n};\n```\n\n```text\napp.vue\n```\n\n```text\ntailwind.config.js\n```\n\n========================================\n\nComments:\n- You can use Windi CSS (nearly exactly the same thing, but personally slightly better and faster). Windi CSS uses the same syntax as Tailwind CSS and works with Nuxt 3. You can find documentation on how to install it here : [windicss.org/].\n- just tested not working :s\n- why do you add `nuxt.config` to your tailwind configs `content` ?\n- @vhflat i just use configuration guide from official documentation, feel free to use your own configuration\n- The latest version of nuxt does not like it when you `require` inside of `nuxt.config.ts`, so I just added the configuration of `postcss.config.js` (the object that is being exported) directly into the `postcssOptions` object within `nuxt.config.ts` Works like a charm!\n- Hey I got tailwind working, but it does not seem to update on file-save. I have to rebuild the server after making a change for the tailwind css to take effect... Does this work with you?\n- This is not the recommended way of setting up a nuxt3 project. See nuxt.com/modules/tailwindcss and nuxt.com/docs/migration/bundling\n- This is a great start to an answer; please describe how your code fixes the OP's problem.\n- Thx, saved me a lot of time as all the nuxt 3 guides for tailwind are outdated!\n- 2023 and still works :))","metadata":{"transformedAt":"2026-08-18T18:33:07.832Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":354,"estimatedTokens":1704}}46{"id":"stack-51385651","source":"stackoverflow","questionId":51385651,"title":"Custom Directive in nuxt js","tags":["vue.js","nuxt.js","server-side-rendering"],"text":"Title: Custom Directive in nuxt js\nTags: vue.js, nuxt.js, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nis there a way how to write a custom directive in nuxt js, which will work for ssr and also for frontend (or even for ssr only)? \n\nI tried it like in following documentation: \nhttps://nuxtjs.org/api/configuration-render#bundleRenderer\n\nso I added this code:\n\n```\nmodule.exports = {\n render: {\n bundleRenderer: {\n directives: {\n custom1: function (el, dir) {\n // something ...\n }\n }\n }\n }\n }\n```\n\nto nuxt.config.js\n\nthen I use it in template as:\n\n```\n\n```\n\nbut it doesn't work, it just throw the frontend error \n\n[Vue warn]: Failed to resolve directive: custom1\n\nAnd it doesn't seem to be working even on server side.\n\nThanks for any advice.\n\n========================================\n\nTop Answer:\nIf you want use custom directives in Nuxt you can do the following:\n\n- Create a file inside plugins folder, for example, directives.js\n\n- In nuxt.config.js add something like `plugins: ['~/plugins/directives.js']`\n\nIn your new file add your custom directive like this:\n\n```\nimport Vue from 'vue'\n\nVue.directive('focus', {\n inserted: (el) => {\n el.focus()\n }\n})\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n render: {\n bundleRenderer: {\n directives: {\n custom1: function (el, dir) {\n // something ...\n }\n }\n }\n }\n }\n```\n\n```text\n<component v-custom1></component>\n```\n\n```text\nrender: {\n bundleRenderer: {\n directives: {\n cww: function (vnode, dir) {\n const style = vnode.data.style || (vnode.data.style = {})\n style.backgroundColor = '#ff0016'\n }\n }\n }\n }\n```\n\n```text\n<div v-cww>X</div>\n```\n\n```text\n<div style=\"background-color:#ff0016;\">X</div>\n```\n\n```text\nimport Vue from 'vue'\n\nVue.directive('focus', {\n inserted: (el) => {\n el.focus()\n }\n})\n```\n\n```text\nplugins: ['~/plugins/directives.js']\n```\n\n```js\n// plugins/directive.client.js\n\nimport Vue from 'vue'\n\nVue.directive('log-inner-text', {\n inserted: el => {\n console.log(el.innerText)\n }\n})\n```\n\n```js\nplugins: [\n '~/plugins/directive.client.js'\n]\n```\n\n```html\n<div v-log-inner-text>Hello</div>\n```\n\n```text\n> \"Hello\"\n```\n\n```text\n.client.js\n```\n\n```text\nSSR\n```\n\n```text\nstatic\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nVue.directive('loading', function (el, binding) {\n console.log('running loading directive client side')\n})\n```\n\n```text\nrender: {\n bundleRenderer: {\n directives: {\n loading (element, binding) {\n console.log('running loading directive server side')\n }\n }\n }\n }\n```\n\n```text\n<div v-loading=\"true\">Test</div>\n```\n\n```text\nrender\n```\n\n```text\n[Vue warn]: Failed to resolve directive: loading\n```\n\n```text\n// plugins/directive.ts\nexport default defineNuxtPlugin((nuxtApp) => {\n nuxtApp.vueApp.directive('my-directive', {\n mounted(element, binding, globalThis) {\n // Your custom directive logic here\n console.log(\"My directive works!\", binding.value); // Output: the value passed as an argument to the directive. In this case the string 'Hello'\n }\n });\n});\n```\n\n```text\n<my-component v-my-directive=\"'Hello'\">\n```\n\n========================================\n\nComments:\n- thanks @Sphinx, but that's in general the same code as I pasted and it doesn't work for me, don't you have some working example please?\n- I met the same problem as yours now (Nuxt.js 1.4.0). I just tried `bundleRenderer.shouldPreload` it works fine, but `bundleRenderer.directives` didn't.\n- thanks for a hint, but this works only on frontend, it doesn't have any effect on server side rendered html.\n- Worked by using `bind` and `unbind` in this syntax.\n- How would you set innerText of the element?\n- @TimarIvoBatis Try this one, stackoverflow.com/questions/59401783/…\n- Thanks haha that was my question and also my answer :D\n- PS: I've also did a small write up on custom SSR directives: blog.lichter.io/posts/universal-ssr-vue-component-guide/…","metadata":{"transformedAt":"2026-08-18T18:33:07.832Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":218,"estimatedTokens":1018}}47{"id":"stack-58774572","source":"stackoverflow","questionId":58774572,"title":"Custom index.html for nuxt.js build","tags":["vue.js","nuxt.js"],"text":"Title: Custom index.html for nuxt.js build\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSorry if this is asked, just not sure what to search for. Is there a way to change the template that's used to generate the index.html file when building a **Nuxt app** in spa mode?\n\n========================================\n\nTop Answer:\n**Nuxt3**\n\nA long-awaited solution as a result of https://github.com/nuxt/nuxt/issues/14195 discussion.\n\nCreate a file in `server/plugins/extend-html.ts` (yes, `server/plugins` folder, not just `plugins` in root)\n\n```\nexport default defineNitroPlugin((nitroApp) => {\n nitroApp.hooks.hook('render:html', (html, { event }) => {\n html.head.push(\n `window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag('js', new Date());gtag('config', 'AW-123456789');`,\n )\n })\n})\n```\n\nas per https://nuxt.com/docs/guide/directory-structure/server#server-plugins it'll automatically import to your file while doing `nuxi build`. It's in `server`, so can't promise it'll work for `nuxi generate`.\n\n========================================\n\nCode:\n```text\n<!DOCTYPE html>\n<html lang=\"en\" {{ HTML_ATTRS }}>\n <head {{ HEAD_ATTRS }}>\n {{ HEAD }}\n </head>\n <body {{ BODY_ATTRS }}>\n {{ APP }}\n </body>\n</html>\n```\n\n```text\n.nuxt/views/app.template.html\n```\n\n```text\napp.html\n```\n\n```text\napp.template.html\n```\n\n```text\nlang\n```\n\n```text\nhtml\n```\n\n```text\napp.html\n```\n\n```text\n@Ohgodwhy\n```\n\n```text\nindex.html\n```\n\n```text\nvue-meta\n```\n\n```text\nexport default defineNitroPlugin((nitroApp) => {\n nitroApp.hooks.hook('render:html', (html, { event }) => {\n html.head.push(\n `<script async src='https://www.googletagmanager.com/gtag/js?id=AW-123456789'></script><script>window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag('js', new Date());gtag('config', 'AW-123456789');</script>`,\n )\n })\n})\n```\n\n```text\nserver/plugins/extend-html.ts\n```\n\n```text\nserver/plugins\n```\n\n```text\nplugins\n```\n\n```text\nnuxi build\n```\n\n```text\nserver\n```\n\n```text\nnuxi generate\n```\n\n========================================\n\nComments:\n- There is no *index.html* with nuxt. What is output is generated automagically by the framework through several points of configuration. What are you attempting to accomplish here?\n- When you do \"npm run build\" and you have it set to spa mode in the nuxt config, there is an index.html file that is generated in the dist folder. I'm wondering if it's possible to control what that html content looks like. If it's possible, I'd like to have that only have the script tags rather than a fully generated page with html, head, and body tags.\n- There *is* an `index.html` generated by Nuxt based on what configuration you have.\n- how about Nuxt 3?\n- copy/pasted from github.com/nuxt/nuxt/issues/14195, at least leave the source","metadata":{"transformedAt":"2026-08-18T18:33:07.832Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":121,"estimatedTokens":710}}48{"id":"stack-60169343","source":"stackoverflow","questionId":60169343,"title":"Invalid component name: \"pages/product/_slug.vue\". Component names should conform to valid custom element name in html5 specification","tags":["javascript","vue.js","routes","vue-router","nuxt.js"],"text":"Title: Invalid component name: \"pages/product/_slug.vue\". Component names should conform to valid custom element name in html5 specification\nTags: javascript, vue.js, routes, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using Nuxt.js and have some dynamic routes. My folder structure is this:\n\n```\n- pages\n - product\n - _slug.vue\n```\n\nI link to the route like this: \n\n```\n\n```\n\nIt works fine, it shows the correct URL and also directs the page fine, however, I am getting an annoying red error in my console:\n\n```\n[Vue warn]: Invalid component name: \"pages/product/_slug.vue\". Component names should conform to valid custom element name in html5 specification.\n```\n\nhttps://i.sstatic.net/EYKRl.png\n\nI have found this issue, but to little avail: https://github.com/nuxt/nuxt.js/issues/165\n\n========================================\n\nTop Answer:\nThe reason of this error message is that the name of the `_slug.vue` component which is the same as the file name.\n\nI expect it `name='_slug.vue'` you need to change it to something like this `name='ProductItem'`\n\n========================================\n\nCode:\n```text\n- pages\n - product\n - _slug.vue\n```\n\n```text\n<nuxt-link :to=\"{ name: 'product-slug', params: { slug: product.slug } }\">\n```\n\n```text\n[Vue warn]: Invalid component name: \"pages/product/_slug.vue\". Component names should conform to valid custom element name in html5 specification.\n```\n\n```text\nexport default {\n name: 'Assign Role'\n}\n```\n\n```text\nexport default {\n name: 'AssignRole',\n}\n```\n\n```text\n_slug.vue\n```\n\n```text\nname='_slug.vue'\n```\n\n```text\nname='ProductItem'\n```\n\n```text\nexport default {\n name: 'NameOfTheCompnent',\n ...\n }\n```\n\n```js\n@Component({})\nexport default class MyComponent extends Vue {\n...\n}\n```\n\n```text\nvue-property-decorator\n```\n\n```text\n({})\n```\n\n```text\nname\n```\n\n```text\n@Component\n```\n\n```text\n@Component({ name: 'MyComponent' })\n```\n\n```text\nexport default {\n name: \"WelcomeScreen\",\n components: [\n Welcome_Ready,\n ],\n}\n```\n\n```text\nexport default {\n name: \"WelcomeScreen\",\n components: {\n Welcome_Ready,\n },\n}\n```\n\n========================================\n\nComments:\n- have you tried `` ?\n- or add it if you don't have an export from that file\n- He was correct. When you do NOT specify a \"name\" in the component, Nuxt assigns the path as the name. You need to add: `export default { name: 'componentName', ... }` to fix the warning.","metadata":{"transformedAt":"2026-08-18T18:33:07.832Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":135,"estimatedTokens":609}}49{"id":"stack-59413786","source":"stackoverflow","questionId":59413786,"title":"Can not access process.env variables in component nuxt","tags":["vue.js","vuejs2","environment-variables","nuxt.js"],"text":"Title: Can not access process.env variables in component nuxt\nTags: vue.js, vuejs2, environment-variables, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn nuxt config I have env object\n\n```\nenv: {\n hey: process.env.hey || 'hey'\n},\n```\n\nas soon as I want to display it in component template:\n\n```\n{{ process.env.hey }}\n```\n\nI got an error \n\n Cannot read property 'env' of undefined\n\nAny idea what can cause that?\n\n========================================\n\nTop Answer:\nIn case someone is looking for a solution in Nuxt 3 and vite.\n\n*.env*\n\n`VITE_APP_VARIABLE_NAME=\"your variable\"`\n\n*template.vue*\n\n```\n\nconst loginUrl = import.meta.env.VITE_APP_VARIABLE_NAME as string;\n\n```\n\n========================================\n\nCode:\n```text\nenv: {\n hey: process.env.hey || 'hey'\n},\n```\n\n```text\n{{ process.env.hey }}\n```\n\n```html\n<template>\n <div>{{ message }}</div>\n</template>\n```\n\n```js\nexport default {\n computed: {\n message() {\n return process.env.hey;\n },\n },\n};\n```\n\n```js\nexport default {\n publicRuntimeConfig: {\n message: process.env.hey || 'hello world!',\n },\n};\n```\n\n```html\n<template>\n <div>{{ $config.message }}</div>\n</template>\n```\n\n```text\nprocess\n```\n\n```text\nconst state = () => ({\n env: {},\n buildEnv: '',\n})\n\nconst mutations = {\n setEnv(state, env) {\n state.env = env\n },\n setBuildEnv(state, env) {\n state.buildEnv = env\n },\n}\n\nconst actions = {\n nuxtServerInit({ commit }) {\n if (process.server) {\n if (process.env.NUXT_ENV_BUILD_HASH) {\n commit('setEnv', {\n buildHash: JSON.parse(process.env.NUXT_ENV_BUILD_HASH),\n })\n } else {\n commit('setEnv', {\n buildHash: false,\n })\n }\n commit('setBuildEnv', process.env.NODE_ENV)\n }\n },\n}\nconst getters = {\n env(state) {\n return state.env\n },\n buildEnv(state) {\n return state.buildEnv\n },\n}\n\nexport default {\n state,\n mutations,\n actions,\n getters,\n}\n```\n\n```text\ncomputed: {\n ...mapGetters(['env', 'buildEnv']),\n}\n```\n\n```text\nserverInit.js\n```\n\n```text\nprocess.env\n```\n\n```text\nif (process.server)\n```\n\n```text\nprocess.env\n```\n\n```text\n<script setup lang=\"ts\">\nconst loginUrl = import.meta.env.VITE_APP_VARIABLE_NAME as string;\n</script>\n```\n\n```text\nVITE_APP_VARIABLE_NAME=\"your variable\"\n```\n\n========================================\n\nComments:\n- @dopeCode I'm confused why this is the accepted answer. When you use nuxt, it adds `process.env` as a global variable on the client. This means that no additional steps are necessary, and components do have access to your predefined env vars.\n- Not sure if this answer is outdated, as I've already tried it in the latest version of Nuxt without any luck. Please see my answer below.\n- In my case I'm building a SPA, and this still works with the latest version nuxt. I assume this would work differently if the pages server generated.\n- Ah yes, I'm using universal mode. See my answer below for SSR\n- I use universal mode as well and this answer is still working.\n- What about using the runtime config? nuxtjs.org/blog/moving-from-nuxtjs-dotenv-to-runtime-config\n- @retroriff Good call! I've updated the answer.\n- This is not working for me. My config : \"nuxt\": \"^3.3.1\", \"vite-plugin-string\": \"^1.2.1\"\n- i have tried \"nuxt\": \"^3.3.1\" and it is working for me. Maybe you have to bind the env file in package.json's script `\"dev\": \"nuxt dev --port 8080 --dotenv .env.development\",` more info here vitejs.dev/guide/env-and-mode.html","metadata":{"transformedAt":"2026-08-18T18:33:07.832Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":181,"estimatedTokens":864}}50{"id":"stack-50375244","source":"stackoverflow","questionId":50375244,"title":"Push a route (Moving from vueJS to nuxtJS)","tags":["vue.js","nuxt.js","vue-i18n","nuxt-i18n"],"text":"Title: Push a route (Moving from vueJS to nuxtJS)\nTags: vue.js, nuxt.js, vue-i18n, nuxt-i18n\nSource: Stack Overflow\n\nQuestion:\nI am converting a VueJS project to Nuxt.js and I have a problem understanding how nuxt handles routing. Its documentation doesn't say anything about Pushing a route.\n\nUsing VueJS I have the following in a component.\n\n```\n//template\n \n //script\n methods: {\n submitSearch() {\n this.$route.push({name: 'search', query: {q: this.q}});\n\n //also tried the following\n //nuxt.$router.push({name: 'search', query: {q: this.q}});\n\n }\n }\n```\n\nBut this doesn't do a thing in Nuxt. Putting an alert('hi); inside the submitSearch fires fine but I am never redirected to the route.\n\nThe goal here is when the user presses enter in the searchbar, to be redirected to /search?q=blablabla\n\n**EDIT:** \n\nThe problem is that the user is redirected to `/?q=blablabla` instead of `/search?`..\n\nI just realized that this is because there are different names for multilingual routes.\n\nHow am I going to push to a route name that instead of '`search`' is named `search__en` dynamically?\n\n========================================\n\nTop Answer:\nThis is how it could be done in Nuxt3, with the Composition API\n\n```\n\nconst router = useRouter()\nconst moveToIndex = () => router.push({ name: 'about' })\n\n move to about page\n\n```\n\nThe Options API is still working in the same exact way.\n\n========================================\n\nCode:\n```text\n//template\n <input class=\"\" type=\"search\"\n name=\"q\" id=\"q\" v-model=\"q\"\n @keyup.enter=\"submitSearch\"\n >\n //script\n methods: {\n submitSearch() {\n this.$route.push({name: 'search', query: {q: this.q}});\n\n //also tried the following\n //nuxt.$router.push({name: 'search', query: {q: this.q}});\n\n }\n }\n```\n\n```text\n/?q=blablabla\n```\n\n```text\n/search?\n```\n\n```text\nsearch\n```\n\n```text\nsearch__en\n```\n\n```js\nthis.$router.push({path: this.localePath('search'), query: {q: this.q}});\n```\n\n```text\n#${hash}\n```\n\n```text\nrouter\n```\n\n```text\nthis.$nuxt.$options.router\n```\n\n```text\nthis.$nuxt.$options.router.push()\n```\n\n```html\n<script setup>\nconst router = useRouter()\nconst moveToIndex = () => router.push({ name: 'about' })\n</script>\n\n<template>\n <button @click=\"moveToIndex\">move to about page</button>\n</template>\n```\n\n```text\nconst router = useRouter();\n\nrouter.push({ path: '/home' });\nrouter.push({ path: 'project-list' });\nrouter.replace({ name: 'project-list' });\n```\n\n```text\nrouter.back();\nrouter.forward();\nrouter.go();\n```\n\n```js\nnavigateTo(\"/reports/\" + reportId);\n```\n\n========================================\n\nComments:\n- isn't it still \"this.$router.push...?\"\n- Also refer to this issue: github.com/nuxt/nuxt.js/issues/2737\n- Thanks @DevinFields, I updated my question.\n- there still might not be enough information. Is that the complete vue file? Can you post your router configuration?\n- This answer is in the wrong place, but you definitely helped me. Thanks. Also I realized stack overflow converts the backticks you used.\n- You don't need to go that deep, as shown by the other answers.","metadata":{"transformedAt":"2026-08-18T18:33:07.833Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":147,"estimatedTokens":775}}51{"id":"stack-56896966","source":"stackoverflow","questionId":56896966,"title":"How to deploy a finished nuxt.js app to a webserver?","tags":["vue.js","nginx","npm","vuex","nuxt.js"],"text":"Title: How to deploy a finished nuxt.js app to a webserver?\nTags: vue.js, nginx, npm, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nAt work, I got some little insight to nuxtjs development and I got very interested in it. So, I started developing on my own a little bit, but now, I'm stuck with my finished project. \n\nTo develop, I spin up a local server with \"npm run dev\" in my CLI. This all works fine. \n\nBut, how do I deploy my now finished project to run it in something like nginx (or are there better alternatives that run on an Windows Server environment) on my home server? I heard about \"npm run build\" into my CLI, but how is the procedure beyond that? And is that command even the right method?\n\nI'm absolutely a noob in this department. Could anybody teach me step by step what I have to do to go \"in production\"? \n\nThank's very much in advance!\n\nMax\n\nOf course, \"npm run dev\" isn't a viable option for production. It's only accessable from the machine the server is running on.\n\n========================================\n\nTop Answer:\nThere is no one answer to this question and the main variables are, are you deploying a static app, or a universal (ssr) app and where do you want to host it.\n\nStatic apps are pretty straight forward as suggested in the comments and other answer, but chances are you've got a SSR app and need to deploy that.\n\nThe docs have details on deploying to a range of hosting providers as well as a bit about using nginx.\n\nThere is a tutorial to deploy to digital ocean.\n\nSome hosting providers are easier than others, and really the ones that provide a CLI to deploy from are usually easier. Therefore Heroku is a good choice as are Now and Netlify, but the later two are only for static apps. The docs say that \"AWS is a death by 1000 paper cuts\", so I guess that's not easy.\n\nSo you should check out your hosting options and choose one, try and the nuxt docs to deploy and if you get stuck, ask another question here with specifics.\n\n========================================\n\nCode:\n```text\nnpm run generate\n```\n\n```text\ndist\n```\n\n```text\nmode\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nspa\n```\n\n```text\nnpm run build\n```\n\n```text\ndist/\n```\n\n```text\n|- nuxt # (this is project folder)\n| |- dockerfiles\n| |- nginx\n| |- prod\n| |- conf.d\n| |- nginx.conf\n| |- docker-compose-wo-le.yml\n| |- nginx.tmpl # (must be downloaded, read top comments in docker-compose-wo-le.yml)\n|- src\n| |- .nuxt\n| |- folders and files here\n| |- assets\n| |- components\n| |- .......\n| |- node_modules\n| |- .......\n| |- nuxt.config.js\n| |- package.json\n| |- package-lock.json\n```\n\n```text\n# HOW TO USE:\n# 1. Download latest nginx.tmpl (save next to this docker-compose file):\n# curl https://raw.githubusercontent.com/jwilder/nginx-proxy/master/nginx.tmpl > ./nginx.tmpl\n# 2. Run docker-compose: docker-compose -f ./docker-compose-wo-le.yml up -d\n\nversion: '3.5'\nservices:\n nuxt-nginx:\n restart: always\n image: nginx\n container_name: nuxt-nginx-container\n volumes:\n - /etc/localtime:/etc/localtime:ro\n - ./nginx/prod/conf.d:/etc/nginx/conf.d\n ports:\n - '80:80'\n\n nuxt-node:\n image: node:10.23\n container_name: nuxt-node-container\n command: npm run start\n volumes:\n - ../src:/usr/src/app\n working_dir: /usr/src/app\n environment:\n HOST: 0.0.0.0\n```\n\n```text\nmap $sent_http_content_type $expires {\n \"text/html\" epoch;\n \"text/html; charset=utf-8\" epoch;\n default off;\n}\n\nproxy_cache_path /tmp/nuxt levels=1:2 keys_zone=nuxt_cache:10m max_size=100m inactive=30m use_temp_path=off;\nproxy_cache_key \"$scheme$request_method$host$request_uri\";\nproxy_cache_use_stale updating error timeout http_500 http_502 http_503 http_504;\nproxy_cache_background_update on;\nproxy_cache_valid 200 302 20m;\n\nserver {\n listen 80 default_server;\n server_name localhost;\n charset utf-8;\n keepalive_timeout 5;\n\n gzip on;\n gzip_comp_level 5;\n gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;\n gzip_proxied no-cache no-store private expired auth;\n gzip_min_length 1000;\n\n location / {\n expires $expires;\n\n proxy_redirect off;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_read_timeout 1m;\n proxy_connect_timeout 1m;\n\n proxy_pass http://nuxt-node:3000;\n\n # Required for caching\n proxy_ignore_headers Expires Cache-Control;\n proxy_cache_revalidate on;\n proxy_cache_lock on;\n proxy_cache nuxt_cache;\n }\n}\n```\n\n```text\nnuxt generate\n```\n\n```text\nlocalhost\n```\n\n```text\nerror Exit status 139\n```\n\n```text\nnode_modules\n```\n\n```text\nnpm run build\n```\n\n```text\nindex.js\n```\n\n========================================\n\nComments:\n- after running `npm run build`, you should have production files in the `dist` folder, just upload the contents and it should be fine (given that they're static files).\n- I used npm run generate and did all your steps. It worked fine!\n- @A.L Nuxt builds a statically deployable version of the application (ie. a Node server is not needed, all routes are generated as static HTML files) with `nuxt generate` (or `nuxt-ts generate`) and builds the output in the `build` folder. For SSR + Client apps (ie. a Node server is needed to run the application), Nuxt creates a `.nuxt` folder after calling `nuxt build` (or `nuxt-ts build`), which can be deployed as a Node.js application.\n- @AbingPj yes. But one thing this question and this answer don't cover, is the question \"Is the app server side rendered or just a static app?\", so the answer is incomplete at best.\n- @Paul-SebastianManole , I have nuxt app but not SSR. can i deploy it using,. \"npm run build & start\",????... I already deploy static app in the apache server. But Icannt dynamic routes,. So, i want it to change using \"npm run build & start\" deployment\n- @AbingPj SSR as the name implies needs a Node.js server. You cannot deploy a dynamic Nuxt app to Apache as static content. Please learn the basics first or you'll become frustrated if you try to do things that won't work because they simply cannot work as you expect them to.\n- Thanks for helping me out! In my case, I simply used npm run generate and put all that stuff into my htdocs folder.\n- @MaxCroon Better then you take the effort to update your question, because I don't see this information in the question and it's causing some confusion.\n- This is a complicated answer not really suited for the question. Before going through the effort, I supposed it would have been best to ask the OP what exactly he wants to do, because it is not clear: deploy a static or a universal Nuxt app?\n- BTW, It's necessary to expose port from nuxt-node dockerfile and also HOST environment variable should be set (0.0.0.0 works for me)","metadata":{"transformedAt":"2026-08-18T18:33:07.833Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":200,"estimatedTokens":1800}}52{"id":"stack-54477839","source":"stackoverflow","questionId":54477839,"title":"What is the best way to store constants in Nuxt?","tags":["vue.js","constants","nuxt.js"],"text":"Title: What is the best way to store constants in Nuxt?\nTags: vue.js, constants, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a nuxt project (vuejs) and I'm wondering how to store constants in my project ? ( about 50 constants).\n\nThank you for your response.\nkaboume\n\n========================================\n\nTop Answer:\nI think @Birante is just about right. Just because certain folders don't ship with the boilerplate doesn't mean you can't add them. However, I'd propose a structure like such,\n\n```\n|-- assets\n|\n|-- components\n| |-- Logo.vue\n| `-- index.js\n|\n|-- constants\n| |-- constants_002.js\n| |-- constants_001.js\n| `-- index.js\n|\n|-- layouts\n| |-- default.vue\n| `-- index.js\n|\n|-- middleware\n| `-- index.js\n|\n|-- pages\n| `-- index.vue\n|\n|-- plugins\n|\n|-- static\n|\n|-- store\n| `-- index.js\n|\n|-- test\n| `-- Logo.spec\n|\n`-- package.json\n```\n\nAnd then set up your constants in a modular fashion like you would any other part of your app.\n\nconstants/constants_001.js\n\n```\nexport const MY_FIRST_CONSTANT = 'is awesome'\n```\n\nconstants/constants_002.js\n\n```\nexport const MY_SECOND_CONSTANT = 'is also awesome'\n```\n\nconstants/index.js\n\n```\nexport * from './constants_001';\nexport * from './constants_002';\n```\n\nThen you can import your constants as per the convention used throughout your app.\n\n```\nimport { MY_FIRST_CONSTANT, MY_SECOND_CONSTANT } from '@/constants/'\n```\n\nThis is also a great convention for `utils` as well that you need to across the application :)\n\n========================================\n\nCode:\n```js\n// constants.js\nexport const CONSTANT_1 = 'CONSTANT_1';\nexport const CONSTANT_2 = 'CONSTANT_2';\nexport const CONSTANT_3 = 'CONSTANT_3';\n \n// And call it like this\nimport { CONSTANT_1 } from 'constants';\n```\n\n```text\nconstants.js\n```\n\n```text\nconst api = \"api\";\n export default Object.freeze({\n api,\n });\n```\n\n```text\n// store/mutation-types.js\nexport const TOGGLE_MENU_STATE = 'TOGGLE_MENU_STATE';\n```\n\n```text\nimport {\n TOGGLE_MENU_STATE,\n} from '../store/mutation-types';\n\nconst mutations = {\n [TOGGLE_MENU_STATE](state) {\n state.isOpen = !state.isOpen;\n },\n};\n\nexport default mutations;\n```\n\n```text\n// constants/app-constants.js -- example\nexport const HYDRATING_SUCCESS = 'HYDRATING_SUCCESS';\nexport const HYDRATING_FAILED = 'HYDRATING_FAILED';\nexport const LOADING = 'LOADING';\nexport const LOADED = 'LOADED';\nexport const SET_ERROR_STATE = 'SET_ERROR_STATE';\nexport const CLEAR_ERROR_STATE = 'CLEAR_ERROR_STATE';\n...\n```\n\n```text\nconstants\n```\n\n```text\n|-- assets\n|\n|-- components\n| |-- Logo.vue\n| `-- index.js\n|\n|-- constants\n| |-- constants_002.js\n| |-- constants_001.js\n| `-- index.js\n|\n|-- layouts\n| |-- default.vue\n| `-- index.js\n|\n|-- middleware\n| `-- index.js\n|\n|-- pages\n| `-- index.vue\n|\n|-- plugins\n|\n|-- static\n|\n|-- store\n| `-- index.js\n|\n|-- test\n| `-- Logo.spec\n|\n`-- package.json\n```\n\n```js\nexport const MY_FIRST_CONSTANT = 'is awesome'\n```\n\n```js\nexport const MY_SECOND_CONSTANT = 'is also awesome'\n```\n\n```js\nexport * from './constants_001';\nexport * from './constants_002';\n```\n\n```text\nimport { MY_FIRST_CONSTANT, MY_SECOND_CONSTANT } from '@/constants/'\n```\n\n```text\nutils\n```\n\n```js\nconst X=\"X\";\nconst Y=\"Y\";\n\nexport {\n X,\n Y\n}\n```\n\n```js\nimport * as Constants from '@/locale/constants';\n\nexport default ({ app }, inject) => {\n inject('constants', Constants)\n}\n```\n\n```js\nthis.$constants.X\n```\n\n```text\nbreadcrumb\n```\n\n```text\ni18n\n```\n\n```text\nconstants.js\n```\n\n```text\nlocal\n```\n\n```text\n|-- plugins\n| `-- config-constants\n| | |-- config.ts\n| | |-- index.ts\n| | `-- messages.ts\n| `-- constants.js\n```\n\n```js\nimport { defineNuxtPlugin } from '@nuxtjs/composition-api'\nimport * as constants from './config-constants'\n \nexport default defineNuxtPlugin((_, inject) => {\n inject('const', constants)\n})\n```\n\n```js\nimport * as constants from '~/plugins/config-constants'\n\ndeclare module 'vue/types/vue' {\n interface Vue {\n $const: typeof constants\n }\n}\n\ndeclare module '@nuxt/types' {\n interface Context {\n $const: typeof constants\n }\n}\n\ndeclare module 'vuex' {\n interface ActionContext<S, R> {\n $const: typeof constants\n }\n}\n```\n\n```text\nconstants.ts\n```\n\n```text\n~/plugins/config-constants/index.ts\n```\n\n```text\ntype definitions\n```\n\n```text\n$const\n```\n\n```text\nthis\n```\n\n```text\ncontext\n```\n\n```text\nexport const FRUIT_COLORS = {\n apples: \"#cc9999\"\n pears: \"#99cc99\",\n}\n```\n\n```text\n./utils\n```\n\n========================================\n\nComments:\n- In which file ? a plugin file ?\n- no in the plugin, create a folder in a root then made file in that which purpose of const\n- Niokobok bro / We togheter\n- How to use it inside the template tag?\n- do you happen to know if something is changed since this answer? I've pretty much copied and pasted your answer. And I get a `\"export 'MY_FIRST_CONSTANT' was not found in '@/constants/linkConstants'` errors\n- Hey @Quickee. Sorry about that it looks like i dropped the `const` out of the export. The answer has been updated to read `export const MY_FIRST_CONSTANT = 'is awesome'`. Can you let me know if that works fine now?\n- yes that did fix it. but, only when i use them within the JS. im trying to use these consts inside the html as output or attribute values, i was able to achieve that by setting them to a data model inside of created or mounted `created () : {this.var = const}` thanks a bunch\n- Nice one. Yeah if you want to do that you could bind them in your created method or just have them returned in your data object. You could also drop them into a computed property if need be.","metadata":{"transformedAt":"2026-08-18T18:33:07.833Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":317,"estimatedTokens":1396}}53{"id":"stack-50674972","source":"stackoverflow","questionId":50674972,"title":"Nuxt.js: Include font files: use /static or /assets","tags":["vue.js","fonts","font-face","assets","nuxt.js"],"text":"Title: Nuxt.js: Include font files: use /static or /assets\nTags: vue.js, fonts, font-face, assets, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI know some posts in the nuxt.js github repo cover this a bit, but I would like to know what is the correct way to use font-files in nuxt.js.\n\nSo far we had them in the `/static/fonts` directory, but other people use `assets` to store the font files.\nWhat are the differences? Is one of the options better and if so, why?\n\nAlso there are different ways to include them.\nWould a path like this be correct:\n\n```\n@font-face {\n font-family: 'FontName';\n font-weight: normal;\n src: url('~static/fonts/font.file.eot'); /* IE9 Compat Mode */\n src: url('~static/fonts/font.file.woff') format('woff'),\n url('~static/fonts/font.file.otf') format('otf'),\n url('~static/fonts/font.file.eot') format('eot');\n}\n```\n\nThanks for some clarification here :D.\ncheers\n\nJ\n\n========================================\n\nCode:\n```text\n@font-face {\n font-family: 'FontName';\n font-weight: normal;\n src: url('~static/fonts/font.file.eot'); /* IE9 Compat Mode */\n src: url('~static/fonts/font.file.woff') format('woff'),\n url('~static/fonts/font.file.otf') format('otf'),\n url('~static/fonts/font.file.eot') format('eot');\n}\n```\n\n```text\n/static/fonts\n```\n\n```text\nassets\n```\n\n```text\nassets\\\n```\n\n```text\nstatic\\\n```\n\n========================================\n\nComments:\n- hey check out this answer. I think its a bit related\n- Ok. I somehow did not find this. Thanks for the clarification. Cheers\n- The docs don't answer the question. Which is better for fonts? If you're loading Google fonts, should you load them from the CDN, and if so, where in the app do you do it?\n- @ccleve to import a resource (eg. a font) from a CDN, the better way si to declare it in your \"nuxt.config.js\" file as explained in docs: nuxtjs.org/faq/#global-settings\n- nuxtjs.org/docs/2.x/directory-structure/assets#fonts\n- actually the docs say initially that assets is the directory for images, sass-files and for *fonts*, but then they also state that you can also use the static folder. I would assume that by the nature of font files, you don't want to touch them or processed by webpack and therefore `static` would be the better place to store them? Or am I missing something?","metadata":{"transformedAt":"2026-08-18T18:33:07.833Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":68,"estimatedTokens":572}}54{"id":"stack-59347414","source":"stackoverflow","questionId":59347414,"title":"Why is my `client-only` component in nuxt complaining that `window is not defined`?","tags":["vue.js","leaflet","nuxt.js"],"text":"Title: Why is my `client-only` component in nuxt complaining that `window is not defined`?\nTags: vue.js, leaflet, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have Vue SPA that I'm trying to migrate to nuxt. I am using `vue2leaflet` in a component that I enclosed in `` tags but still getting an error from nuxt saying that `window is not defined`.\n\nI know I could use `nuxt-leaflet` or create a plugin but that increases the vendor bundle dramatically and I don't want that. I want to import the leaflet plugin only for the components that need it. Any way to do this?\n\n```\n\n \n\n```\n\nAnd the `map` component:\n\n```\n\n \n \n \n \n \n\nimport {\n LMap,\n LTileLayer,\n LMarker,\n LFeatureGroup,\n LGeoJson,\n LPolyline,\n LPolygon,\n LControlScale\n} from 'vue2-leaflet';\nimport { Icon } from 'leaflet';\nimport 'leaflet/dist/leaflet.css';\n\n// this part resolve an issue where the markers would not appear\ndelete Icon.Default.prototype._getIconUrl;\n\nexport default {\n name: 'map',\n components: {\n LMap,\n LTileLayer,\n LMarker,\n LFeatureGroup,\n LGeoJson,\n LPolyline,\n LPolygon,\n LControlScale\n },\n//...\n```\n\n========================================\n\nTop Answer:\n```\n\n \n \n \n \n\n \n export default {\n name: 'parent-component',\n components: {\n Map: () =>\n if (process.client) {\n return import ('../components/Map.vue')\n },\n },\n }\n \n```\n\nThe solutions above did not work for me.\n\nWhy? This took me a while to find out so I hope it helps someone else.\n\nThe \"problem\" is that Nuxt automatically includes Components from the \"components\" folder so you don't have to include them manually. This means that even if you load it dynamically only on process.client it will still load it server side due to this automatism.\n\nI have found the following two solutions:\n\nRename the \"components\" folder to something else to stop the automatic import and then use the solution above (process.client).\n\n(and better option IMO) there is yet another feature to lazy load the automatically loaded components. To do this prefix the component name with \"lazy-\". This, in combination with will prevent the component from being rendered server-side.\n\nIn the end your setup should look like this\nFiles:\n\n```\n./components/map.vue\n./pages/index.html\n```\n\nindex.html:\n\n```\n\n \n \n \n \n \n export default {\n }\n \n```\n\n========================================\n\nCode:\n```html\n<client-only>\n <map></map>\n</client-only>\n```\n\n```html\n<template>\n <div id=\"map-container\">\n <l-map\n style=\"height: 80%; width: 100%\"\n :zoom=\"zoom\"\n :center=\"center\"\n @update:zoom=\"zoomUpdated\"\n @update:center=\"centerUpdated\"\n @update:bounds=\"boundsUpdated\"\n >\n <l-tile-layer :url=\"url\"></l-tile-layer>\n </l-map>\n </div>\n</template>\n\n<script>\nimport {\n LMap,\n LTileLayer,\n LMarker,\n LFeatureGroup,\n LGeoJson,\n LPolyline,\n LPolygon,\n LControlScale\n} from 'vue2-leaflet';\nimport { Icon } from 'leaflet';\nimport 'leaflet/dist/leaflet.css';\n\n// this part resolve an issue where the markers would not appear\ndelete Icon.Default.prototype._getIconUrl;\n\nexport default {\n name: 'map',\n components: {\n LMap,\n LTileLayer,\n LMarker,\n LFeatureGroup,\n LGeoJson,\n LPolyline,\n LPolygon,\n LControlScale\n },\n//...\n```\n\n```text\nvue2leaflet\n```\n\n```text\n<client-only>\n```\n\n```text\nwindow is not defined\n```\n\n```text\nnuxt-leaflet\n```\n\n```text\nmap\n```\n\n```html\n<template>\n <client-only>\n <map/>\n </client-only>\n</template>\n\n<script>\nexport default {\n name: 'parent-component',\n components: {\n Map: () => if(process.client){return import('../components/Map.vue')},\n },\n}\n</script>\n```\n\n```text\n<client-only>\n```\n\n```html\n<template>\n <client-only>\n <map/>\n </client-only>\n </template>\n\n <script>\n export default {\n name: 'parent-component',\n components: {\n Map: () =>\n if (process.client) {\n return import ('../components/Map.vue')\n },\n },\n }\n </script>\n```\n\n```text\n./components/map.vue\n./pages/index.html\n```\n\n```html\n<template>\n <client-only>\n <lazy-map/>\n </client-only>\n </template>\n <script>\n export default {\n }\n </script>\n```\n\n```js\nasync mounted() {\n const MyPlugin = await import('some-vue-plugin');\n Vue.use(MyPlugin);\n}\n```\n\n```text\nVue.use()\n```\n\n```text\nVue.use(MyPlugin.default)\n```\n\n```text\n<script>\nlet LMap, LTileLayer, LMarker, LPopup, LIcon, LControlAttribution, LControlZoom, Vue2LeafletMarkerCluster, Icon\nif (process.client) {\n require(\"leaflet\");\n ({\n LMap,\n LTileLayer,\n LMarker,\n LPopup,\n LIcon,\n LControlAttribution,\n LControlZoom,\n } = require(\"vue2-leaflet/dist/vue2-leaflet.min\"));\n ({\n Icon\n } = require(\"leaflet\"));\n Vue2LeafletMarkerCluster = require('vue2-leaflet-markercluster')\n\n}\n\nimport \"leaflet/dist/leaflet.css\";\nexport default {\n components: {\n \"l-map\": LMap,\n \"l-tile-layer\": LTileLayer,\n \"l-marker\": LMarker,\n \"l-popup\": LPopup,\n \"l-icon\": LIcon,\n \"l-control-attribution\": LControlAttribution,\n \"l-control-zoom\": LControlZoom,\n \"v-marker-cluster\": Vue2LeafletMarkerCluster,\n \n },\n\n mounted() {\n if (!process.server) //probably not needed but whatever\n {\n // This makes sure the common error that the images are not found is solved, and also adds the settings to it.\n delete Icon.Default.prototype._getIconUrl;\n Icon.Default.mergeOptions({\n // iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'), // if you want the defaults\n // iconUrl: require('leaflet/dist/images/marker-icon.png'), if you want the defaults\n // shadowUrl: require('leaflet/dist/images/marker-shadow.png') if you want the defaults\n shadowUrl: \"/icon_shadow_7.png\",\n iconUrl: \"/housemarkerblue1.png\",\n shadowAnchor: [10, 45],\n iconAnchor: [16, 37],\n popupAnchor: [-5, -35],\n iconSize: [23, 33],\n // staticAnchor: [30,30],\n });\n }\n },\n```\n\n```text\n<client-only></client-only>\n```\n\n```html\n<template>\n <div id=\"map-container\">\n <l-map style=\"height: 80%; width: 100%\">\n <l-tile-layer :url=\"url\"></l-tile-layer>\n </l-map>\n </div>\n</template>\n\n<script>\nimport 'leaflet/dist/leaflet.css'\n\nexport default {\n name: 'Map',\n components: {\n [process.client && 'LMap']: () => import('vue2-leaflet').LMap,\n [process.client && 'LTileLayer']: () => import('vue2-leaflet').LTileLayer,\n },\n}\n</script>\n```\n\n```text\nMap.vue\n```\n\n```text\nleaflet\n```\n\n```text\nMap.vue\n```\n\n```text\nMap.vue\n```\n\n```text\nimport('vue2-leaflet').LMap\n```\n\n```text\nvue2-editor\n```\n\n```text\njsplumb\n```\n\n```html\n<client-only v-if=\"$root.$el\">\n <client-only>\n <map/>\n </client-only>\n</client-only>\n```\n\n```js\n// plugins/env.js\nexport default defineNuxtPlugin(nuxtApp => {\n nuxtApp.provide('env', {\n isClientSide: process.client\n });\n});\n```\n\n```html\n<client-only v-if=\"$env.isClientSide\">\n <client-only>\n <map/>\n </client-only>\n</client-only>\n```\n\n```text\n$root.$el\n```\n\n```text\n<client-only>\n```\n\n```text\n<client-only>\n```\n\n```text\n$env\n```\n\n========================================\n\nComments:\n- the component isn't the problem here, it's the inclusion of leaflet which is not ssr friendly. all `` is doing is preventing the rendering during ssr, it is not preventing the inclusion of the script.\n- I see. Any way to use a plugin like `nuxt-leaflet` *only* for this component?\n- No, because even with dynamic imports it would still be transpiled in during ssr. I would assume the inclusion of the library has to happen within a conditional\n- Your proposed syntax was not accepted in my case, but I modified it slightly and then it is working correctly. I modified it to this: `Map: () => process.client ? import('@/components/Map') : null,`\n- You should be registering the map component from a plugin with mode 'client' instead. nuxtjs.org/guide/plugins#client-or-server-side-only\n- @idmean I want it loaded only when necessary. Plugins are loaded globally AFAIK.\n- The Map component has an export default. Do you know how to import destructed components as well? Does the import function provide this functionality?\n- @idmean nope, if the component/library only needs to be local, please keep it so. No need to bring it in the global scope. Simple example, you use a library for a datepicker on a single `/contact-us` page. Loading it with a plugin means that this datepicker will be loaded at the start of the app, whenever you use it on a given page or not. Not a good approach performance-wise.\n- for me, I needed to destructure the import. So I used the following syntax `Map : () => process.client ? import('package-name').then(e => e.Map) : undefined`\n- You can disable the auto import of the components if you find it annoying: `components: false` in `nuxt.config.js`. Otherwise, here is the article related to all of those component improvements: nuxtjs.org/tutorials/…\n- Using `Vue.use()` would make it global, so there is no benefit over using it as a plugin in your case. Prefer keeping it locally import for the given component.\n- Re: Nuxt plugin: Is there still a problem if you were to use client-side plugins?\n- @MarsAndBack you can use client-side plugins with Nuxt, you'll just get some errors with Nuxt if you don't explicitly say: \"I want to use them ONLY on client side\". Not an issue overall.","metadata":{"transformedAt":"2026-08-18T18:33:07.833Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":430,"estimatedTokens":2333}}55{"id":"stack-55885337","source":"stackoverflow","questionId":55885337,"title":"\"Default Apollo Queries\" VS \"AsyncData\" (Nuxt.js)","tags":["vue.js","async-await","graphql","nuxt.js","vue-apollo"],"text":"Title: \"Default Apollo Queries\" VS \"AsyncData\" (Nuxt.js)\nTags: vue.js, async-await, graphql, nuxt.js, vue-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm building a site with Nuxt/Vue, and it's using a GraphQL backend API. We access this using the Apollo module for Nuxt.\n\nIn a page component, you can do this (I think this is called a Smart Query, but I'm not sure):\n\n```\napollo: {\n pages: {\n query: pagesQuery,\n update(data) {\n return _get(data, \"pageBy\", {});\n }\n },\n }\n}\n```\n\nBut you can also do the query like this I think, using the Nuxt asyncData hook:\n\n```\nasyncData(context) {\n let client = context.app.apolloProvider.defaultClient;\n client.query({query, variables})\n .then(({ data }) => {\n // do what you want with data\n });\n }\n}\n```\n\nI'm not sure what the difference is between these two ways, and which is better. Does anyone know? I couldn't find an explanation in the docs anywhere.\n\n========================================\n\nCode:\n```js\napollo: {\n pages: {\n query: pagesQuery,\n update(data) {\n return _get(data, \"pageBy\", {});\n }\n },\n }\n}\n```\n\n```js\nasyncData(context) {\n let client = context.app.apolloProvider.defaultClient;\n client.query({query, variables})\n .then(({ data }) => {\n // do what you want with data\n });\n }\n}\n```\n\n========================================\n\nComments:\n- Using `asyncData` doesn't update Apollo cache automatically while smart query does.\n- So a smart query isn't blocking in anyway? I worry that my SSR page is going to have to wait for all these queries to finish before showing anything to the user.\n- My understanding is that the query behaves in the same manner as asyncData would, in that it is asynchronous, and the server prefetches data into a dedicated data store while pre-rendering and injects that into the client when complete. I've not noticed any blocking behaviour but only have a couple of projects utilising them to go by.\n- Asyncdata wait for data to be ready before rendering both on client and server","metadata":{"transformedAt":"2026-08-18T18:33:07.833Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":69,"estimatedTokens":504}}56{"id":"stack-66336557","source":"stackoverflow","questionId":66336557,"title":"Nuxt not automatically importing components from nested directory","tags":["javascript","vue.js","nuxt.js","nuxt3.js"],"text":"Title: Nuxt not automatically importing components from nested directory\nTags: javascript, vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nIn my nuxt app, components in nested directories are not automatically importing as expected. For some of my components i have something like the following:\n\n`vue 2.6.12`, `nuxt 2.15.0`\n\n`components\\` Directory structure\n\n```\nTopArea\\\n--SomeComponent.vue\n```\n\n```\n\n \n Hello\n \n \n\n```\n\nNo other component in the application has the name `SomeComponent`. In the example above i get the error: `Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the \"name\" option.`. I can get around the issue by specifying the directory name before the component filename (`TopAreaSomeComponent`), use the prefix option in nuxt.config, or by manually importing the component. This is confusing because the docs state:\n\nNested Directories\n\nIf you have components in nested directories such as:\n\n`components/baseButton.vue`\n\nThe component name will be based on its own filename. Therefore, the component will be:\n\n``\n\nIt goes on to say \"We recommend you use the directory name in the filename for clarity\". But that seems like a rule than a recommendation. If i don't use the directory name as part of the filename, dynamic imports are not working for components in nested directories.\n\nIs this an error in the docs or am I reading it wrong?\n\n========================================\n\nTop Answer:\nThis may answered already. But to illustrate the solution to comers here here's the way according to docs:\n\n```\n\n```\n\nif your components is nested deeply:\n\n`components / TopArea / SomeComponent.vue`\n\nhttps://nuxtjs.org/docs/directory-structure/components/#nested-directories\n\n========================================\n\nCode:\n```text\nTopArea\\\n--SomeComponent.vue\n```\n\n```text\n<template>\n <header class=\"header\">\n <div>Hello</div>\n <SomeComponent />\n </header>\n</template>\n```\n\n```text\nvue 2.6.12\n```\n\n```text\nnuxt 2.15.0\n```\n\n```text\ncomponents\\\n```\n\n```text\nSomeComponent\n```\n\n```text\nUnknown custom element: <SomeComponent> - did you register the component correctly? For recursive components, make sure to provide the \"name\" option.\n```\n\n```text\nTopAreaSomeComponent\n```\n\n```text\ncomponents/baseButton.vue\n```\n\n```text\n<button />\n```\n\n```js\ncomponents: [\n {\n path: '~/components', // will get any components nested in let's say /components/test too\n pathPrefix: false,\n },\n]\n```\n\n```html\n<template>\n <div>\n <yolo-swag /> <!-- no need for <nested-yolo-swag /> here -->\n </div>\n</template>\n```\n\n```js\nimport { defineNuxtConfig } from 'nuxt'\n\nexport default defineNuxtConfig({\n components: {\n global: true,\n dirs: ['~/components']\n },\n})\n```\n\n```text\ncomponents\n```\n\n```text\npathPrefix\n```\n\n```text\nnuxt.config.js/ts\n```\n\n```html\n<TopAreaSomeComponent />\n```\n\n```text\ncomponents / TopArea / SomeComponent.vue\n```\n\n```text\n\"overrides\": {\n \"unimport\": \"3.13.4\"\n}\n```\n\n```text\n\"pnpm\": {\n \"overrides\": {\n \"unimport\": \"3.13.4\"\n }\n}\n```\n\n```text\nunimport\n```\n\n```text\n^3.14\n```\n\n```text\npackage.json\n```\n\n```text\n3.13.4\n```\n\n```text\npnpm\n```\n\n```text\npnpm\n```\n\n========================================\n\nComments:\n- Just an fyi for future visitors, this is no longer a problem. The docs have been updated to reflect how it actually works in the current version\n- Documentation issue being worked on in github.com/nuxt/nuxtjs.org/pull/1279\n- wow, I had this bug for 8 months, thank you very much","metadata":{"transformedAt":"2026-08-18T18:33:07.833Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":197,"estimatedTokens":879}}57{"id":"stack-52364451","source":"stackoverflow","questionId":52364451,"title":"How to make Nuxt-auth and Nuxt-i18n to be friends","tags":["javascript","authentication","vue.js","internationalization","nuxt.js"],"text":"Title: How to make Nuxt-auth and Nuxt-i18n to be friends\nTags: javascript, authentication, vue.js, internationalization, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to use nuxt@auth module and nuxt-i18n together. The problem appears when I want to have different routes for login page. For example:\n\n```\npages: {\n login: {\n en: '/authorization',\n fr: '/autorisation'\n }\n}\n```\n\nRoutes are working well, but when I try to use nuxt@auth with all page restricted, the default redirect asks for /login page. In nuxt.config.js file I can rewrite redirect route, but I can set only one redirect.\n\n```\nauth: {\n redirect: {\n login: '/fr/autorisation'\n }\n}\n```\n\nHow can I show to auth module to ask for route of selected language? Thanks in advance!\n\n========================================\n\nTop Answer:\nIt seems that there was a solution for that problem https://github.com/nuxt-community/auth-module/pull/185, but I can't access to `onRedirect` method in the current release.\n\nI did a workaround. I added `auth-lang-redirect.js` plugin, which overrides `redirect` option defined in the `nuxt.config.js` file.\n\n```\nexport default ({ app }) => {\n var redirect = app.$auth.$storage.options.redirect\n for (var key in redirect) {\n redirect[key] = '/' + app.i18n.locale + redirect[key]\n }\n app.$auth.$storage.options.redirect = redirect\n}\n```\n\nNotice that I don't use `nuxt-i18n` module, but you should get the point. \nYou have to register this plugin in `nuxt.config.js` like this:\n\n```\nauth: {\n strategies: { ... },\n redirect: {\n login: '/login',\n logout: '/',\n callback: '/login',\n home: '/user/profile'\n },\n plugins: ['@/plugins/auth-lang-redirect.js']\n },\n```\n\n========================================\n\nCode:\n```text\npages: {\n login: {\n en: '/authorization',\n fr: '/autorisation'\n }\n}\n```\n\n```text\nauth: {\n redirect: {\n login: '/fr/autorisation'\n }\n}\n```\n\n```text\nexport default ({ app, $auth }) => {\n $auth.onRedirect((to, from) => {\n return app.localePath(to)\n })\n}\n```\n\n```text\nexport default ({ app }) => {\n var redirect = app.$auth.$storage.options.redirect\n for (var key in redirect) {\n redirect[key] = '/' + app.i18n.locale + redirect[key]\n }\n app.$auth.$storage.options.redirect = redirect\n}\n```\n\n```text\nauth: {\n strategies: { ... },\n redirect: {\n login: '/login',\n logout: '/',\n callback: '/login',\n home: '/user/profile'\n },\n plugins: ['@/plugins/auth-lang-redirect.js']\n },\n```\n\n```text\nonRedirect\n```\n\n```text\nauth-lang-redirect.js\n```\n\n```text\nredirect\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt-i18n\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nexport default function({ app, $auth }) {\n const redirect = { ...$auth.$storage.options.redirect };\n\n const localizeRedirects = () => {\n for (const key in redirect) {\n $auth.$storage.options.redirect[key] = app.localePath(redirect[key]);\n }\n };\n\n localizeRedirects();\n\n app.i18n.onLanguageSwitched = () => {\n localizeRedirects();\n };\n}\n```\n\n========================================\n\nComments:\n- Thanks, I allready fixed that problem, my workaround it's without for, but does the same thing.\n- This is the correct solution. It respects prefix_except_default (no prefix for default language) and works flawlessly with single page behaviour (switch language -> login)\n- Is this as plugin or middleware?\n- @Rozkalns it's the plugin\n- Works perfectly! Just wanted to clear that the plugin must be registered in auth config, not with the plugins property, auth.nuxtjs.org/recipes/extend","metadata":{"transformedAt":"2026-08-18T18:33:07.833Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":162,"estimatedTokens":876}}58{"id":"stack-50138074","source":"stackoverflow","questionId":50138074,"title":"How to append JS files in NUXT before ends","tags":["webpack","vuejs2","nuxt.js"],"text":"Title: How to append JS files in NUXT before ends\nTags: webpack, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIm trying to append javascript files in NUXT.\nbut when i use nuxt.config to append javascript it works but not as I want.\n\n```\nhead: {\n title: 'mynuxt',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: 'Nuxt.js project' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },\n { rel: 'stylesheet', href: 'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css' },\n { rel: 'stylesheet', href: '/css/bootstrap.min.css' },\n { rel: 'stylesheet', href: '/css/mdb.min.css' },\n { rel: 'stylesheet', href: '/css/style.min.css' },\n ],\n script: [\n { src: '/js/bootstrap.min.js' },\n { src: '/js/popper.min.js' },\n { src: '/js/mdb.min.js' }\n ],\n },\n```\n\nwhen i inspect element it inserted but in head.\nhttps://i.sstatic.net/9hFRb.png\n\nIve search already in google but did not found any solution yet. thanks in advance\n\n========================================\n\nTop Answer:\nFor Nuxt-3.0.0 (final) you can control the insertion behavior of several tags directly inside a component using e.g.\n\n```\n\n useHead({\n script: [\n {\n type: 'text/javascript',\n innerHTML: 'Code goes here...',\n tagPosition: 'bodyClose | bodyOpen | head',\n }\n ]\n });\n\n```\n\nThe script will be put\n\n- `bodyClose` -> ending of body\n\n- `bodyOpen` -> start of body\n\n- `head` -> head (default)\n\nOr you can refer to this post where it is explained how to put a script tag inside a component's template section.\n\n========================================\n\nCode:\n```text\nhead: {\n title: 'mynuxt',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: 'Nuxt.js project' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },\n { rel: 'stylesheet', href: 'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css' },\n { rel: 'stylesheet', href: '/css/bootstrap.min.css' },\n { rel: 'stylesheet', href: '/css/mdb.min.css' },\n { rel: 'stylesheet', href: '/css/style.min.css' },\n ],\n script: [\n { src: '/js/bootstrap.min.js' },\n { src: '/js/popper.min.js' },\n { src: '/js/mdb.min.js' }\n ],\n },\n```\n\n```text\nmodule.exports = {\n plugins: ['~/plugins/example']\n}\n```\n\n```text\n<script>\nexport default {\n head: {\n script: [\n { src: '/head.js' },\n // Supported since Nuxt 1.0\n { src: '/body.js', body: true },\n { src: '/defer.js', defer: '' }\n ]\n }\n}\n</script>\n```\n\n```text\n.js\n```\n\n```text\nplugin\n```\n\n```text\nplugins/example.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nbody: true\n```\n\n```text\napp: {\n head: {\n title: 'title',\n charset: 'utf-8',\n meta: [\n { name: 'viewport', content: 'width=device-width, initial-scale=1' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },\n { rel: 'stylesheet', href: '/layout/css/bootstrap.css' },\n { rel: 'stylesheet', href: '/layout/vendors/chartjs/Chart.min.css' },\n { rel: 'stylesheet', href: '/layout/vendors/perfect-scrollbar/perfect-scrollbar.css' },\n { rel: 'stylesheet', href: '/layout/css/app.css' }\n ],\n noscript: [\n { children: 'Javascript is required' }\n ],\n script: [\n { src: '/layout/vendors/perfect-scrollbar/perfect-scrollbar.min.js', body: true },\n { src: '/layout/js/app.js', body: true },\n { src: '/layout/vendors/chartjs/Chart.min.js', body: true },\n { src: '/layout/vendors/apexcharts/apexcharts.min.js', body: true },\n { src: '/layout/js/pages/dashboard.js', body: true },\n { src: '/layout/js/main.js', body: true }\n ]\n }\n },\n```\n\n```text\nbody:true\n```\n\n```js\n<script setup lang=\"ts\">\n useHead({\n script: [\n {\n type: 'text/javascript',\n innerHTML: 'Code goes here...',\n tagPosition: 'bodyClose | bodyOpen | head',\n }\n ]\n });\n</script>\n```\n\n```text\nbodyClose\n```\n\n```text\nbodyOpen\n```\n\n```text\nhead\n```\n\n========================================\n\nComments:\n- should i reside my js files from plugins not on static sir?\n- @WinstonFale I do not know what your goal is, why do you want to put out the Vue or in the plugin?? in the plugin any `.js` works, static too.\n- i have static js for a theme. i already import css. using head > link from nuxt.config. but it has also custom javascripts which is required to be put before closing of . it is not working when i put in header because it will find element that is not existing yet.\n- @WinstonFale Try `{ src: '/example.js', body: true },` with `body:true`\n- thanks you so much adriano meta data {body:true} works for me\n- how can add js files from node_module this way?","metadata":{"transformedAt":"2026-08-18T18:33:07.833Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":201,"estimatedTokens":1236}}59{"id":"stack-61318494","source":"stackoverflow","questionId":61318494,"title":"Can't change default nuxt favicon","tags":["javascript","vue.js","frontend","nuxt.js","favicon"],"text":"Title: Can't change default nuxt favicon\nTags: javascript, vue.js, frontend, nuxt.js, favicon\nSource: Stack Overflow\n\nQuestion:\nI am new to nuxt and trying to change default favicon in my project.\n\nI changed the `favicon.png` and `favicon.ico` in my `static` folder. => **didn't work**.\n\nchanged the `favicon.png` and `favicon.ico` in my `dist` folder. => **didn't work**.\n\nreplaced the proper files generated by favicon generator websites in my `dist/_nuxt/icons` folder. => **didn't work**.\n\nand this is my `nuxt.config.js`\n\n```\nhead: {\n title: \"my first nuxt proj - main page\",\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: pkg.description }\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.png' }],\n },\n```\n\nam I missing something?\n\n========================================\n\nTop Answer:\nHave you tried replace `type: 'image/x-icon'` with `type: 'image/png'`?\n\nThe infos about this attribute and tag generally can be read here\n\nnuxt will convert object like `{ head: { link: [{ rel: 'icon', type: 'image/png', href: '/favicon.png' }] }}` to\n\n```\n\n \n\n```\n\nSo you can use any attributes listed in the article above.\n\n========================================\n\nCode:\n```text\nhead: {\n title: \"my first nuxt proj - main page\",\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: pkg.description }\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.png' }],\n },\n```\n\n```text\nfavicon.png\n```\n\n```text\nfavicon.ico\n```\n\n```text\nstatic\n```\n\n```text\nfavicon.png\n```\n\n```text\nfavicon.ico\n```\n\n```text\ndist\n```\n\n```text\ndist/_nuxt/icons\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nstatic\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n<head>\n <link rel='icon' type='image/png' href='/favicon.png'>\n</head>\n```\n\n```text\ntype: 'image/x-icon'\n```\n\n```text\ntype: 'image/png'\n```\n\n```text\n{ head: { link: [{ rel: 'icon', type: 'image/png', href: '/favicon.png' }] }}\n```\n\n```text\nnuxt\n```\n\n```text\n/static/icon.png\n```\n\n```text\nnode_modules/.cache/pwa/icon\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run build\n```\n\n```text\nrel: 'icon', type: 'image/png', href: '/favicon.png'\n```\n\n```text\nrel: 'icon', type: 'image/x-icon', href: '/favicon.ico'\n```\n\n```text\n{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n```\n\n```text\nnpm run build\n```\n\n```text\n{rootDir}/node_modules/.cache/pwa/icon\n```\n\n```text\n{rootDir}/node_modules/.cache/nuxt/dist/client/icons\n```\n\n```text\nnpm run build\n\nnpm run generate\n```\n\n```text\n{ rel: 'icon', href: `${storedata.company_logo}?v1` }\n```\n\n```text\nhead: {\n title: \"my first nuxt proj - main page\",\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: pkg.description }\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],\n },\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nfavicon.ico\n```\n\n```js\nexport default defineNuxtConfig({\n devtools: { enabled: true },\n app: {\n head: {\n link: [\n {\n rel: \"icon\",\n type: \"image/png\",\n href: \"/favicon.png\"\n }\n ]\n }\n }\n})\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n<template>\n <Head>\n <Link\n rel=\"apple-touch-icon\"\n sizes=\"180x180\"\n href=\"/favicon/apple-touch-icon.png\"\n />\n <Link\n rel=\"icon\"\n type=\"image/png\"\n sizes=\"32x32\"\n href=\"/favicon/favicon-32x32.png\"\n />\n <Link\n rel=\"icon\"\n type=\"image/png\"\n sizes=\"16x16\"\n href=\"/favicon/favicon-16x16.png\"\n />\n <Link rel=\"manifest\" href=\"/favicon/site.webmanifest\" />\n </Head>\n\n <slot />\n</template>\n```\n\n```text\n<Head>\n```\n\n```text\n<Head>\n <link rel=\"icon\" href=\"/favicon.ico\" type=\"image/x-icon\" />\n</Head>\n```\n\n========================================\n\nComments:\n- Should be working the way you do it. Could you try to remove client cache?\n- @ajobi I found a bad trick. it is about size\n- Ahh okay, didn't expect that :D\n- I did this and it worked for the base favicon, but the icon is still the default NUXT icon for other link tags (e.g rel=\"apple-touch-icon\")\n- I found that there's a node_modules/.cache/pwa/icon directory. I had to remove that and set `pwa: { source: '~/static/icon.png' },` in nuxt.config.js\n- @tgf I think it should be `pwa: { icon: { source: '~/static/icon.png' } }` That is actually the source directory set by default\n- There are uite a few websites doing that but you may use this one to generate a 32x32 sized icon.\n- This doesn't seem like a useful answer, in that it appears you are guessing at the solution, and don't provide context into how/why this solution might work. I think this would be better left as a comment to the OP\n- I couldn't leave a comment, sry. but anyway, You were trying to use png as favicon and facing sizing conflict. That's why it can be a solution. At least it works for me\n- I gotcha @Mik, I forgot about needing rep to comment. Can you update that additional info in your answer at your convenience? Just to make your answer the best it can be =) Looks like the OP may have solved by now, but your answer could be useful to another in the future\n- this answer is to sweep something under the carpet, not solve the question\n- It is possible that the image you linked might not be available at some point in the future. As such, it would be nice if you could put the code into your answer instead of linking an image.\n- Please, post relevant code as text, not an image. Unlike images, text can be easily copied and searched.\n- Make sure someone else didn't overwrite your `pwa` in the same file also... happened to me.\n- Solved the issue for me!\n- Yeah but normally a website needs multiple favicons in different sizes.","metadata":{"transformedAt":"2026-08-18T18:33:07.833Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":270,"estimatedTokens":1491}}60{"id":"stack-55752797","source":"stackoverflow","questionId":55752797,"title":"Nuxt: How to open page in a new tab","tags":["vue-router","nuxt.js"],"text":"Title: Nuxt: How to open page in a new tab\nTags: vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI go through the documentation of Nuxt, but couldn't find information about how to open a page in a new tab. Is there a way to open a link in a new tab instead of opening it in the current tab? I tried the following code:\n\n```\nUser\n```\n\nBut it doesn't work.\n\n========================================\n\nTop Answer:\nAs @anthonygore pointed out in a comment to first post.\nIt's now working to open link in a new tab by , having all the features of router name/path link\n\ndo it with by adding `target=\"_blank\"` to/inside NuxtLink to have\n\n```\nNuxt link to external page\n```\n\nor just use default\n\n```\nA link to external page\n```\n\n========================================\n\nCode:\n```text\n<nuxt-link to=\"/user\" target=\"_blank\">User</nuxt-link>\n```\n\n```text\n<a href=\"/user\" target=\"_blank\">User</a>\n```\n\n```js\n<NuxtLink :to=\"...\" target=\"_blank\">Nuxt link to external page</NuxtLink>\n```\n\n```js\n<a href=\"...\" target=\"_blank\">A link to external page</a>\n```\n\n```text\ntarget=\"_blank\"\n```\n\n```text\n<a href=\"./user\" target=\"_blank\">User</a>\n```\n\n========================================\n\nComments:\n- Adding attribute `target=\"_blank\"` now works\n- Love your cynicism\n- Nuxt 3 Nuxt-link adds the rel=”noreferrer noopener” to external links, so it is advised to use NuxtLink for external links as well, if you're using Nuxt 3\n- @ElPapi42 I don't, it's completely unnecessary and what's more he's not even correct.\n- I think the closing tag in the upper example should be `` instead of ``","metadata":{"transformedAt":"2026-08-18T18:33:07.833Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":66,"estimatedTokens":394}}61{"id":"stack-63096652","source":"stackoverflow","questionId":63096652,"title":"How to ignore the Nuxt.js starting question","tags":["nuxt.js"],"text":"Title: How to ignore the Nuxt.js starting question\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhen I run command `npm run dev` in a nuxt project, there'll be a question asked in the log,\n\nNuxtJS collects completely anonymous data about usage. 23:02:58\nThis will help us improving Nuxt developer experience over the time.\nRead more on https://git.io/nuxt-telemetry\nAre you interested in participation? (Y/n)\n\nI want to know how to skip this question when running the project?\n\n========================================\n\nTop Answer:\nIn command prompt: >set NUXT_TELEMETRY_DISABLED=1\n\n========================================\n\nCode:\n```text\nnpm run dev\n```\n\n```text\nexport default {\n telemetry: false\n }\n```\n\n```text\nNUXT_TELEMETRY_DISABLED=1\n```\n\n```text\nnpx nuxt telemetry [status|enable|disable] [-g,--global] [dir]\n```\n\n========================================\n\nComments:\n- I'm using nuxt version 2.14.6 and the `telemetry: false` option didn't work for me. The `npx` option does it for you, hence it didn't work for me either..\n- I chose option 2, by creating a `.env` file and placing the environment variable in it. I'm using Nuxt 3 and only the first two options work. The telemetry `npx nuxi telemetry` command has been removed. In Nuxt 3 the command is `nuxi` instead of `nuxt`. I chose the environment variable option because putting `telemetry: false` in `nuxt.config.js` results in a TypeScript error, because as of now they haven't properly defined the type to include the telemetry option.\n- Building with Docker/Podman and using the suggested environment flag worked for me. Example: `ENV NUXT_TELEMETRY_DISABLED=1`. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:07.834Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":46,"estimatedTokens":411}}62{"id":"stack-70396414","source":"stackoverflow","questionId":70396414,"title":"NuxtLink is updating route in nuxt 3 app, but not rendering contents","tags":["vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: NuxtLink is updating route in nuxt 3 app, but not rendering contents\nTags: vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to use route using NuxtLink in a Nuxt 3 app, and it's changing the route, but it's not showing any contents. But, if I refresh or reload the updated route which was blank ago, then it's showing it's content normally.\n\n`/pages/index.vue`\n\n```\n\n \n \n\n### It's Nuxt3!\n\n Home Page\n\n \n User\n\n```\n\n`/pages/user.vue`\n\n```\n\n \n \n\n### It's Nuxt3!\n\n User Page\n\n \n\n```\n\nFolder Structure & Illustration:\n\nhttps://i.sstatic.net/rBCHq.png\n\nhttps://i.sstatic.net/AAzZQ.gif\n\n========================================\n\nCode:\n```html\n<template>\n <div>\n <h1>It's Nuxt3!</h1>\n <p>Home Page</p>\n </div>\n <NuxtLink to=\"/user\">User</NuxtLink>\n</template>\n```\n\n```html\n<template>\n <div>\n <h1>It's Nuxt3!</h1>\n <p>User Page</p>\n </div>\n</template>\n```\n\n```text\n/pages/index.vue\n```\n\n```text\n/pages/user.vue\n```\n\n```text\n[Vue warn]: Component inside <Transition> renders non-element root node that cannot be animated. \n at <Index onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< VueInstance > key=\"/\" > \n at <BaseTransition mode=\"out-in\" appear=false persisted=false ... > \n at <Transition name=\"page\" mode=\"out-in\" > \n at <NuxtLayout key=0 name=undefined > \n at <RouterView> \n at <NuxtPage> \n at <App> \n at <NuxtRoot>\n```\n\n```html\n<template>\n <div> 1️⃣ <!-- root node -->\n <h1>Hello, World</h1>\n <p>It's Nuxt3!</p>\n </div>\n <NuxtLink to=\"/user\">User</NuxtLink> 2️⃣ <!-- root node -->\n</template>\n```\n\n```html\n// index.vue\n<template>\n <div> 👈 <!-- single root node -->\n <div>\n <h1>Hello, World</h1>\n <p>It's Nuxt3!</p>\n <div>\n <NuxtLink to=\"/user\">User</NuxtLink>\n </div>\n</template>\n```\n\n```text\n<Index>\n```\n\n```text\nindex.vue\n```\n\n```text\ndiv\n```\n\n========================================\n\nComments:\n- As written here, this is something that is required to allow for proper animations. This is not a Nuxt limitation, because in Vue's doc, it also states ` only supports a single element or component as its slot content. If the content is a component, the component must also have only one single root element`, hence everything is as expected.\n- Even having commented code before the root node will break the rendering process!\n- @PouyaM Thank you!!! I had no idea a comment before the root node on any of the pages/components I was trying to render would have caused this issue - yes I am using transitions for anyone else who stumbles here","metadata":{"transformedAt":"2026-08-18T18:33:07.834Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":127,"estimatedTokens":633}}63{"id":"stack-56912847","source":"stackoverflow","questionId":56912847,"title":"NuxtJs Cannot read property '_normalized' of undefined","tags":["javascript","vue.js","nuxt.js"],"text":"Title: NuxtJs Cannot read property '_normalized' of undefined\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nthis error show when I try to fetch some data in nuxtjs\n\n```\nCannot read property '_normalized' of undefined\n```\n\nThis is my axios request in nuxtjs :\n\n```\nasync asyncData({app}){\n var response = await app.$axios.get('/store/get-services',{params:{id:app.$auth.user.store.id}});\n return {services:response.data.services};\n }\n```\n\nthis is a backend controller laravel:\n\n```\npublic function store_ads(Request $req){\n if($req->user()->store->id != $req->id){\n abort(403);\n }\n $services = Store::select('id')->with('ads:id,store_id,price,title')->where('id',$req->id)->first();\n return response()->json(['services'=>$services],200);\n}\n```\n\nand here is how i fetch them in my template:\n\n```\n\n \n\n### No Services\n\n \n \n- {{service.title}}\n \n \n```\n\nWhat is the reason?\n\n========================================\n\nTop Answer:\nHad the same error message. Changing the order in the `v-for`-loops solved the problem for me.\n\nBefore my `v-for` looked like this:\n\n```\n\n{{ highlight.title }}\n\n```\n\nI changed the order of the attributes to:\n\n```\n\n{{ highlight.title }}\n\n```\n\nNote: I used Vue.js with Nuxt.js\n\n========================================\n\nCode:\n```text\nCannot read property '_normalized' of undefined\n```\n\n```text\nasync asyncData({app}){\n var response = await app.$axios.get('/store/get-services',{params:{id:app.$auth.user.store.id}});\n return {services:response.data.services};\n }\n```\n\n```text\npublic function store_ads(Request $req){\n if($req->user()->store->id != $req->id){\n abort(403);\n }\n $services = Store::select('id')->with('ads:id,store_id,price,title')->where('id',$req->id)->first();\n return response()->json(['services'=>$services],200);\n}\n```\n\n```text\n<div class=\"services-list\">\n <h4 class=\"is-vcentered title has-text-centered has-text-grey-light\" v-if=\"services.ads.length==0\">No Services</h4>\n <ul>\n <li v-for=\"service in services.ads\" :key=\"service.id\"><nuxt-link>{{service.title}}</nuxt-link></li>\n </ul>\n </div>\n```\n\n```text\nto\n```\n\n```text\n<nuxt-link></nuxt-link>\n```\n\n```text\n<NuxtLink v-for=\"(key, highlight) in highlights\" :key=\"key\" :to=\"highlight.url\">\n{{ highlight.title }}\n</NuxtLink>\n```\n\n```text\n<NuxtLink v-for=\"(highlight, key) in highlights\" :key=\"key\" :to=\"highlight.url\">\n{{ highlight.title }}\n</NuxtLink>\n```\n\n```text\nv-for\n```\n\n```text\nv-for\n```\n\n========================================\n\nComments:\n- Exactly. Nuxt.js could provide a better error message than this one.\n- Yeah, cryptic error, how could anyone understand it without googling.\n- In my case was problem with undefined url for `this.$router.push(...)`","metadata":{"transformedAt":"2026-08-18T18:33:07.834Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":139,"estimatedTokens":707}}64{"id":"stack-75941108","source":"stackoverflow","questionId":75941108,"title":"Cannot find name 'defineNuxtConfig'.ts(2304)","tags":["nuxt.js","nuxt3.js"],"text":"Title: Cannot find name 'defineNuxtConfig'.ts(2304)\nTags: nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI tried to install Nuxt 3 layers inside a monorepo with turborepo. and I somehow get error with typescript where it's seems to not able to figure out nuxt\n\ndefineNuxtConfig not find\n\nappConfig not found\n\nthe ts config file look like this:\n\n```\n{\n \"extends\": \"./.playground/.nuxt/tsconfig.json\"\n}\n```\n\nand on .playground/.nuxt folder there's tsconfig that look like this(auto-generated):\n\n```\n// Generated by nuxi\n{\n \"compilerOptions\": {\n \"forceConsistentCasingInFileNames\": true,\n \"jsx\": \"preserve\",\n \"target\": \"ESNext\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\",\n \"skipLibCheck\": true,\n \"strict\": true,\n \"allowJs\": true,\n \"noEmit\": true,\n \"resolveJsonModule\": true,\n \"allowSyntheticDefaultImports\": true,\n \"types\": [\n \"node\"\n ],\n \"baseUrl\": \"..\",\n \"paths\": {\n \"~\": [\n \".\"\n ],\n \"~/*\": [\n \"./*\"\n ],\n \"@\": [\n \".\"\n ],\n \"@/*\": [\n \"./*\"\n ],\n \"~~\": [\n \".\"\n ],\n \"~~/*\": [\n \"./*\"\n ],\n \"@@\": [\n \".\"\n ],\n \"@@/*\": [\n \"./*\"\n ],\n \"assets\": [\n \"assets\"\n ],\n \"public\": [\n \"public\"\n ],\n \"#app\": [\n \"../../../node_modules/nuxt/dist/app\"\n ],\n \"#app/*\": [\n \"../../../node_modules/nuxt/dist/app/*\"\n ],\n \"vue-demi\": [\n \"../../../node_modules/nuxt/dist/app/compat/vue-demi\"\n ],\n \"@vueuse/head\": [\n \"../../../node_modules/@unhead/vue/dist/index\"\n ],\n \"#imports\": [\n \".nuxt/imports\"\n ],\n \"#build\": [\n \".nuxt\"\n ],\n \"#build/*\": [\n \".nuxt/*\"\n ],\n \"#components\": [\n \".nuxt/components\"\n ]\n }\n },\n \"include\": [\n \"./nuxt.d.ts\",\n \"../**/*\"\n ],\n \"exclude\": [\n \"../dist\",\n \"../.output\"\n ]\n}\n```\n\nhow can i fix this so that defineNuxtConfig is recognized properly?\n\nremove error Cannot find name 'defineNuxtConfig'.ts(2304)\n\n========================================\n\nTop Answer:\nNot an automatic solution, but you can import the symbol manually:\n\n```\nimport { defineNuxtConfig } from 'nuxt/config'\n```\n\n========================================\n\nCode:\n```text\n{\n \"extends\": \"./.playground/.nuxt/tsconfig.json\"\n}\n```\n\n```text\n// Generated by nuxi\n{\n \"compilerOptions\": {\n \"forceConsistentCasingInFileNames\": true,\n \"jsx\": \"preserve\",\n \"target\": \"ESNext\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\",\n \"skipLibCheck\": true,\n \"strict\": true,\n \"allowJs\": true,\n \"noEmit\": true,\n \"resolveJsonModule\": true,\n \"allowSyntheticDefaultImports\": true,\n \"types\": [\n \"node\"\n ],\n \"baseUrl\": \"..\",\n \"paths\": {\n \"~\": [\n \".\"\n ],\n \"~/*\": [\n \"./*\"\n ],\n \"@\": [\n \".\"\n ],\n \"@/*\": [\n \"./*\"\n ],\n \"~~\": [\n \".\"\n ],\n \"~~/*\": [\n \"./*\"\n ],\n \"@@\": [\n \".\"\n ],\n \"@@/*\": [\n \"./*\"\n ],\n \"assets\": [\n \"assets\"\n ],\n \"public\": [\n \"public\"\n ],\n \"#app\": [\n \"../../../node_modules/nuxt/dist/app\"\n ],\n \"#app/*\": [\n \"../../../node_modules/nuxt/dist/app/*\"\n ],\n \"vue-demi\": [\n \"../../../node_modules/nuxt/dist/app/compat/vue-demi\"\n ],\n \"@vueuse/head\": [\n \"../../../node_modules/@unhead/vue/dist/index\"\n ],\n \"#imports\": [\n \".nuxt/imports\"\n ],\n \"#build\": [\n \".nuxt\"\n ],\n \"#build/*\": [\n \".nuxt/*\"\n ],\n \"#components\": [\n \".nuxt/components\"\n ]\n }\n },\n \"include\": [\n \"./nuxt.d.ts\",\n \"../**/*\"\n ],\n \"exclude\": [\n \"../dist\",\n \"../.output\"\n ]\n}\n```\n\n```text\nUse workspace version\n```\n\n```text\nUse VS Code's Version\n```\n\n```text\nF1\n```\n\n```text\nCtrl + Shift + P\n```\n\n```text\nVolar: Select Typescript Version\n```\n\n```text\nUse workspace version\n```\n\n```text\nUse VS Code's Version\n```\n\n```text\nimport { defineNuxtConfig } from 'nuxt/config'\n```\n\n```json\n{\n \"extends\": \"./.nuxt/tsconfig.json\"\n}\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- Did u manage to solve the issue? It is impacting auto import on the whole layer which is very annoying to keep consistency across the monorepo\n- As of December 2025 this fix did not work for me. To remove errors such as \"Cannot find name 'defineNuxtConfig'.ts(2304)\" I had to the instructions on the Nuxt.js typescript documentation, at nuxt.com/docs/4.x/guide/concepts/typescript. You simply have to add vue-tsc and typescript to your dev dependencies, like (pick the package manager you are using) : bun add -D vue-tsc typescript It will generate a .nuxt folder at the root of your project.\n- Could you please explain the reason why this is required, moreover if possible also provide the `command` for doing so.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- The extension is deprecated :(\n- this is working fine, except when you have a .playground folder... for some reason \"extends\": \"./.playground/.nuxt/tsconfig.json\" is not working for me\n- I have switched from `rootDir` to `srcDir` in order to keep default path for `extends`.\n- This worked beautifully in my Nuxt 3 project using the official VSCode plugin for Nuxt. Just an additional note, it only worked once I removed all of my other options I had put in my `tsconfig.json` file. Closed the server and rebuilt the project for it to take affect. Thank you @Fifciuu!\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:07.834Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":271,"estimatedTokens":1423}}65{"id":"stack-74945103","source":"stackoverflow","questionId":74945103,"title":"How to catch a route and redirect to Another Page in Nuxt 3","tags":["nuxt.js","vuejs3","middleware"],"text":"Title: How to catch a route and redirect to Another Page in Nuxt 3\nTags: nuxt.js, vuejs3, middleware\nSource: Stack Overflow\n\nQuestion:\nI have a website that I have rebuilt using Nuxt 3. Backlinks exists on numerous platforms and I need the old links to point to the new pages.\nExample:\nold(website.com/contact.html) new(website.com/contact)\n\nI tried using middleware, but after deploying it, I get this error:\n502 Error decoding lambda response\n\nIn my middleware/redirect folder I have this:\n\n```\nconst redirects = [{\n 'from' : '/contact.html',\n 'to' : '/contact'\n}]\n\nexport default function (req, res, next) {\n const redirect = redirects.find((r)=> r.from === req.url)\n\n if (redirect) {\n res.writeHead(301, { Location: redirect.to })\n res.end()\n } else {\n next()\n }\n}\n```\n\nIt works locally but not after deploying to netlify!\n\nand I added this to my nuxtconfig file:\n\n```\nserverMiddleware: [\n '~/middleware/redirect'\n ]\n```\n\nI thought that this middleware would act as a net to catch any req to the old contacts.html page and redirect them to the new contact page. but instead it sends that lambda error which I looked around and have not found a solid fix for. I am open to any solution including a different way of redirecting!\nThank you!\n\n========================================\n\nTop Answer:\nInstead of building your own middleware, you can add your own router options. Here are the docs.\n\n- Create a folder called `app` in the root of your project (same folder as `nuxt.config.ts`.\n\n- Inside`/app` create file `router.options.ts`.\n\n- Inside `router.options.ts` write:\n\n```\nimport type { RouterOptions } from '@nuxt/schema';\n\n// https://router.vuejs.org/api/interfaces/routeroptions.html\nexport default {\n routes: (_routes) => [\n {\n name: 'contact',\n path: '/contact',\n component: () => import('~/pages/contact.vue'),\n alias: '/contact.html',\n },\n ],\n};\n```\n\nEDIT:\nYou could also use `definePageMeta` with `alias`. Docs.\n\n========================================\n\nCode:\n```text\nconst redirects = [{\n 'from' : '/contact.html',\n 'to' : '/contact'\n}]\n\nexport default function (req, res, next) {\n const redirect = redirects.find((r)=> r.from === req.url)\n\n if (redirect) {\n res.writeHead(301, { Location: redirect.to })\n res.end()\n } else {\n next()\n }\n}\n```\n\n```text\nserverMiddleware: [\n '~/middleware/redirect'\n ]\n```\n\n```js\nexport default defineNuxtConfig({\n routeRules: {\n '/contact.html': { redirect: '/contact' },\n '/external-route': { redirect: 'https://example.com' },\n },\n})\n```\n\n```text\nredirect\n```\n\n```text\nrouteRules\n```\n\n```text\nnuxt.config.ts\n```\n\n```js\nimport type { RouterOptions } from '@nuxt/schema';\n\n// https://router.vuejs.org/api/interfaces/routeroptions.html\nexport default <RouterOptions>{\n routes: (_routes) => [\n {\n name: 'contact',\n path: '/contact',\n component: () => import('~/pages/contact.vue'),\n alias: '/contact.html',\n },\n ],\n};\n```\n\n```text\napp\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n/app\n```\n\n```text\nrouter.options.ts\n```\n\n```text\nrouter.options.ts\n```\n\n```text\ndefinePageMeta\n```\n\n```text\nalias\n```\n\n========================================\n\nComments:\n- The best would probably be to make the redirects directly on the platform itself (before it even reaches your app) with a rule so that it matches what you had before and what you have now in Nuxt.\n- I agree its a better solution to change the links directly. I was just trying to save a bit of time and effort because some of the backlinks are in blogs/articles on other peoples websites.\n- Even tho this is a viable solution, it's more of a front-end one (client-side navigation) and not related to server-side/DNS redirections.\n- Is it possible to reroute multiple pages like so? /contact/** to example.com**\n- Do you also know how to keep the query parameters? This way they get lost.\n- This is still an experimental feature (at least it says so in the code). This works: \"/foo/:id\": { redirect: \"/bar\" } for redirecting all pages to one page, but I can't figure out how to do something like this: \"/foo/:id\": { redirect: \"/bar/:id\" }. It just puts ':id' in the address bar.\n- @DavidStack You have to define it like so `'/old-page/**': { redirect: '/new-page/**' },`","metadata":{"transformedAt":"2026-08-18T18:33:07.834Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":177,"estimatedTokens":1070}}66{"id":"stack-52576160","source":"stackoverflow","questionId":52576160,"title":"Nuxt Auth - User Data not set","tags":["authentication","axios","vuex","nuxt.js"],"text":"Title: Nuxt Auth - User Data not set\nTags: authentication, axios, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI try to do a login via nuxt-auth module. As a response I get the token and then the user data is delivered. However, `this.$Auth.loggedIn` is `false` and `this.$Auth.user` is `undefined`. I have been fighting for 3 days and can not get any further. Hope somebody can help me.\n\n**login**\n\n```\nawait this.$auth.login({\n data: {\n email: this.email,\n password: this.password\n }\n}).then(() => {\n this.$router.push('/dashboard')\n}).catch(err => {\n this.snackbar.show = true;\n})\n```\n\n**nuxt.config.js**\n\n```\nauth: {\n strategies: {\n local: {\n endpoints: {\n login: {\n url: '/auth/login',\n method: 'post',\n propertyName: 'access_token'\n },\n logout: {\n url: '/auth/logout',\n method: 'post'\n },\n user: {\n url: '/auth/me',\n method: 'post'\n },\n tokenRequired: true\n }\n }\n }\n}\n```\n\n**response login**\n\n```\n{\n\"access_token\": \"xxxxxxxxxxxxx.eyJpc3MiOiJodHRwczpcL1wvYXBpLmFwcHJlexxxxxxxcxXRoXC9sb2dpbiIsImlhdCI6MTUzODI5NTczMywiZXhwIjoxNTM4Mjk5MzMzLCJuYmYiOjE1MzgyOTU3MzMsImp0aSI6ImdtWWVyZTViQjk1cU5BRG8iLCJzdWIiOjIsInBydiI6IjYwODM2NzQ0MzQ4ZDQzMTk4NzE4N2ZjMWM2YzIzMjYxMDcyMWE5ZjAifQ.JhOiwIg7StzZR71aqYyI9rJpPXVclmddzPSIwqCIUN4\",\n\"token_type\": \"bearer\",\n\"expires_in\": 3600\n}\n```\n\n**response user**\n\n```\n{\n \"id\": 2,\n \"name\": \"Dominik Dummy\",\n \"email\": \"dummy@andreas-pabst.de\",\n \"created_at\": {\n \"date\": \"2018-09-28 09:11:31.000000\",\n \"timezone_type\": 3,\n \"timezone\": \"UTC\"\n },\n \"updated_at\": {\n \"date\": \"2018-09-28 09:11:31.000000\",\n \"timezone_type\": 3,\n \"timezone\": \"UTC\"\n },\n \"self\": \"https:\\/\\/api.apprex.de\\/api\\/users\\/2\"\n}\n```\n\nhttps://i.sstatic.net/E2epz.png\n\n========================================\n\nTop Answer:\n**Update for auth-next\": \"^5.0.0\"**\n\nYou will have to set `property: false` instead of `propertyName`.\nSo your nuxt.config.js might be as follows:\n\n```\nauth: {\n strategies: {\n local: {\n token: {\n property: 'access_token',\n required: true,\n type: 'Bearer'\n },\n user: {\n property: false, // <--- Default \"user\"\n autoFetch: true\n },\n endpoints: {\n login: { url: 'api/login', method: 'post' },\n logout: { url: 'api/auth/logout', method: 'post' },\n user: { url: 'api/user', method: 'get' }\n }\n }\n }\n },\n```\n\n========================================\n\nCode:\n```text\nawait this.$auth.login({\n data: {\n email: this.email,\n password: this.password\n }\n}).then(() => {\n this.$router.push('/dashboard')\n}).catch(err => {\n this.snackbar.show = true;\n})\n```\n\n```text\nauth: {\n strategies: {\n local: {\n endpoints: {\n login: {\n url: '/auth/login',\n method: 'post',\n propertyName: 'access_token'\n },\n logout: {\n url: '/auth/logout',\n method: 'post'\n },\n user: {\n url: '/auth/me',\n method: 'post'\n },\n tokenRequired: true\n }\n }\n }\n}\n```\n\n```text\n{\n\"access_token\": \"xxxxxxxxxxxxx.eyJpc3MiOiJodHRwczpcL1wvYXBpLmFwcHJlexxxxxxxcxXRoXC9sb2dpbiIsImlhdCI6MTUzODI5NTczMywiZXhwIjoxNTM4Mjk5MzMzLCJuYmYiOjE1MzgyOTU3MzMsImp0aSI6ImdtWWVyZTViQjk1cU5BRG8iLCJzdWIiOjIsInBydiI6IjYwODM2NzQ0MzQ4ZDQzMTk4NzE4N2ZjMWM2YzIzMjYxMDcyMWE5ZjAifQ.JhOiwIg7StzZR71aqYyI9rJpPXVclmddzPSIwqCIUN4\",\n\"token_type\": \"bearer\",\n\"expires_in\": 3600\n}\n```\n\n```text\n{\n \"id\": 2,\n \"name\": \"Dominik Dummy\",\n \"email\": \"dummy@andreas-pabst.de\",\n \"created_at\": {\n \"date\": \"2018-09-28 09:11:31.000000\",\n \"timezone_type\": 3,\n \"timezone\": \"UTC\"\n },\n \"updated_at\": {\n \"date\": \"2018-09-28 09:11:31.000000\",\n \"timezone_type\": 3,\n \"timezone\": \"UTC\"\n },\n \"self\": \"https:\\/\\/api.apprex.de\\/api\\/users\\/2\"\n}\n```\n\n```text\nthis.$Auth.loggedIn\n```\n\n```text\nfalse\n```\n\n```text\nthis.$Auth.user\n```\n\n```text\nundefined\n```\n\n```text\nauth: {\nstrategies: {\n local: {\n endpoints: {\n login: {\n url: '/auth/login',\n method: 'post',\n propertyName: 'access_token'\n },\n logout: {\n url: '/auth/logout',\n method: 'post'\n },\n user: {\n url: '/auth/me',\n method: 'post',\n propertyName: false // <--- Default \"user\"\n }\n }\n }\n}\n}\n```\n\n```text\nauth.fetchUser()\n```\n\n```text\nuser\n```\n\n```text\nthis.$auth.fetchUser()\n```\n\n```text\nuser\n```\n\n```text\nloggedIn\n```\n\n```text\nauth\n```\n\n```text\nauth: {\n strategies: {\n local: {\n token: {\n property: 'access_token',\n required: true,\n type: 'Bearer'\n },\n user: {\n property: false, // <--- Default \"user\"\n autoFetch: true\n },\n endpoints: {\n login: { url: 'api/login', method: 'post' },\n logout: { url: 'api/auth/logout', method: 'post' },\n user: { url: 'api/user', method: 'get' }\n }\n }\n }\n },\n```\n\n```text\nproperty: false\n```\n\n```text\npropertyName\n```\n\n========================================\n\nComments:\n- Are u sure you need post request for getting user? If so - check the network if the user get request done.\n- No, its called automatically after login github.com/nuxt-community/auth-module/blob/dev/lib/schemes/…\n- Yes I know it, but I think you wanted to call it manually and if you have the response from `self` API so it would be great and you can reload the page after getting the response for debugging it if user object fills after reload make sure you `this.$auth.fetchUser()` does work, else trouble due to not call `fetchUser` function\n- thanks for this function! This needs to be called if we are updating user's data on backend\n- Note that some tutorials I've seen say to set `propertyName` to `undefined` — that doesn't work. Your answer is the only one that's worked for me!\n- you save my time\n- Thank you for posting an updated answer 👍\n- I wanted to avoid making an extra request to the `user` endpoint. To do this, I also needed to set `endpoints.user` to `false`. As the documentation says: \"...unless you disable the user endpoint with endpoints.user: false you will still need to implement the user endpoint so that auth can fetch the user information on e.g. page refresh.\" (auth.nuxtjs.org/schemes/local/#user)","metadata":{"transformedAt":"2026-08-18T18:33:07.834Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":288,"estimatedTokens":1602}}67{"id":"stack-72526965","source":"stackoverflow","questionId":72526965,"title":"How to specify useFetch data return type in Nuxt","tags":["javascript","typescript","vue.js","nuxt.js"],"text":"Title: How to specify useFetch data return type in Nuxt\nTags: javascript, typescript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am fetching data from an API in Nuxt3. I am using typescript and I wish to define the type of data that I will get. How do I specify this?\n\n```\n\n interface APIBody {\n /* properties defined here */\n }\n\n const {data} = await useFetch(\"api_url here\")\n\n {{ data.name.officialName }}\n\n```\n\nI get an error in the `template` where I am displaying `data.name.officialName`\n\nProperty 'name' does not exist on type 'never'\n\nHowever, while running the code in the browser, the website works fine.\n\n**Edit**\nI tried the following code but I am receiving a different error now.\n\n```\n\n interface APIBody {\n /* properties defined here */\n }\n\n const typedData = ref()\n const {data} = await useFetch(\"api_url here\")\n typedData.value = data as APIBody[] // -> error here\n\n {{ data.name.officialName }}\n\n```\n\nThe error in this case is:\n\nConversion of type 'Ref>' to type 'APIBody[]' may be a mistake because neither type sufficiently overlaps with the other.\n\n========================================\n\nTop Answer:\nIt's my working example in Nuxt 3.9.0:\n\n```\n// /api/test.post.ts\nexport default defineEventHandler(async (event) => {\n const body = await readBody(event);\n return { body };\n});\n```\n\nIn any component or page:\n\n```\n\nimport type { AsyncData } from 'nuxt/app';\nimport type { FetchError } from 'ofetch';\n \ninterface Body { key: string };\n \nconst { data: { value: { body } }, error } = await useFetch('/api/test', {\n method: 'post',\n body: {\n key: 'value',\n }\n }) as AsyncData;\n \n// now you're getting body's properties without ts-errors\nconsole.log(body.key); // value\n\n```\n\n========================================\n\nCode:\n```html\n<script lang=\"ts\" setup>\n interface APIBody {\n /* properties defined here */\n }\n\n const {data} = await useFetch(\"api_url here\")\n</script>\n\n<template>\n {{ data.name.officialName }}\n<template>\n```\n\n```html\n<script lang=\"ts\" setup>\n interface APIBody {\n /* properties defined here */\n }\n\n const typedData = ref<APIBody[]>()\n const {data} = await useFetch(\"api_url here\")\n typedData.value = data as APIBody[] // -> error here\n</script>\n\n<template>\n {{ data.name.officialName }}\n<template>\n```\n\n```text\ntemplate\n```\n\n```text\ndata.name.officialName\n```\n\n```text\ninterface APIBody {\n /* properties defined here */\n }\n\n const {data} = await useFetch<APIBody>(\"api_url here\")\n```\n\n```text\nuseFetch\n```\n\n```js\ntype SomeProps = {\n prop1: string;\n prop2: string;\n};\n\nexport function usePropsApi() {\n const { public: { api } } = useRuntimeConfig();\n\n return {\n read: <T extends keyof SomeProps>({\n pick = [],\n }: {\n pick?: Array<T>;\n } = {}) => useFetch<Pick<SomeProps, T>>('/props', {\n baseURL: api,\n ...(pick.length && pick),\n }),\n };\n}\n```\n\n```js\nconst { data } = await usePropsApi().read({\n pick: ['prop1'],\n});\nconsole.log('data.value: ', data.value?.prop1);\nconsole.log('data.value: ', data.value?.prop2); // Property 'prop2' does not exist on type ...\n```\n\n```text\npick\n```\n\n```text\npick[]\n```\n\n```text\n// /api/test.post.ts\nexport default defineEventHandler(async (event) => {\n const body = await readBody(event);\n return { body };\n});\n```\n\n```text\n<script lang=\"ts\" setup>\nimport type { AsyncData } from 'nuxt/app';\nimport type { FetchError } from 'ofetch';\n \ninterface Body { key: string };\n \nconst { data: { value: { body } }, error } = await useFetch('/api/test', {\n method: 'post',\n body: {\n key: 'value',\n }\n }) as AsyncData<{ body: Body }, FetchError>;\n \n// now you're getting body's properties without ts-errors\nconsole.log(body.key); // value\n</script>\n```\n\n========================================\n\nComments:\n- how to parse data from this APIBody then? @under_koen\n- What do you mean? Accesing the content within the APIBody? If so you can just use `data.name` for example. You need to define `name` then in the `APIBody` interface\n- the problem is that it's not defining correct typing for the extracted data, I receive `const data: globalThis.Ref> | null>` even though I've provided proper interface to the `useFetch`.\n- @adyry this is expected, `_ResT` is `IProductResponse` in your case. `PickFrom`, `Ref` and `KeyOfRes` are utilty types to transform your type to be more correct with the actual response.\n- But then when I try to access property via `data.value.reviewed` of the response, typescript yields `TS2339: Property 'reviewed' does not exist on type 'NonNullable _ResT, KeyOfRes >>'.` so it's not seeing `IProductResponse` properly\n- Could you create an different question with code?","metadata":{"transformedAt":"2026-08-18T18:33:07.834Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":207,"estimatedTokens":1175}}68{"id":"stack-74902697","source":"stackoverflow","questionId":74902697,"title":"Error: `The request url * is outside of Vite serving allow list` after git init of submodule inside pnpm monorepo workspace","tags":["nuxt.js","vite","pnpm-workspace"],"text":"Title: Error: `The request url * is outside of Vite serving allow list` after git init of submodule inside pnpm monorepo workspace\nTags: nuxt.js, vite, pnpm-workspace\nSource: Stack Overflow\n\nQuestion:\nI have setup a pnpm workspace with a number of projects that I am adding as git submodules.\n\nA previously working Nuxt project suddenly started giving the error `The request url * is outside of Vite serving allow list` for multiple files, including dependencies installed as pnpm modules inside the **workspace** `node_modules` folder.\n\nThe only change had been to initialise my project as a git repository.\n\nI was expecting the dev server to keep working, and that changes to git would not have any effect.\n\nThe project still builds ok.\n\n========================================\n\nTop Answer:\nThe recommended method is to add it to the `server.fs.allow` list:\n\n```\nimport { defineConfig, searchForWorkspaceRoot } from 'vite'\n \nexport default defineConfig({\n server: {\n fs: {\n allow: [\n // search up for workspace root\n searchForWorkspaceRoot(process.cwd()),\n // your custom rules\n '/path/to/custom/allow',\n ],\n },\n },\n})\n```\n\n========================================\n\nCode:\n```text\nThe request url * is outside of Vite serving allow list\n```\n\n```text\nnode_modules\n```\n\n```js\nexport default defineNuxtConfig({\n vite: {\n server: {\n fs: {\n allow: [\"/home/user/Monorepo\"]\n }\n }\n }\n})\n```\n\n```text\nnode_modules\n```\n\n```js\nimport { defineConfig, searchForWorkspaceRoot } from 'vite'\n \nexport default defineConfig({\n server: {\n fs: {\n allow: [\n // search up for workspace root\n searchForWorkspaceRoot(process.cwd()),\n // your custom rules\n '/path/to/custom/allow',\n ],\n },\n },\n})\n```\n\n```text\nserver.fs.allow\n```\n\n```text\nserver: {\n fs: {\n // Allow serving files from one level up to the project root\n allow: ['..'],\n },\n},\n```\n\n```text\nviteConf.server = {\n ...viteConf.server,\n fs: {\n strict: false // Disable strict file serving restrictions\n }\n };\n```\n\n```text\nnpm run build\n```\n\n========================================\n\nComments:\n- Related (unanwsered) questions: stackoverflow.com/questions/74326498/…, stackoverflow.com/questions/74264304/…\n- Works nice with absolute paths, but couldn't figure out how to make it work with relative paths (better in teams).\n- I tried this: stackoverflow.com/a/72327029/5935615 but the only thing that worked (but it feels a little bit dirty) is, instead of setting vite.server.fs.allow as you did, setting vite.server.fs.strict to false.\n- stackoverflow.com/questions/71113423/…\n- I've tried this solution with my own user path to the project, but still getting \"Failed to load url\" and \"The request url...is outside of Vite serving allow list\" errors. I'm not using pnpm workspace. My Node version is v18.15.0. Nuxt 3.3.3. My Nuxt app also worked fine before initializing as git repository. Now the app is constantly trying to load (browser tab spinning) and does not hot-reload. Is there something I'm missing? Any help appreciated!\n- @Anelec It's hard to say without knowing what you *are* using, npm workspace? You might also be able to output the result of `searchForWorkspaceRoot` to help with debugging and compare this to where your node_modules are in your setup. If that's not enough to resolve the issue then I'd suggest asking your own question and linking it to this one, then you can explain properly what your setup is and how/why this solution isn't working for you. hth\n- @a2k42 thanks for your response! i'm new to nuxt and don't know how to do the `searchForWorkspaceRoot` function...but yes I'm using an npm workspace and here's a repo of the test project in which i'm getting the errors. i'm happy to create a new question too, if this is too much for comments\n- @anelec the path you've used in the allow array looks suspect to me\n- @a2k42 wow. i added a few more lines to the code. including a path to the local project and a path to the global \"node_modules\" folder on the system – with and without the asterisk to include all folders within....that seemed to do the trick. thanks so much for your help. you have no idea how long this took me and i don't know why it didn't work before.\n- I know it's recommended in the docs, but I wonder if `searchForWorkspaceRoot(process.cwd())` is really necessary. Maybe you can just use `'.'` if `vite.config.js` is run from your project root folder already.\n- While securing your back end is a common focus, there's two problems with this comment: (1) This is actually securing the \"back-end\" (file system) of your development machine — without this random users on your network may be able to read ANY file on your machine = not good! (2) Front end security *IS* actually a big deal, and if you ignore it, attackers may be able to steal cookies, session tokens, users' location data, localStorage data, gain admin rights to your app, and inject all sorts of nasty content that attacks you or your users.","metadata":{"transformedAt":"2026-08-18T18:33:07.834Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":121,"estimatedTokens":1270}}69{"id":"stack-52885180","source":"stackoverflow","questionId":52885180,"title":"Can anyone help implementing Nuxt.js Google Tag Manager?","tags":["vue.js","google-tag-manager","nuxt.js"],"text":"Title: Can anyone help implementing Nuxt.js Google Tag Manager?\nTags: vue.js, google-tag-manager, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHey i've built a Nuxt app and am having trouble with the package `@nuxtjs/google-tag-manager` package. Found below. The documentation is pretty light and I haven't found many example implementations out there. In my `nuxt.config.js` I have the following set.\n\n```\n['@nuxtjs/google-tag-manager', {\n id: process.env.GTM_ID,\n layer: 'dataLayer',\n pageTracking: true\n}],\n```\n\n..but unfortunately am not getting any *Page Views* in Google Tag Manager\n\nDoes anyone have any ideas or experience in how to best implement GTM or what has worked for them?\n\nThanks in advance\n\n========================================\n\nCode:\n```text\n['@nuxtjs/google-tag-manager', {\n id: process.env.GTM_ID,\n layer: 'dataLayer',\n pageTracking: true\n}],\n```\n\n```text\n@nuxtjs/google-tag-manager\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nfunction startPageTracking(ctx) {\n ctx.app.router.afterEach((to) => {\n setTimeout(() => {\n ctx.$gtm.push(to.gtm || {\n routeName: to.name,\n pageType: 'PageView',\n pageUrl: '<%= options.routerBase %>' + to.fullPath,\n pageTitle: (typeof document !== 'undefined' && document.title) || '',\n event: '<%= options.pageViewEventName %>'\n })\n }, 250)\n })\n}\n```\n\n```text\n{\nrouteName: to.name,\npageType: 'PageView',\npageUrl: '<%= options.routerBase %>' + to.fullPath,\npageTitle: (typeof document !== 'undefined' && document.title) || '',\nevent: '<%= options.pageViewEventName %>' //default is 'nuxtRoute'\n}\n```\n\n```text\nhttps://github.com/nuxt-community/gtm-module/blob/master/lib/defaults.js\n```\n\n```text\npageUrl\n```\n\n```text\nrouteName\n```\n\n========================================\n\nComments:\n- Do you have your GA tags configured properly in GTM?\n- Thanks for the detailed reply @XTOTHEL, I really appreciate you taking the time to put this together. The marketing team i'm working with were wanting to setup the trigger a s a 'Page View' rather than a custom event though, and currently page views aren't coming through. There has to be a way!\n- When you set it up as instructed. It will come through as a page view. The events in the data layer is just the triggering event for the pageview.\n- The data layer events are not the same as events in GA.\n- Is there a way that the trigger could be the page view event rather than a custom event? Sorry for all the questions, just trying to get my head around it all!\n- Because you’re using vue, I’m assuming this is in a SPA, in a SPA the only time there is a “pageview” the the traditional sense is when the app is loaded. That’s why you’re using nuxt, it provides a “event” to signal to GTM when your routing in the SPA that there is a new “screen” view. GTM then takes that screen view event, take in the data layer variables around the URL, title, etc and send that data to GA.\n- Xhothel's answer is spot on, it's just that you seem not fully aware of the difference between GTM events and GA events. The above will show up as a page view in Analytics. The trigger type is irrelevant to the tracking data - as long as the Analytics tag says \"pageview\" you will get a (virtual) pageview in GA, no matter which GTM event triggered it.\n- It seems GA tracks the correct pageURL even without the custom variable, setting the trigger to `nuxtRoute` might be enough.\n- Why is this not documented within the nuxt google-tag-manager module? Is there an other way which we can use without creating a new trigger in google-tag-manager?\n- @PhilippS. this is documented on the first page under \"Router Integration\". Might've not been there before.\n- @XTOTHEL: What do you exactly mean? What is documented there? How to implement this without creating a custom trigger in google-tag-manager?\n- On the first load I see two pageviews triggered. 1) First is coming from the plugin and the second coming from the custom trigger which you have described.\n- @PhilippS. I meant it is documented for the nuxt GTM plugin that you need to create the trigger, maybe it isn’t explicit, but since they documented what the event name sent to the data layer, it was understood to me that a trigger needs to be created.\n- I followed this method, and it works flawlessly. However, I noticed that my Google Ads are not keeping up. I have Bounce rate flying through the roof. I noticed through Hotjar, that my users are in fact not bouncing. My question is now, how do I set this up to also work with Google Ads?\n- If you're using `@nuxtjs/gtm`, the `pageURL` parameter is now named `pageUrl` !","metadata":{"transformedAt":"2026-08-18T18:33:07.834Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":96,"estimatedTokens":1152}}70{"id":"stack-51589746","source":"stackoverflow","questionId":51589746,"title":"router push a locale route in nuxt with nuxt-i18n","tags":["vue.js","vue-router","nuxt.js"],"text":"Title: router push a locale route in nuxt with nuxt-i18n\nTags: vue.js, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI use nuxt-i18n to get internationalization in my application. I have a list of news that gives me routes like that :\n\n```\nmyapp.com/news (default language English)\nmyapp.com/fr/news\nmyapp.com/it/news\n```\n\nwhen i click on a news i want to reach th _id page to get only only the news i clicked on. so i did this in a method (onclick) :\n\n```\nonLoadNews(id) {this.$router.push(\"/news/\" + id);}\n```\n\nBut this way I always return to English default language. How to push a locale route (in the function of a method) this way?\n\n========================================\n\nCode:\n```text\nmyapp.com/news (default language English)\nmyapp.com/fr/news\nmyapp.com/it/news\n```\n\n```text\nonLoadNews(id) {this.$router.push(\"/news/\" + id);}\n```\n\n========================================\n\nComments:\n- thanks, worth to notice that adding the `_id.vue` makes change the route name to `news-id`.\n- How can I navigate to a route programmatically including the current language? Currently it looks like this but it always navigates to the main language. `this.$router.push({ path: `step/${this.currentStep + 1}` });` Every step is single page e.g. `step/1`or `step/2`","metadata":{"transformedAt":"2026-08-18T18:33:07.834Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":39,"estimatedTokens":320}}71{"id":"stack-59263711","source":"stackoverflow","questionId":59263711,"title":"Vuetify: Automatic treeshaking in Nuxt.js","tags":["vuetify.js","nuxt.js","tree-shaking"],"text":"Title: Vuetify: Automatic treeshaking in Nuxt.js\nTags: vuetify.js, nuxt.js, tree-shaking\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get the automatic tree-shaking functionality provided by the Nuxt.js / Vuetify module working. In my nuxt.config.js I have:\n\n```\nbuildModules: [\n ['@nuxtjs/vuetify', {treeShake: true}]\n],\n```\n\nHowever, I'm only using one or two components at the moment, but I'm still getting a very large vendor.app (adding the treeshake option had no effect on size)\n\n```\nHash: 9ab07d7e13cc875194be\nVersion: webpack 4.41.2\nTime: 18845ms\nBuilt at: 12/10/2019 11:04:48 AM\n Asset Size Chunks Chunk Names\n../server/client.manifest.json 12.2 KiB [emitted] \n 5384010d9cdd9c2188ab.js 155 KiB 1 [emitted] [immutable] commons.app\n 706a50a7b04fc7741c9f.js 2.35 KiB 4 [emitted] [immutable] runtime\n 8d5a3837a62a2930b94f.js 34.7 KiB 0 [emitted] [immutable] app\n 9d5a4d22f4d1df95d7a7.js 1.95 KiB 3 [emitted] [immutable] pages/login\n LICENSES 389 bytes [emitted] \n a0699603e56c5e67b811.js 170 KiB 6 [emitted] [immutable] vendors.pages/login\n b1019b7a0578a5af9559.js 265 KiB 5 [emitted] [immutable] [big] vendors.app\n b327d22dbda68a34a081.js 3.04 KiB 2 [emitted] [immutable] pages/index\n + 1 hidden asset\nEntrypoint app = 706a50a7b04fc7741c9f.js 5384010d9cdd9c2188ab.js b1019b7a0578a5af9559.js 8d5a3837a62a2930b94f.js\n\nWARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).\nThis can impact web performance.\nAssets: \n b1019b7a0578a5af9559.js (265 KiB)\nℹ Generating pages 11:04:48\n✔ Generated / 11:04:48\n✔ Generated /login\n```\n\nNotice the line indicating the large vendors.app\n\n`Notice: b1019b7a0578a5af9559.js 265 KiB 5 [emitted] [immutable] [big] vendors.app`\n\nCan you please advise?\n\n========================================\n\nCode:\n```text\nbuildModules: [\n ['@nuxtjs/vuetify', {treeShake: true}]\n],\n```\n\n```text\nHash: 9ab07d7e13cc875194be\nVersion: webpack 4.41.2\nTime: 18845ms\nBuilt at: 12/10/2019 11:04:48 AM\n Asset Size Chunks Chunk Names\n../server/client.manifest.json 12.2 KiB [emitted] \n 5384010d9cdd9c2188ab.js 155 KiB 1 [emitted] [immutable] commons.app\n 706a50a7b04fc7741c9f.js 2.35 KiB 4 [emitted] [immutable] runtime\n 8d5a3837a62a2930b94f.js 34.7 KiB 0 [emitted] [immutable] app\n 9d5a4d22f4d1df95d7a7.js 1.95 KiB 3 [emitted] [immutable] pages/login\n LICENSES 389 bytes [emitted] \n a0699603e56c5e67b811.js 170 KiB 6 [emitted] [immutable] vendors.pages/login\n b1019b7a0578a5af9559.js 265 KiB 5 [emitted] [immutable] [big] vendors.app\n b327d22dbda68a34a081.js 3.04 KiB 2 [emitted] [immutable] pages/index\n + 1 hidden asset\nEntrypoint app = 706a50a7b04fc7741c9f.js 5384010d9cdd9c2188ab.js b1019b7a0578a5af9559.js 8d5a3837a62a2930b94f.js\n\nWARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).\nThis can impact web performance.\nAssets: \n b1019b7a0578a5af9559.js (265 KiB)\nℹ Generating pages 11:04:48\n✔ Generated / 11:04:48\n✔ Generated /login\n```\n\n```text\nNotice: b1019b7a0578a5af9559.js 265 KiB 5 [emitted] [immutable] [big] vendors.app\n```\n\n```text\nbuild: {\n analyze:true,\n extractCSS: true\n}\n```\n\n```text\nbuild: {analyze:true}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnpm run build\n```\n\n```text\nextractCSS:true\n```\n\n========================================\n\nComments:\n- when u say few kb is it around 277.24kb?","metadata":{"transformedAt":"2026-08-18T18:33:07.834Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":115,"estimatedTokens":957}}72{"id":"stack-60284864","source":"stackoverflow","questionId":60284864,"title":"Nuxt.js static site and 404 page","tags":["nuxt.js","custom-error-pages","static-site"],"text":"Title: Nuxt.js static site and 404 page\nTags: nuxt.js, custom-error-pages, static-site\nSource: Stack Overflow\n\nQuestion:\nI have currently created a `pages/404.vue` file, then, in my server settings, I redirect any non existent url to /404.html (the generated page).\n\nApart me having to declare the file extension (it gives me redirect error if I redirect to /404), it seems to work fine, and I guess it will also give me an easy way to create other server error files, if needed.\n\nHowever, following the documentation, I first tried adding `fallback: true` inside `generate:{ }`. This creates a `404.html` page in my root, but using a default Nuxt layout (an infinite loading wheel page).\n\nI assumed that creating `layouts/error.vue` (as per docs) would do the trick, but didn't seem the case.\n\nWhat is the right practice, and, if the documentation one is to , why my personalised error.vue wasn't working?\nThanks.\n\n========================================\n\nTop Answer:\nIn order to generate a 404 fallback page in nuxt.js you need to first set the generate option in your nuxt.config.js like this\n`generate: { fallback: '404.html' }`\n\nThen you need to create a new layout called error.vue in your layouts directory\n\n```\nlayouts/error.vue\n```\n\nAfter you have done this you can `nuxt generate` followed by `nuxt start` to run your project with a fallback page for the 404 error.\n\n========================================\n\nCode:\n```text\npages/404.vue\n```\n\n```text\nfallback: true\n```\n\n```text\ngenerate:{ }\n```\n\n```text\n404.html\n```\n\n```text\nlayouts/error.vue\n```\n\n```text\npages/404.vue\n```\n\n```text\nlayouts/error.vue\n```\n\n```text\nlayouts/basic.vue\n```\n\n```text\ngenerate: { fallback: true }\n```\n\n```text\nlayouts/error.vue\n```\n\n```text\ngenerate: { fallback: '404.html' }\n```\n\n```text\nnuxt generate\n```\n\n```text\nnuxt start\n```\n\n```text\n// layouts/error.vue\n<template>\n <div>\n <h1 v-if=\"error.statusCode === 404\">Page not found</h1>\n <h1 v-else>An error occurred</h1>\n <NuxtLink to=\"/\">Home page</NuxtLink>\n </div>\n</template>\n\n<script>\nexport default {\n name: 'error',\n layout: 'empty', //OR layout:'default'\n props: {\n error: {\n type: Object,\n },\n },\n};\n</script>\n```\n\n```text\n// layouts/empty.vue\n<template>\n //your codes\n <Nuxt />\n</template>\n```\n\n```text\nerror.vue\n```\n\n```text\nempty.vue\n```\n\n```text\nlayouts\n```\n\n```text\nlayout:\"empty\"\n```\n\n```text\nlayout:\"default\"\n```\n\n```text\n// /error.vue\n<template>\n <div class=\"flex flex-col items-center\">\n <div class=\"text-indigo-500 font-bold text-7xl\">\n 404\n </div>\n\n <div class=\"font-bold text-3xl xl:text-7xl lg:text-6xl md:text-5xl mt-10\">\n This page does not exist\n </div>\n\n <div class=\"text-gray-400 font-medium text-sm md:text-xl lg:text-2xl mt-8\">\n The page you are looking for could not be found.\n </div>\n </div>\n</template>\n```\n\n```text\nerror.vue\n```\n\n```text\n/pages\n```\n\n```text\n/layouts\n```\n\n```text\npages/[...catchAll].vue\n```\n\n========================================\n\nComments:\n- Any news on this?\n- do you have an update on this? I'm using AWS Amplify and it specifically ask for an actual 404 page/path. Should I go with having an actual 404.vue page?\n- no, if you are using `target: static`, then you want to add `generate { fallback: true }` in nuxt.config.js and the actual page in `layouts/error.vue` , then you need to redirect the errors in the server to the 404.html generated file","metadata":{"transformedAt":"2026-08-18T18:33:07.834Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":177,"estimatedTokens":874}}73{"id":"stack-53446792","source":"stackoverflow","questionId":53446792,"title":"Nuxt + Vuex - How do I break down a Vuex module into separate files?","tags":["javascript","vue.js","vuex","nuxt.js"],"text":"Title: Nuxt + Vuex - How do I break down a Vuex module into separate files?\nTags: javascript, vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn the Nuxt documentation (here) it says 'You can optionally break down a module file into separate files: `state.js`, `actions.js`, `mutations.js` and `getters.js`.'\n\nI can't seem to find any examples of how this is done - lots of breaking down the Vuex store at the root level into `state.js`, `actions.js`, `mutations.js` and `getters.js`, and into individual module files, but nothing about breaking the modules themselves down.\n\nSo currently I have:\n\n```\n├── assets\n ├── components\n └── store\n ├── moduleOne.js\n ├── moduleTwo.js\n └── etc...\n```\n\nAnd what I would like to have is:\n\n```\n├── assets\n ├── components\n └── store\n └── moduleOne\n └── state.js\n └── getters.js\n └── mutations.js\n └── actions.js\n └── moduleTwo\n └── etc...\n```\n\nTo try this out, in `/store/moduleOne/state.js` I have:\n\n```\nexport const state = () => {\n return {\n test: 'test'\n }\n};\n```\n\nand in `/store/moduleOne/getters.js` I have:\n\n```\nexport const getters = {\n getTest (state) {\n return state.test;\n }\n}\n```\n\nIn my component I'm accessing this with `$store.getters['moduleOne/getters/getTest']`\n\nHowever using the debugger and Vue devtools, it seems like state isn't accessible in the getters file - it seems to be looking for a state in the local file, so `state.test` is undefined.\n\nAttempting to import `state` from my `state.js` file into my `getters.js` file doesn't seem to work either.\n\nDoes anyone have an example of how they've managed to break the store down like this in Nuxt?\n\n========================================\n\nTop Answer:\nIn nuxt version 2.14^ you don't necessary have to create this in your store root index.js file.\n\n```\nimport Vuex from 'vuex';\nimport apiModule from './modules/api-logic';\nimport appModule from './modules/app-logic';\n\nconst createStore = () => {\n return new Vuex.Store({\n namespaced: true,\n modules: {\n appLogic: appModule,\n api: apiModule\n }\n });\n};\n\nexport default createStore\n```\n\nBut instead, you can just leave your root index.js file as default or do what you need. No need to import.\n\n`store/index.js`\n\n```\nexport const state = () => ({\n counter: 0\n})\n\nexport const mutations = {\n increment(state) {\n state.counter++\n }\n}\n\nexport const actions = {\n async nuxtServerInit({ state, commit }, { req }) {\n const cookies = this.$cookies.getAll() \n ...\n}\n```\n\nAnd this how it looks like, its very simple.\n\nFolder structure\n\n```\n📦store\n ┣ 📂auth\n ┣ 📂utils\n ┣ 📂posts\n ┃ ┗ 📜actions.js\n ┃ ┗ 📜mutations.js\n ┃ ┗ 📜getters.js\n ┃ ┗ 📜index.js\n ┣ index.js\n```\n\nExample\n\n`store/posts/index.js` you can just put the state function. You don't need to import the actions, getters and mutations.\n\n```\nexport const state = () => ({ \n comments: []\n})\n```\n\n`store/posts/actions.js`\n\n```\nconst actions = {\n async getPosts({ commit, state }, obj) {\n return new Promise((resolve, reject) => { \n ...\n }\n }\n}\n\nexport default actions\n```\n\n`store/posts/mutations.js`\n\n```\nconst mutations = {\n CLEAR_POST_IMAGE_CONTENT: (state) => {\n state.post_image_content = []\n }\n }\n \n export default mutations\n```\n\n`store/posts/getters.js`\n\n```\nconst getters = {\n datatest: (state) => state.datatest,\n headlineFeatures: (state) => state.headlineFeatures,\n}\n\nexport default getters\n```\n\nThe effect is same as @CMarzin answer but much cleaner\n\n========================================\n\nCode:\n```text\n├── assets\n ├── components\n └── store\n ├── moduleOne.js\n ├── moduleTwo.js\n └── etc...\n```\n\n```text\n├── assets\n ├── components\n └── store\n └── moduleOne\n └── state.js\n └── getters.js\n └── mutations.js\n └── actions.js\n └── moduleTwo\n └── etc...\n```\n\n```text\nexport const state = () => {\n return {\n test: 'test'\n }\n};\n```\n\n```text\nexport const getters = {\n getTest (state) {\n return state.test;\n }\n}\n```\n\n```text\nstate.js\n```\n\n```text\nactions.js\n```\n\n```text\nmutations.js\n```\n\n```text\ngetters.js\n```\n\n```text\nstate.js\n```\n\n```text\nactions.js\n```\n\n```text\nmutations.js\n```\n\n```text\ngetters.js\n```\n\n```text\n/store/moduleOne/state.js\n```\n\n```text\n/store/moduleOne/getters.js\n```\n\n```text\n$store.getters['moduleOne/getters/getTest']\n```\n\n```text\nstate.test\n```\n\n```text\nstate\n```\n\n```text\nstate.js\n```\n\n```text\ngetters.js\n```\n\n```text\nimport Vuex from 'vuex';\nimport apiModule from './modules/api-logic';\nimport appModule from './modules/app-logic';\n\nconst createStore = () => {\n return new Vuex.Store({\n namespaced: true,\n modules: {\n appLogic: appModule,\n api: apiModule\n }\n });\n};\n\nexport default createStore\n```\n\n```text\nimport actions from './actions';\nimport getters from './getters';\nimport mutations from './mutations';\n\nconst defaultState = {\n hello: 'salut I am module api'\n}\n\nconst inBrowser = typeof window !== 'undefined';\n// if in browser, use pre-fetched state injected by SSR\nconst state = (inBrowser && window.__INITIAL_STATE__) ? window.__INITIAL_STATE__.page : defaultState;\n\nexport default {\n state,\n actions,\n mutations,\n getters\n}\n```\n\n```text\nexport default {\n getHelloThere: state => state.hello\n}\n```\n\n```text\nimport actions from './actions';\nimport getters from './getters';\nimport mutations from './mutations';\n\nconst defaultState = {\n appLogicData: 'bonjours I am module Logic'\n}\n\nconst inBrowser = typeof window !== 'undefined';\n// if in browser, use pre-fetched state injected by SSR\nconst state = (inBrowser && window.__INITIAL_STATE__) ? window.__INITIAL_STATE__.page : defaultState;\n\nexport default {\n state,\n actions,\n mutations,\n getters\n}\n```\n\n```text\nexport default {\n getAppLogicData: state => state.appLogicData\n}\n```\n\n```text\ncomputed: {\n ...mapGetters({\n logicData: 'getAppLogicData',\n coucou: 'getHelloThere'\n })\n},\nmounted () {\n console.log('coucou', this.coucou) --> salut I am module api\n console.log('logicData', this.logicData) --> bonjours I am module Logic\n}\n```\n\n```text\ncallPokemonFromAppLogic: ({ dispatch }, id) => {\n dispatch('callThePokemonFromApiLogic', id, {root:true});\n },\n```\n\n```text\ncallThePokemonFromApiLogic: ({ commit }, id) => {\n\n console.log('I make the call here')\n axios.get('http://pokeapi.salestock.net/api/v2/pokemon/' + id).then(response => commit('update_pokemon', response.data))\n },\n```\n\n```text\nimport actions from './actions';\nimport getters from './getters';\nimport mutations from './mutations';\n\nconst defaultState = {\n appLogicData: 'bonjours I am module Logic',\n pokemon: {}\n}\n\nconst inBrowser = typeof window !== 'undefined';\n// if in browser, use pre-fetched state injected by SSR\nconst state = (inBrowser && window.__INITIAL_STATE__) ? window.__INITIAL_STATE__.page : defaultState;\n\nexport default {\n state,\n actions,\n mutations,\n getters\n}\n```\n\n```text\nupdate_pokemon: (state, pokemon) => {\n state.pokemon = pokemon\n }\n```\n\n```text\ncomputed: {\n ...mapGetters({\n bidule: 'bidule',\n pokemon: 'getPokemon'\n })\n},\nmounted() {\n console.log('bidule', this.bidule)\n this.callPokemonFromAppLogic('1') --> the call \n console.log('the pokemon', this.pokemon.name) --> 'bulbasaur'\n},\nmethods: {\n ...mapActions({\n callPokemonFromAppLogic: 'callPokemonFromAppLogic'\n }),\n}\n```\n\n```text\n2.1.0\n```\n\n```text\nstore/index.js\n```\n\n```text\nstore/api-logic/index.js\n```\n\n```text\nstore/api-logic/getters.js\n```\n\n```text\nstore/app-logic/index.js\n```\n\n```text\nstore/app-logic/getters.js\n```\n\n```text\nroot: true\n```\n\n```text\nstore/app-logic/actions.js\n```\n\n```text\nstore/api-logic/actions.js\n```\n\n```text\nstore/api-logic/index.js\n```\n\n```text\nstore/api-logic/mutations.js\n```\n\n```text\n<template>\n <div>\n <h1>{{ baz }}</h1>\n <br>\n <p>{{ $store.state.counter }}</p>\n <br>\n <h2>{{ getVal }}</h2>\n <br>\n <h3>{{ getBabVal }}</h3>\n </div>\n</template>\n\n<script>\nimport { mapGetters } from 'vuex'\n\nexport default {\n computed: {\n ...mapGetters('foo/bar', ['baz']),\n ...mapGetters('foo/blarg', ['getVal']),\n ...mapGetters('bab', ['getBabVal'])\n }\n}\n</script>\n```\n\n```text\ndefault\n```\n\n```text\nindex.js\n```\n\n```text\nbasic\n```\n\n```text\ngetVal\n```\n\n```text\nstate.val\n```\n\n```text\nimport Vuex from 'vuex';\nimport apiModule from './modules/api-logic';\nimport appModule from './modules/app-logic';\n\nconst createStore = () => {\n return new Vuex.Store({\n namespaced: true,\n modules: {\n appLogic: appModule,\n api: apiModule\n }\n });\n};\n\nexport default createStore\n```\n\n```text\nexport const state = () => ({\n counter: 0\n})\n\nexport const mutations = {\n increment(state) {\n state.counter++\n }\n}\n\nexport const actions = {\n async nuxtServerInit({ state, commit }, { req }) {\n const cookies = this.$cookies.getAll() \n ...\n}\n```\n\n```text\n📦store\n ┣ 📂auth\n ┣ 📂utils\n ┣ 📂posts\n ┃ ┗ 📜actions.js\n ┃ ┗ 📜mutations.js\n ┃ ┗ 📜getters.js\n ┃ ┗ 📜index.js\n ┣ index.js\n```\n\n```text\nexport const state = () => ({ \n comments: []\n})\n```\n\n```text\nconst actions = {\n async getPosts({ commit, state }, obj) {\n return new Promise((resolve, reject) => { \n ...\n }\n }\n}\n\nexport default actions\n```\n\n```text\nconst mutations = {\n CLEAR_POST_IMAGE_CONTENT: (state) => {\n state.post_image_content = []\n }\n }\n \n export default mutations\n```\n\n```text\nconst getters = {\n datatest: (state) => state.datatest,\n headlineFeatures: (state) => state.headlineFeatures,\n}\n\nexport default getters\n```\n\n```text\nstore/index.js\n```\n\n```text\nstore/posts/index.js\n```\n\n```text\nstore/posts/actions.js\n```\n\n```text\nstore/posts/mutations.js\n```\n\n```text\nstore/posts/getters.js\n```\n\n========================================\n\nComments:\n- Good question. Just tried it out and it indeed breaks down my app. Maybe create an issue on cmty.app/nuxt. Seems like either a bug or lack of documentation.\n- Example is at github.com/nuxt/nuxt.js/tree/dev/test/fixtures/basic/store/f‌​oo/… ;)\n- above answer from @manniL doesn't solve the issue, since the contents of the module directory are simply repeated in the file of the same name in the root of the store\n- Sorry, I got a bit more into detail now ;)\n- Is any solution to isolate one store in one page? I don't need to import checkout store for all pages","metadata":{"transformedAt":"2026-08-18T18:33:07.835Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":59,"totalLines":623,"estimatedTokens":2572}}74{"id":"stack-62571970","source":"stackoverflow","questionId":62571970,"title":"NUXT how to pass data from page to layout","tags":["javascript","vue.js","nuxt.js"],"text":"Title: NUXT how to pass data from page to layout\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am creating a very simple website. I want to change the Navbar elements depending on data set in `navLayout` on the page template. I want to pass the data to the layout, then use `props` to send it to the `NavBar`. My issue is how to `emit` data from the page to the layout.\n\n**layouts/default.vue**\n\n```\n\n \n \n \n \n \n \n \n\nimport NavBar from '~/components/NavBar.vue'\n\nexport default {\n components: {\n NavBar,\n }\n}\n\n```\n\n**pages/index.vue**\n\n```\n...\n\nexport default {\n\n data: () => {\n return {\n navLayout: 'simple'\n }\n },\n computed: () => {\n return {\n this.$emit('navLayout', value)\n }\n\n }\n...\n\n```\n\n========================================\n\nTop Answer:\nYou should use $emit from parent element, so the parent element to the page is layout page. Here is sample:\n\n```\nthis.$parent.$emit(\"eventName\");\n```\n\nThen listen action at layout on the Nuxt component.\n\n```\n\n```\n\nAnd here it is)\n\n========================================\n\nCode:\n```text\n<template>\n <div>\n <NavBar />\n <div class=\"site-container\">\n <nuxt />\n </div>\n <Footer />\n </div>\n</template>\n<script>\nimport NavBar from '~/components/NavBar.vue'\n\nexport default {\n components: {\n NavBar,\n }\n}\n</script>\n```\n\n```text\n...\n<script>\nexport default {\n\n data: () => {\n return {\n navLayout: 'simple'\n }\n },\n computed: () => {\n return {\n this.$emit('navLayout', value)\n }\n\n }\n...\n</script>\n```\n\n```text\nnavLayout\n```\n\n```text\nprops\n```\n\n```text\nNavBar\n```\n\n```text\nemit\n```\n\n```text\nexport const state = () => ({\n layout: 'Your default value',\n})\n \nexport const mutations = {\n CHANGE_NAV_LAYOUT(state, layout) {\n state.layout = layout;\n }\n}\n```\n\n```text\ncomputed: {\n navLayout() {\n return this.$store.state.layout;\n }\n}\n```\n\n```text\nindex.js\n```\n\n```text\nthis.$store.commit('CHANGE_NAV_LAYOUT',value)\n```\n\n```text\nthis.$parent.$emit(\"eventName\");\n```\n\n```text\n<Nuxt @eventname=\"actionHandler()\"/>\n```\n\n========================================\n\nComments:\n- You wanna do it depending on the route or depending on some state inside of a page?\n- Depending on a state within the page.\n- I do have this issue.\n- Where do I place ` this.$store.commit('CHANGE_NAV_LAYOUT',value)` within a page/component?\n- I added it inside `created()` . But now the default is always overwritten\n- Their seems to be a slight delay also for when the store value is updated during from a component on a page. Would it be better to pass the value up from the component to the page then change the $store. ?\n- @Simon should not make any difference, I assume the delay is caused by something else\n- I think the delay is caused because of the way the DOM is rendered.\n- Can we agree on the fact that this is very hacky? I'm surprised such API doesn't exist in nuxt yet.\n- As far as I know cannot listen for events","metadata":{"transformedAt":"2026-08-18T18:33:07.835Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":177,"estimatedTokens":732}}75{"id":"stack-74287452","source":"stackoverflow","questionId":74287452,"title":"Vitest mock modules function in only one test and use the actual function in others","tags":["javascript","unit-testing","nuxt.js","vitest"],"text":"Title: Vitest mock modules function in only one test and use the actual function in others\nTags: javascript, unit-testing, nuxt.js, vitest\nSource: Stack Overflow\n\nQuestion:\nThe following is an abstraction of my problem and thus does not make too much sense:\n\nGiven I have a simple utility `callMethodIf` that's returning the return of another imported method (`blackbox`).\n\n~~/utils/call-method-if.js:\n\n```\nimport { blackbox } from '~~/utils/blackbox';\n\nexport const callMethodIf = (condition) => {\n return blackbox(condition);\n};\n```\n\n~~/utils/blackbox.js:\n\n```\nexport const blackbox = (condition) => {\n return { called: condition };\n};\n```\n\nHow would I run one test case which calls the actual implementation of `blackbox()` and another one where I mock the return value of `blackbox()`?\n\nI tried to do it that way:\n\n```\nimport { describe, expect, it } from 'vitest';\n\nimport { callMethodIf } from '~~/utils/call-method-if';\n\ndescribe('Call method if', () => {\n it('returns \"called: true\" if condition is true', () => {\n const result = callMethodIf(true);\n expect(result).toEqual({ called: true });\n });\n\n it('returns mocked blackbox return object', () => {\n vi.mock('~~/utils/blackbox', () => ({\n blackbox: vi.fn().mockReturnValue({ mock: true })\n }));\n const result = callMethodIf(false);\n expect(result).toEqual({ mock: true });\n });\n});\n```\n\nBoth tests work if I run only one of them, but they don't work when combined.\n\nRunning `vi.clearAllMocks()` or `vi.resetAllMocks()` don't help.\n\nDefining a global mock and overwriting it in my first test doesn't work either:\n\n```\nimport { describe, expect, it } from 'vitest';\n\nimport { callMethodIf } from '~~/utils/call-method-if';\n\nvi.mock('~~/utils/blackbox', () => ({\n blackbox: vi.fn().mockReturnValue({ mock: true })\n}));\n\ndescribe('Call method if', () => {\n it('returns \"called: true\" if condition is true', () => {\n vi.mock('~~/utils/blackbox', async () => ({\n blackbox: (await vi.importActual('~~/utils/blackbox')).blackbox\n }));\n const result = callMethodIf(true);\n expect(result).toEqual({ called: true });\n });\n\n it('returns mocked blackbox return object', () => {\n const result = callMethodIf(false);\n expect(result).toEqual({ mock: true });\n });\n});\n```\n\n========================================\n\nTop Answer:\nI also ran in to this problem with using Vite. After a lot of trail and error I have managed to get the mocking of a module function working by using the following code:\n\n```\nvi.mock('@/models/generated/graphql')\n\ndescribe('MyComponent works as expected', () => {\n it('Shows loading when loading', async () => {\n const graphql = await import('@/models/generated/graphql')\n graphql.useGetAllQuery = vi.fn().mockReturnValue({ loading: true, error: null, data: null })\n\n render()\n\n expect(screen.findByTestId('my-component-loading')).toBeTruthy()\n })\n}\n```\n\nThe function that I am mocking is this one (which is auto generated for my Graphql service):\n\n```\nexport function useGetAllQuery(baseOptions?: Apollo.QueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useQuery(GetAllDocument, options);\n }\n```\n\nI do not really understand why this works, but it does. I hope that this code snippet might help some.\n\n========================================\n\nCode:\n```js\nimport { blackbox } from '~~/utils/blackbox';\n\nexport const callMethodIf = (condition) => {\n return blackbox(condition);\n};\n```\n\n```js\nexport const blackbox = (condition) => {\n return { called: condition };\n};\n```\n\n```js\nimport { describe, expect, it } from 'vitest';\n\nimport { callMethodIf } from '~~/utils/call-method-if';\n\ndescribe('Call method if', () => {\n it('returns \"called: true\" if condition is true', () => {\n const result = callMethodIf(true);\n expect(result).toEqual({ called: true });\n });\n\n it('returns mocked blackbox return object', () => {\n vi.mock('~~/utils/blackbox', () => ({\n blackbox: vi.fn().mockReturnValue({ mock: true })\n }));\n const result = callMethodIf(false);\n expect(result).toEqual({ mock: true });\n });\n});\n```\n\n```js\nimport { describe, expect, it } from 'vitest';\n\nimport { callMethodIf } from '~~/utils/call-method-if';\n\nvi.mock('~~/utils/blackbox', () => ({\n blackbox: vi.fn().mockReturnValue({ mock: true })\n}));\n\ndescribe('Call method if', () => {\n it('returns \"called: true\" if condition is true', () => {\n vi.mock('~~/utils/blackbox', async () => ({\n blackbox: (await vi.importActual('~~/utils/blackbox')).blackbox\n }));\n const result = callMethodIf(true);\n expect(result).toEqual({ called: true });\n });\n\n it('returns mocked blackbox return object', () => {\n const result = callMethodIf(false);\n expect(result).toEqual({ mock: true });\n });\n});\n```\n\n```text\ncallMethodIf\n```\n\n```text\nblackbox\n```\n\n```text\nblackbox()\n```\n\n```text\nblackbox()\n```\n\n```text\nvi.clearAllMocks()\n```\n\n```text\nvi.resetAllMocks()\n```\n\n```js\nimport { describe, expect, it } from 'vitest';\n\nimport { callMethodIf } from '~~/utils/call-method-if';\n\nvi.mock('~~/utils/blackbox');\n\ndescribe('Call method if', () => {\n it('returns \"called: true\" if condition is true', async () => {\n const blackbox = await import('~~/utils/blackbox');\n blackbox.blackbox = (await vi.importActual('~~/utils/blackbox')).blackbox;\n const result = callMethodIf(true);\n expect(result).toEqual({ called: true });\n });\n\n it('returns mocked blackbox return object', async () => {\n const blackbox = await import('~~/utils/blackbox');\n blackbox.blackbox = vi.fn().mockReturnValue({ mock: true });\n const result = callMethodIf(false);\n expect(result).toEqual({ mock: true });\n });\n});\n```\n\n```js\nblackbox.blackbox = (await vi.importActual<typeof import('~~/utils/blackbox')>('~~/utils/blackbox')).blackbox;\n```\n\n```text\nimportActual()\n```\n\n```text\nvi.mock('@/models/generated/graphql')\n\ndescribe('MyComponent works as expected', () => {\n it('Shows loading when loading', async () => {\n const graphql = await import('@/models/generated/graphql')\n graphql.useGetAllQuery = vi.fn().mockReturnValue({ loading: true, error: null, data: null })\n\n render(<MyComponent />)\n\n expect(screen.findByTestId('my-component-loading')).toBeTruthy()\n })\n}\n```\n\n```text\nexport function useGetAllQuery(baseOptions?: Apollo.QueryHookOptions<GetAllQuery, GetAllQueryVariables>) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useQuery<GetAllQuery, GetAllQueryVariables>(GetAllDocument, options);\n }\n```\n\n```ts\nimport { vi } from \"vitest\";\nimport { get, set } from \"lodash\";\n\nexport async function unmock(import_path: string, methods: string[]) {\n const module = await import(import_path);\n const actualModule = await vi.importActual(import_path);\n\n const path = methods.join(\".\");\n const actualProperty = get(actualModule, path);\n\n set(module, path, actualProperty);\n}\n\n// Example usage\nawait unmock(\"../../src/util/meta_import_util\", [\"default\", \"getKey\"]);\n```\n\n```text\nlodash\n```\n\n```js\nimport { describe, expect, it, vi } from 'vitest'\n\nimport { callMethodIf } from '~~/utils/call-method-if'\n\ndescribe('Call method if', () => {\n it('returns \"called: true\" if condition is true', () => {\n const result = callMethodIf(true)\n expect(result).toEqual({ called: true })\n })\n\n it('returns mocked blackbox return object', async () => {\n // clear module registry so modules are re-evaluated for new imports\n vi.resetModules()\n\n // apply mock\n vi.doMock('~~/utils/blackbox', () => ({\n blackbox: vi.fn().mockReturnValue({ mock: true }),\n }))\n\n // re-import the function you're testing, now using your mock\n const callMethodIfWithMock = (\n await import('~~/utils/call-method-if')\n ).callMethodIf\n\n const result = callMethodIfWithMock(false)\n expect(result).toEqual({ mock: true })\n })\n})\n```\n\n```text\nvi.doMock\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.835Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":311,"estimatedTokens":1988}}76{"id":"stack-54095215","source":"stackoverflow","questionId":54095215,"title":"How to get all the image files in a directory using vue.js / nuxt.js","tags":["javascript","vue.js","vuejs2","nuxt.js"],"text":"Title: How to get all the image files in a directory using vue.js / nuxt.js\nTags: javascript, vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am working on a nuxt.js project and getting error: \n\nIn browser I am seeing this error:\n\n```\n__webpack_require__(...).context is not a function\n```\n\nAnd, in terminal I am getting this error:\n\n```\nCritical dependency: require function is used in a way in which dependencies cannot be statically extracted\n```\n\nHere is my code\n\n```\n\nexport default {\n name: 'SectionOurClients',\n data() {\n return {\n imageDir: '../assets/images/clients/',\n images: {},\n };\n },\n\n mounted() {\n this.importAll(require.context(this.imageDir, true, /\\.png$/));\n },\n\n methods: {\n importAll(r) {\n console.log(r)\n },\n },\n};\n\n```\n\nI have used the above script from HERE.\n\nPlease help, thanks.\n\n**EDIT**: After following @MaxSinev's answer, here is how my working code looks:\n\n```\n\n .row\n .col(v-for=\"client in images\")\n img(:src=\"client.pathLong\")\n\nexport default {\n name: 'SectionOurClients',\n data() {\n return {\n images: [],\n };\n },\n\n mounted() {\n this.importAll(require.context('../assets/images/clients/', true, /\\.png$/));\n },\n\n methods: {\n importAll(r) {\n r.keys().forEach(key => (this.images.push({ pathLong: r(key), pathShort: key })));\n },\n },\n};\n\n```\n\n========================================\n\nTop Answer:\nSolution for vue 3 with vite:\n\n```\n\nconst fonts = import.meta.glob('@/assets/fonts/*.otf')\nconsole.log(fonts)\n\n```\n\nRead more: https://github.com/vitejs/vite/issues/77\n\n========================================\n\nCode:\n```text\n__webpack_require__(...).context is not a function\n```\n\n```text\nCritical dependency: require function is used in a way in which dependencies cannot be statically extracted\n```\n\n```text\n<script>\nexport default {\n name: 'SectionOurClients',\n data() {\n return {\n imageDir: '../assets/images/clients/',\n images: {},\n };\n },\n\n mounted() {\n this.importAll(require.context(this.imageDir, true, /\\.png$/));\n },\n\n methods: {\n importAll(r) {\n console.log(r)\n },\n },\n};\n</script>\n```\n\n```text\n<template lang=\"pug\">\n .row\n .col(v-for=\"client in images\")\n img(:src=\"client.pathLong\")\n</template>\n\n<script>\nexport default {\n name: 'SectionOurClients',\n data() {\n return {\n images: [],\n };\n },\n\n mounted() {\n this.importAll(require.context('../assets/images/clients/', true, /\\.png$/));\n },\n\n methods: {\n importAll(r) {\n r.keys().forEach(key => (this.images.push({ pathLong: r(key), pathShort: key })));\n },\n },\n};\n</script>\n```\n\n```text\nmounted() {\n this.importAll(require.context('../assets/images/clients/', true, /\\.png$/));\n},\n```\n\n```text\nrequire.context\n```\n\n```text\nrequire.context\n```\n\n```text\nimageDir\n```\n\n```html\n<script setup lang=\"ts\">\nconst fonts = import.meta.glob('@/assets/fonts/*.otf')\nconsole.log(fonts)\n</script>\n```\n\n========================================\n\nComments:\n- why dont you use `import` instead of `require` ?\n- @Terry it's not quite correct answer. Both `import` and `require` imports file as module, if you want to import images you can do that only with specified webpack loader and there is no difference between `import` and `require` for webpack. But in question example we can not use `import` because we have to use webpack helper `require.context` to load all images dymically during bundling.\n- @Terry, even `.png`'s can be imported `import defaultAvatar from '@/assets/images/default-avatar.png'`\n- thanks for your help, I have included working code in my answer.\n- when i am adding .pdf its throwing error. is there any way to get list of all files from a folder?\n- @SudhirKGupta if you want to involve pdf file to the bundling process you should add, for example, `file-loader` definition for your file type after that it will be resolved by webpack.","metadata":{"transformedAt":"2026-08-18T18:33:07.835Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":190,"estimatedTokens":960}}77{"id":"stack-59015259","source":"stackoverflow","questionId":59015259,"title":"Include external javascript file in a nuxt.js page","tags":["javascript","vue.js","vuejs2","nuxt.js"],"text":"Title: Include external javascript file in a nuxt.js page\nTags: javascript, vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a relatively simple question.\n\nI am trying to implement the widget from this codepen in Nuxt.js.\n\nHere's my code, which works fine if I use RAW HTML:\n\n```\n\n \n \n\n```\n\nBut when I try to include this dev widget in my nuxt.js project, in one of my pages, it does not work.\n\nHere is my code:\n\n```\n\n \n\n \n \n \n\n \n\nexport default {\n layout: \"default\",\n};\n\n```\n\nI keep getting an error: \n\n```\nUnknown custom element: \n```\n\nAny idea what I am doing wrong here?\n\n========================================\n\nTop Answer:\n**Adding as globally**\n\nNavigate to the nuxt.config.js file.\nIt adds the script tag to all pages in your Nuxt app.\n\n```\nexport default {\n head: {\n script: [\n {\n src: \"https://code.jquery.com/jquery-3.5.1.min.js\",\n },\n ],\n }\n // other config goes here\n}\n```\n\nIf you want to add a script tag before closing the `` instead of `` tag, you can do it by adding a `body: true`.\n\n```\nscript: [\n {\n src: \"https://code.jquery.com/jquery-3.5.1.min.js\",\n body: true,\n },\n```\n\nYou can also add async, cross-origin attributes to a script tag like this.\n\n```\nscript: [\n {\n src: \"https://code.jquery.com/jquery-3.5.1.min.js\",\n async: true,\n crossorigin: \"anonymous\"\n },\n],\n```\n\n**OUTPUT**\n\n```\n\n```\n\n**Adding to particular page**\n\n```\n\n export default {\n head() {\n return {\n script: [\n {\n src: 'https://code.jquery.com/jquery-3.5.1.min.js'\n }\n ],\n }\n }\n }\n\n```\n\n**Note:**\nIf you want to add a local js file, place it in a root `static` folder and add it as follows.\n\n```\nexport default {\n head() {\n return {\n script: [\n {\n src: '/js/jquery.min.js'\n }\n ],\n }\n }\n }\n```\n\n========================================\n\nCode:\n```text\n<!DOCTYPE html>\n<html>\n<head></head>\n<body>\n <dev-widget data-username=\"saurabhdaware\"></dev-widget>\n <script src=\"https://unpkg.com/dev-widget@1.0.3/dist/card.component.mjs\" type=\"module\"></script>\n</body>\n\n</html>\n```\n\n```text\n<template>\n <div class=\"container\">\n\n <div>\n <dev-widget data-username=\"saurabhdaware\"></dev-widget>\n </div>\n\n </div>\n</template>\n\n<script>\n\nexport default {\n layout: \"default\",\n};\n</script>\n\n<script src=\"https://unpkg.com/dev-widget@1.0.3/dist/card.component.mjs\" type=\"module\"></script>\n```\n\n```text\nUnknown custom element: < dev-widget >\n```\n\n```html\nexport default {\n mode: 'universal',\n /*\n ** Headers of the page\n */\n head: {\n title: 'Your title',\n meta: [{\n charset: 'utf-8'\n },\n {\n name: 'viewport',\n content: 'width=device-width, initial-scale=1'\n }\n ],\n\n link: [\n {\n rel: 'stylesheet',\n href: 'css/mystyles.css'\n }\n ],\n\n script: [\n {\n type: 'module',\n src: 'https://unpkg.com/dev-widget@1.0.3/dist/card.component.js'\n }\n ]\n },\n /*\n ** Customize the progress-bar color\n */\n loading: {\n color: '#fff'\n },\n /*\n ** Global CSS\n */\n css: [],\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [],\n /*\n ** Nuxt.js dev-modules\n */\n buildModules: [],\n /*\n ** Nuxt.js modules\n */\n modules: [],\n /*\n ** Build configuration\n */\n build: {}\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n<template>\n <div class=\"container\">\n\n <div>\n <dev-widget data-username=\"saurabhdaware\"></dev-widget>\n </div>\n\n </div>\n</template>\n\n<script>\n\nexport default {\n layout: \"default\",\n\n head: {\n script: [\n {\n type: 'module',\n src: 'https://unpkg.com/dev-widget@1.0.3/dist/card.component.mjs'\n }\n ]\n },\n\n};\n</script>\n```\n\n```text\nexport default {\n head: {\n script: [\n {\n src: \"https://code.jquery.com/jquery-3.5.1.min.js\",\n },\n ],\n }\n // other config goes here\n}\n```\n\n```text\nscript: [\n {\n src: \"https://code.jquery.com/jquery-3.5.1.min.js\",\n body: true,\n },\n```\n\n```text\nscript: [\n {\n src: \"https://code.jquery.com/jquery-3.5.1.min.js\",\n async: true,\n crossorigin: \"anonymous\"\n },\n],\n```\n\n```text\n<script data-n-head=\"ssr\" src=\"https://code.jquery.com/jquery-3.5.1.min.js\"\ncrossorigin=\"anonymous\" async=\"\"></script>\n```\n\n```text\n<script>\n export default {\n head() {\n return {\n script: [\n {\n src: 'https://code.jquery.com/jquery-3.5.1.min.js'\n }\n ],\n }\n }\n }\n</script>\n```\n\n```text\nexport default {\n head() {\n return {\n script: [\n {\n src: '/js/jquery.min.js'\n }\n ],\n }\n }\n }\n```\n\n```text\n</body>\n```\n\n```text\n<head>\n```\n\n```text\nbody: true\n```\n\n```text\nstatic\n```\n\n```json\nmeta: { \n script: [\n { src: \"https://path.to/your.js\" }\n ]\n},\n```\n\n========================================\n\nComments:\n- How do I include the external script file, though?\n- This approach will definitely work, but you will run into issues if the external script loads something in you want to work with in Nuxt. Then there's a race condition between your Nuxt (Vue) code running before the external file has been fetched and processed by your browser.\n- @beporter Could you tell more about this? I have a script that loads correctly if I start from / and then browse to the page the uses the script. If I load the page directly, the script is not loaded","metadata":{"transformedAt":"2026-08-18T18:33:07.835Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":359,"estimatedTokens":1370}}78{"id":"stack-49301521","source":"stackoverflow","questionId":49301521,"title":"How do we include only required modules from lodash in a Nuxt?Vuejs Project?","tags":["javascript","webpack","vue.js","lodash","nuxt.js"],"text":"Title: How do we include only required modules from lodash in a Nuxt?Vuejs Project?\nTags: javascript, webpack, vue.js, lodash, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWe have built a Nuxt/VueJS project. \n\nNuxt has its own config file called `nuxt.config.js` within which we configure webpack and other build setup.\n\nIn our package.json, we have included the lodash package.\n\nIn our code, we have been careful to load only import what we require, for example:\n\n```\nimport orderBy from 'lodash/orderBy'\n```\n\nIn `nuxt.config.js`, lodash is add to the `vendor` list.\n\nHowever when we create the build, webpack always includes the entire `lodash` library instead of including only what we have used in our code.\n\nI have read numerous tutorials but haven't got the answer. Some of those answers will surely work if it was a webpack only project. But in our case, it is through nuxt config file.\n\nLooking forward to some help.\n\nBelow is the partial nuxt.config.js file. Only relevant/important parts are included:\n\n```\nconst resolve = require('resolve')\nconst webpack = require('webpack')\n\nmodule.exports = {\n /*\n ** Headers of the page\n */\n head: {\n },\n modules: [\n ['@nuxtjs/component-cache', { maxAge: 1000 * 60 * 10 }]\n ],\n plugins: [\n { src: '~/plugins/intersection', ssr: false },\n ],\n build: {\n vendor: ['moment', 'lodash'],\n analyze: {\n analyzerMode: 'static'\n },\n postcss: {\n plugins: {\n 'postcss-custom-properties': false\n }\n },\n plugins: [\n new webpack.IgnorePlugin(/^\\.\\/locale$/, /moment$/)\n ],\n /*\n ** Run ESLINT on save\n */\n extend (config, ctx) {\n // config.resolve.alias['create-api'] = `./create-api-${ctx.isClient ? 'client' : 'server'}.js`\n\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport orderBy from 'lodash/orderBy'\n```\n\n```text\nconst resolve = require('resolve')\nconst webpack = require('webpack')\n\nmodule.exports = {\n /*\n ** Headers of the page\n */\n head: {\n },\n modules: [\n ['@nuxtjs/component-cache', { maxAge: 1000 * 60 * 10 }]\n ],\n plugins: [\n { src: '~/plugins/intersection', ssr: false },\n ],\n build: {\n vendor: ['moment', 'lodash'],\n analyze: {\n analyzerMode: 'static'\n },\n postcss: {\n plugins: {\n 'postcss-custom-properties': false\n }\n },\n plugins: [\n new webpack.IgnorePlugin(/^\\.\\/locale$/, /moment$/)\n ],\n /*\n ** Run ESLINT on save\n */\n extend (config, ctx) {\n // config.resolve.alias['create-api'] = `./create-api-${ctx.isClient ? 'client' : 'server'}.js`\n\n }\n }\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nvendor\n```\n\n```text\nlodash\n```\n\n```text\nnpm install\n```\n\n```text\nnpm i -S lodash.orderby\n```\n\n```text\nimport orderBy from 'lodash/orderBy'\n```\n\n```text\nimport orderBy from 'lodash.orderby'\n```\n\n========================================\n\nComments:\n- Maybe the vendor list is telling webpack to include the entire package. Do you get an import error if you remove it from the vendor list?\n- @cgTag I just removed it from the vendor list. There is no error, but there is no change either. Full lodash is still a part of the vendor bundle.\n- What if you try the global reference like this `import orderBy from 'lodash'`. WebPack 2 and above will only import the single function. You don't have to define the path to the function.\n- Removing lodash from vendor still got it in vendor.js probably because of this - In Nuxt, a module is extracted into the vendor chunk when it's inside node_modules and used in at-least 1/2 of the total pages.\n- That sounds like Nuxt isn't using WebPack for bundling or it's doing a lot of the bundle work for it. I guess that's part of the template compiling needed for production. That's a shame as WebPack's tree shaking can do a better job. webpack.js.org/guides/tree-shaking\n- Nuxt is using webpack, and provides a way to include webpack plugins and even extend it. My problem is I don't know how and where to configure. Is there a way I can the config file here?\n- You can add it to the question.\n- Added to the question.\n- Sidenote: I'd strongly recommend to switch from `moment` to `date-fns` as well to reduce your file size.\n- @asanas I see you have the same problem as I, and you even use moment.js. I import moment like you do in the vendor file, but it imports all the unnecessary locale files – I just need one. I see you have an ignore plugin, but I don't really understand. How do you use it. And how do you use moment.js in your components? (I am still importing moment into my components: `import moment from 'moment'`. I would be very glad if you could give some help here. cheers\n- We did make a custom build using lodash cli and loaded only the packages we wanted in our build. the package is much smaller now.\n- you can achieve smaller size with tree-shaking as well but with less fuss of npm installing each function\n- @Claudiu Can you give an answer to show how that is done?","metadata":{"transformedAt":"2026-08-18T18:33:07.835Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":162,"estimatedTokens":1226}}79{"id":"stack-48535181","source":"stackoverflow","questionId":48535181,"title":"asyncData in component of Nuxtjs isn't working","tags":["vuejs2","nuxt.js"],"text":"Title: asyncData in component of Nuxtjs isn't working\nTags: vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have an issue with the nuxt.js project. I used async the component but when it rending, async wasn't working. This is my code.\n\nI have view document in https://nuxtjs.org/api/ but I don't know what is exactly my issue\n\nTest.vue (component)\n\n```\n\n \n {{ project }}\n \n \n\n \n\n export default {\n data() {\n return {\n project : 'aaaa'\n }\n },\n asyncData() {\n return {\n project : 'bbbb'\n }\n }\n }\n\n \n```\n\nThis is index.vue (page)\n\n```\n\n \n \n \n\n import Test from '~/components/Test.vue'\n export default {\n components : {\n Test\n }\n }\n\n \n```\n\nMy expected result is\n\n bbbb\n\nBut when running on http://localhost:3000 this is actual result\n\n aaaa\n\nI try to search google many times but don't have expected solution for me. Someone help me, please.\n\nThanks for helping.\n\n========================================\n\nTop Answer:\nYou cannot use asyncData in component.\n\nYou can choose to use the **fetch** method instead.\n\n\r\n\r\n\n```\n\n \n Loading....\n\n Error while fetching mountains\n\n \n \n {{ mountain.title }}\n \n \n \n\n export default {\n data() {\n return {\n mountains: []\n }\n },\n async fetch() {\n this.mountains = await fetch(\n 'https://api.nuxtjs.dev/mountains'\n ).then(res => res.json())\n }\n }\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div>\n {{ project }}\n </div>\n </template>\n\n <script>\n\n export default {\n data() {\n return {\n project : 'aaaa'\n }\n },\n asyncData() {\n return {\n project : 'bbbb'\n }\n }\n }\n\n </script>\n```\n\n```text\n<template>\n <test></test>\n </template>\n <script>\n\n import Test from '~/components/Test.vue'\n export default {\n components : {\n Test\n }\n }\n\n </script>\n```\n\n```text\nbbbb\n```\n\n```text\naaaa\n```\n\n```text\n<template>\n <div>\n {{ project }}\n </div>\n</template>\n\n<script>\nexport default {\n props: ['project'] // to receive data from page/index.vue\n}\n</script>\n```\n\n```text\n<template>\n <test :project=\"project\"></test>\n</template>\n\n<script>\nimport Test from '~/components/Test.vue'\nexport default {\n components : {\n Test\n },\n asyncData() {\n return {\n project : 'bbbb'\n }\n }\n}\n</script>\n```\n\n```text\ncomponents/\n```\n\n```text\nasyncData\n```\n\n```html\n<template>\n <div>\n <p v-if=\"$fetchState.pending\">Loading....</p>\n <p v-else-if=\"$fetchState.error\">Error while fetching mountains</p>\n <ul v-else>\n <li v-for=\"(mountain, index) in mountains\" :key=\"index\">\n {{ mountain.title }}\n </li>\n </ul>\n </div>\n</template>\n<script>\n export default {\n data() {\n return {\n mountains: []\n }\n },\n async fetch() {\n this.mountains = await fetch(\n 'https://api.nuxtjs.dev/mountains'\n ).then(res => res.json())\n }\n }\n</script>\n```\n\n========================================\n\nComments:\n- Woh, Thanks so much. It works like a charm :D, It had worked\n- I copied your code, and run it, it show me the error \"Duplicated key 'project' \", but I have removed this line of code \"data() { return { project : 'aaaa' } }\" in Test.vue. So It had worked.\n- Thank you so much for your assistance\n- oh... you right about the duplicate key, my bad. I will remove this part from my answer ;-)\n- Thank @NicolasPennec :) so, what files are able to use asyncData? Are all the files in pages/ folder only?\n- @HoangYell, yes it's available on page component only. \"asyncData is called every time before loading the page component.\" (See the \"asyncData\" guide: nuxtjs.org/guide/async-data)","metadata":{"transformedAt":"2026-08-18T18:33:07.835Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":236,"estimatedTokens":928}}80{"id":"stack-53535362","source":"stackoverflow","questionId":53535362,"title":"How to make Nuxt global object?","tags":["javascript","vue.js","nuxt.js"],"text":"Title: How to make Nuxt global object?\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to create custom object that could be available globally in every place (plugins, middleware, component's created/computed/mounted methods)\n\nI could access global object with context property (custom plugin, custom router middleware ... ),\n\nbut how to access it in component's `created()` ?\n\n========================================\n\nTop Answer:\nIt's also possible to inject an object. Useful if you want to create a plugin available everywhere.\n\nHere nuxt doc about this combined-inject.\n\n```\n// nuxt.config.js\n\nexport default {\n plugins: ['~/plugins/myPlugin.js']\n}\n```\n\n```\n// plugins/myPlugin.js\n\nimport Vue from 'vue'\n\nexport default ({ app }, inject) => {\n inject('myPlugin', Vue.observable({ foo: 'bar' }))\n}\n```\n\nAnd then you can access your plugin via prefix `$`.\n\n```\n// components/MyComponent.vue\n\n \n {{ $myPlugin.foo }}\n \n\nexport default {\n methods: {\n aMethod() {\n return this.$myPlugin.foo\n }\n }\n}\n\n```\n\nIt's also available in vuex and nuxt server context.\n\nYou can inject objects or functions.\n\nHere to learn more about client/server injection.\n\n========================================\n\nCode:\n```text\ncreated()\n```\n\n```text\n// your-project/store/index.js\n\nexport const state = () => ({\n var1: null,\n var2: null\n})\n\nexport const mutations = {\n SET_VAR_1 (state, value) {\n console.log('SET_VAR_1', value)\n state.var1 = value\n },\n SET_VAR_2 (state, value) {\n console.log('SET_VAR_2', value)\n state.var2 = value\n }\n}\n```\n\n```text\n// your-project/pages/index.js\n\n<template>\n <section>\n <h2>From Store</h2>\n <div>var1 = {{ $store.state.var1 }}</div>\n <div>var2 = {{ $store.state.var2 }}</div>\n </section>\n</template>\n```\n\n```text\n// your-project/pages/index.js\n\n<template>\n <section>\n <h2>From Store</h2>\n <div>var1 = {{ var1 }}</div>\n <div>var2 = {{ var2 }}</div>\n </section>\n</template>\n\n<script>\nexport default {\n async asyncData ({ store }) {\n return {\n var1: store.state.var1,\n var2: store.state.var2\n }\n }\n}\n</script>\n```\n\n```text\n<script>\nexport default {\n async asyncData ({ store }) {\n\n store.commit('SET_VAR_1', 'foo')\n store.commit('SET_VAR_2', 'bar')\n }\n}\n</script>\n```\n\n```text\n// your-project/pages/example.js\n\n<template>\n <section>\n <my-component :var1=\"$store.state.var1\" :var2=\"$store.state.var2\" />\n </section>\n</template>\n```\n\n```text\n// your-project/components/MyComponent.js\n<template>\n <section>\n <h2>From props</h2>\n <div>var1 = {{ var1 }}</div>\n <div>var2 = {{ var2 }}</div>\n </section>\n</template>\n\n<script>\n export default {\n props: ['var1', 'var2']\n }\n</script>\n```\n\n```text\nvar1\n```\n\n```text\nvar2\n```\n\n```text\n<page>.vue\n```\n\n```text\n<layout>.vue\n```\n\n```text\n<plugin>.vue\n```\n\n```text\n<middleware>.vue\n```\n\n```text\n<template>\n```\n\n```text\n$store\n```\n\n```text\n<script>\n```\n\n```text\nasyncData\n```\n\n```text\n<component>.vue\n```\n\n```js\n// nuxt.config.js\n\nexport default {\n plugins: ['~/plugins/myPlugin.js']\n}\n```\n\n```js\n// plugins/myPlugin.js\n\nimport Vue from 'vue'\n\nexport default ({ app }, inject) => {\n inject('myPlugin', Vue.observable({ foo: 'bar' }))\n}\n```\n\n```html\n// components/MyComponent.vue\n\n<template>\n <div :class=\"$myPlugin.foo\">\n {{ $myPlugin.foo }}\n </div>\n</template>\n\n<script>\nexport default {\n methods: {\n aMethod() {\n return this.$myPlugin.foo\n }\n }\n}\n</script>\n```\n\n```text\n$\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.835Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":247,"estimatedTokens":866}}81{"id":"stack-72367724","source":"stackoverflow","questionId":72367724,"title":"Client-only Nuxt 3 Vue plugin","tags":["javascript","vue.js","nuxt.js","nuxt3.js"],"text":"Title: Client-only Nuxt 3 Vue plugin\nTags: javascript, vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am new to Nuxt and Vue, so go easy on me. I am trying to create a video player component in my Nuxt 3 app using vue3-video-player, which doesn't seem to support SSR based on the following error I get when I import it in my video component:\n\n`ReferenceError: navigator is not defined`\n\nThis error persists even if the component is wrapped with ``. So, based on what I saw in the Nuxt 3 Documentation I thought I would create a client-only plugin located at `plugins/vue3-video-player.client.js` with the following contents:\n\n```\nimport Vue3VideoPlayer from '@cloudgeek/vue3-video-player'\n\nexport default defineNuxtPlugin((nuxtApp) => {\n nuxtApp.vueApp.use(Vue3VideoPlayer)\n})\n```\n\nBut when I try to use it in my component as ``, I get the following error:\n\n`[Vue warn]: Failed to resolve component: vue3-video-player`\n\nSo I guess my question is how do I create a client-only Vue component using Nuxt 3 plugins? Or is there an entirely different approach that would work better?\n\n========================================\n\nTop Answer:\nTo tag along with the given correct answer here,\n\nIf you're trying to install and use a third party NPM package, and running into \"window is not defined\" type errors, you can load the package as a plugin as follows (eg WAD)\n\nnpm install web-audio-daw\n\n```\n// plugins/wad.client.ts\nimport Wad from \"web-audio-daw\"\nexport default defineNuxtPlugin(nuxtApp => {\n return {\n provide: {\n Wad,\n }\n }\n})\n```\n\n```\n// pages/whatever.vue\n\nconst { $Wad } = useNuxtApp();\n// Can use $Wad normally from here on out\n\n```\n\n========================================\n\nCode:\n```js\nimport Vue3VideoPlayer from '@cloudgeek/vue3-video-player'\n\nexport default defineNuxtPlugin((nuxtApp) => {\n nuxtApp.vueApp.use(Vue3VideoPlayer)\n})\n```\n\n```text\nReferenceError: navigator is not defined\n```\n\n```text\n<ClientOnly>\n```\n\n```text\nplugins/vue3-video-player.client.js\n```\n\n```text\n<vue3-video-player>\n```\n\n```text\n[Vue warn]: Failed to resolve component: vue3-video-player\n```\n\n```js\nplugins: [\n {src: '~/plugins/apexcharts', mode: 'client'}\n ],\n```\n\n```text\nnuxt 3\n```\n\n```text\n.server\n```\n\n```text\n.client\n```\n\n```text\nplugins/apexcharts.client.ts\n```\n\n```text\nnuxt\n```\n\n```text\nnuxt 2\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nnuxt 2\n```\n\n```text\nplugins/\n```\n\n```text\nnuxt.config\n```\n\n```text\nimport Vue3VideoPlayer from '@cloudgeek/vue3-video-player'\n\nexport default defineNuxtPlugin((nuxtApp) => {\n \n return {\n provide: {\n Vue3VideoPlayer\n }\n }\n\n})\n```\n\n```text\n// plugins/wad.client.ts\nimport Wad from \"web-audio-daw\"\nexport default defineNuxtPlugin(nuxtApp => {\n return {\n provide: {\n Wad,\n }\n }\n})\n```\n\n```text\n// pages/whatever.vue\n<script lang=\"ts\" setup>\nconst { $Wad } = useNuxtApp();\n// Can use $Wad normally from here on out\n</script>\n```\n\n========================================\n\nComments:\n- Checked my answer here? stackoverflow.com/a/67751550/8816585 (at the bottom)\n- So say I went with the dynamic import at the bottom of your answer. How would I do the equivalent of `import x from 'some_module` using `import()` as you did in `components`?\n- We have the exact same question here: stackoverflow.com/a/67825061/8816585\n- @kissu your answer is related to nuxt 2, which is completely different.\n- @Syffys not completely different no. Maybe a bit regarding the syntax but the issue is the same.\n- Did you ever find a solution for this? I have the exact same problem.\n- When I use the .client trick I get \"Failed to resolve component: font-awesome-icon\". Is there some special trick to make this work?\n- This is actually highly inaccurate, Nuxt 3 still loads everything you've got there, you get those imported libraries/code in the entry JS file of the production build.\n- If you have to destruct with `const { $Wad } = useNuxtApp()`, it seems that the plugin doesn't save you much. You can import Wad in the page where you use it.\n- Thanks. How would you use params with the plugins fir Nuxt 3? ie `$Wad(param1,parm2)` ?\n- now how can i add `mode:client`?","metadata":{"transformedAt":"2026-08-18T18:33:07.835Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":179,"estimatedTokens":1031}}82{"id":"stack-56673290","source":"stackoverflow","questionId":56673290,"title":"Nuxt application returns 404 when dynamic routes are refreshed (Tomcat Server)","tags":["javascript","node.js","vue.js","nuxt.js"],"text":"Title: Nuxt application returns 404 when dynamic routes are refreshed (Tomcat Server)\nTags: javascript, node.js, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm doing the following:\n\n- Production Build: `npm run generate`\n\n- I copy the `dist` folder into the Tomcat Webapps, and it works fine\n\n- Whenever I refresh a dynamic route, it shows 404\n\nURLs that work:\n\n```\nhttps://ip:port/entryPath/dashboard/user\n```\n\nURLs that don't work:\n\n```\nhttps://ip:port/entryPath/dashboard/user/123\nhttps://ip:port/entryPath/dashboard/user/123/settings\nhttps://ip:port/entryPath/dashboard/user/123/privacy\n```\n\nI want to be able to an URL such as:\n\n```\nhttps://ip:port/entryPath/dashboard/user/123/activity\n```\n\nSo other users just clicking the URL should be directly able to access it. But it just ends up with a 404, no matter where I deploy.\n\n***Please Note:***\n\nMy intention is to deploy the `dist` folder contents on Tomcat webapps folder.\n\n========================================\n\nTop Answer:\nYou should setup your server to always request your spa's index.html for all routes that are not a file.\n\n.htaccess\n\n```\n\n RewriteEngine On\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule (.*) index.html [QSA,L]\n\n```\n\n========================================\n\nCode:\n```text\nhttps://ip:port/entryPath/dashboard/user\n```\n\n```text\nhttps://ip:port/entryPath/dashboard/user/123\nhttps://ip:port/entryPath/dashboard/user/123/settings\nhttps://ip:port/entryPath/dashboard/user/123/privacy\n```\n\n```text\nhttps://ip:port/entryPath/dashboard/user/123/activity\n```\n\n```text\nnpm run generate\n```\n\n```text\ndist\n```\n\n```text\ndist\n```\n\n```text\ngenerate: {\n // create an array of all routes for generating static pages\n // careful, this is only used by `npm run generate`. These must match SPA mode routes\n routes: function () {\n return axios.get(\n 'https://jsonplaceholder.typicode.com/users'\n )\n .then((response) => {\n let users = response.data.map((user) => {\n return {\n route: '/users/' + user.id,\n payload: user\n }\n });\n return ['/some-other-dynamic-route-or-array-of-routes/', ...users]\n });\n }\n }\n```\n\n```text\ngenerate\n```\n\n```text\ngenerate\n```\n\n```text\n*.vue\n```\n\n```text\npages\n```\n\n```text\ndist\n```\n\n```text\npages\n```\n\n```text\ngenerate\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ndist\n```\n\n```text\nhttps://ip:port/entryPath/dashboard/user/123\n```\n\n```text\nhttps://ip:port/entryPath#dashboard/user/123\n```\n\n```text\n<ifModule mod_rewrite.c>\n RewriteEngine On\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule (.*) index.html [QSA,L]\n</ifModule>\n```\n\n========================================\n\nComments:\n- Hi what server are you trying to host this. Currently writing an article on deploying nuxt applications. So I should be able to help\n- The \"Edit\" part saved me from getting mad - I believe it should be first solution in this answer :)\n- Quickest and easiest solution to the problem! Do you have an idea about how this effects SEO?","metadata":{"transformedAt":"2026-08-18T18:33:07.836Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":164,"estimatedTokens":779}}83{"id":"stack-54383432","source":"stackoverflow","questionId":54383432,"title":"Nuxt Error: Syntax Unexpected token export after installation","tags":["javascript","vue.js","babeljs","nuxt.js","babel-loader"],"text":"Title: Nuxt Error: Syntax Unexpected token export after installation\nTags: javascript, vue.js, babeljs, nuxt.js, babel-loader\nSource: Stack Overflow\n\nQuestion:\nI am using Nuxt for my Vue project, It was working fine. I deleted my yarn and NPM cache due to other project issues. I re-installed the packages for my Nuxt app. The app is Universal and Uses express. Installation and Dev server is running, but when I try to visit `http://localhost:3000/`, \n\nThe error: \n\n SyntaxError: Unexpected token export, shows up every time.\n\nI know this is babel issue but I don't how to resolve this issue on Nuxt.\n\nNuxt Configuration:\n\n```\nconst pkg = require('./package')\n\nmodule.exports = {\n mode: 'universal',\n\n /*\n ** Headers of the page\n */\n head: {\n title: pkg.name,\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: pkg.description }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n\n /*\n ** Customize the progress-bar color\n */\n loading: { color: '#fff' },\n\n /*\n ** Global CSS\n */\n css: [\n 'element-ui/lib/theme-chalk/index.css',\n '@mdi/font/css/materialdesignicons.min.css'\n ],\n\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n '@/plugins/element-ui',\n '~/plugins/vee-validate.js'\n ],\n\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://github.com/nuxt-community/axios-module#usage\n '@nuxtjs/axios',\n '@nuxtjs/apollo'\n ],\n apollo: {\n tokenName: 'yourApolloTokenName', // optional, default: apollo-token\n tokenExpires: 10, // optional, default: 7\n includeNodeModules: true, // optional, default: false (this includes graphql-tag for node_modules folder)\n authenticationType: 'Basic', // optional, default: 'Bearer'\n // optional\n errorHandler (error) {\n console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message)\n },\n // required\n clientConfigs: {\n default: {\n // required \n httpEndpoint: 'http://localhost:4000',\n // optional\n // See https://www.apollographql.com/docs/link/links/http.html#options\n httpLinkOptions: {\n credentials: 'same-origin'\n },\n // You can use `wss` for secure connection (recommended in production)\n // Use `null` to disable subscriptions\n wsEndpoint: null, // optional\n // LocalStorage token\n tokenName: 'apollo-token', // optional\n // Enable Automatic Query persisting with Apollo Engine\n persisting: false, // Optional\n // Use websockets for everything (no HTTP)\n // You need to pass a `wsEndpoint` for this to work\n websocketsOnly: false // Optional\n },\n test: {\n httpEndpoint: 'http://localhost:5000',\n wsEndpoint: 'ws://localhost:5000',\n tokenName: 'apollo-token'\n },\n // alternative: user path to config which returns exact same config options\n }\n },\n /*\n ** Axios module configuration\n */\n axios: {\n // See https://github.com/nuxt-community/axios-module#options\n },\n\n /*\n ** Build configuration\n */\n build: {\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n\n }\n }\n}\n```\n\nMy `package.json` file\n\n```\n{\n \"name\": \"app\",\n \"version\": \"1.0.0\",\n \"description\": \"My exceptional Nuxt.js project\",\n \"author\": \"Saima\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"cross-env NODE_ENV=development nodemon server/index.js --watch server\",\n \"build\": \"nuxt build\",\n \"start\": \"cross-env NODE_ENV=production node server/index.js\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"@mdi/font\": \"^3.3.92\",\n \"@nuxtjs/apollo\": \"^4.0.0-rc2.3\",\n \"@nuxtjs/axios\": \"^5.0.0\",\n \"cross-env\": \"^5.2.0\",\n \"element-ui\": \"^2.4.6\",\n \"express\": \"^4.16.3\",\n \"graphql-tag\": \"^2.10.1\",\n \"less\": \"^3.9.0\",\n \"less-loader\": \"^4.1.0\",\n \"nuxt\": \"^2.0.0\",\n \"vee-validate\": \"^2.1.5\"\n },\n \"devDependencies\": {\n \"babel-preset-env\": \"^1.7.0\",\n \"babel-register\": \"^6.26.0\",\n \"nodemon\": \"^1.11.0\"\n }\n}\n```\n\nHelp would be appreciated.\n\n========================================\n\nTop Answer:\nThis error can show up if you're importing an ES6 module which needs to be transpiled in order to load into the UI. In that case, this is fixed by adding the module into the `transpile` key of the `build` section of `nuxt.config.js` (at time of this post, the Nuxt transpile docs are a little confusing).\n\nFor instance, if you're trying to import a module called `@stylelib` then you'd want the following in your `nuxt.config.js`:\n\n```\nexport default {\n ...\n build: {\n ...\n transpile: ['@stylelib']\n }\n}\n```\n\n========================================\n\nCode:\n```text\nconst pkg = require('./package')\n\nmodule.exports = {\n mode: 'universal',\n\n /*\n ** Headers of the page\n */\n head: {\n title: pkg.name,\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: pkg.description }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n\n /*\n ** Customize the progress-bar color\n */\n loading: { color: '#fff' },\n\n /*\n ** Global CSS\n */\n css: [\n 'element-ui/lib/theme-chalk/index.css',\n '@mdi/font/css/materialdesignicons.min.css'\n ],\n\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n '@/plugins/element-ui',\n '~/plugins/vee-validate.js'\n ],\n\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://github.com/nuxt-community/axios-module#usage\n '@nuxtjs/axios',\n '@nuxtjs/apollo'\n ],\n apollo: {\n tokenName: 'yourApolloTokenName', // optional, default: apollo-token\n tokenExpires: 10, // optional, default: 7\n includeNodeModules: true, // optional, default: false (this includes graphql-tag for node_modules folder)\n authenticationType: 'Basic', // optional, default: 'Bearer'\n // optional\n errorHandler (error) {\n console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message)\n },\n // required\n clientConfigs: {\n default: {\n // required \n httpEndpoint: 'http://localhost:4000',\n // optional\n // See https://www.apollographql.com/docs/link/links/http.html#options\n httpLinkOptions: {\n credentials: 'same-origin'\n },\n // You can use `wss` for secure connection (recommended in production)\n // Use `null` to disable subscriptions\n wsEndpoint: null, // optional\n // LocalStorage token\n tokenName: 'apollo-token', // optional\n // Enable Automatic Query persisting with Apollo Engine\n persisting: false, // Optional\n // Use websockets for everything (no HTTP)\n // You need to pass a `wsEndpoint` for this to work\n websocketsOnly: false // Optional\n },\n test: {\n httpEndpoint: 'http://localhost:5000',\n wsEndpoint: 'ws://localhost:5000',\n tokenName: 'apollo-token'\n },\n // alternative: user path to config which returns exact same config options\n }\n },\n /*\n ** Axios module configuration\n */\n axios: {\n // See https://github.com/nuxt-community/axios-module#options\n },\n\n /*\n ** Build configuration\n */\n build: {\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n\n }\n }\n}\n```\n\n```text\n{\n \"name\": \"app\",\n \"version\": \"1.0.0\",\n \"description\": \"My exceptional Nuxt.js project\",\n \"author\": \"Saima\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"cross-env NODE_ENV=development nodemon server/index.js --watch server\",\n \"build\": \"nuxt build\",\n \"start\": \"cross-env NODE_ENV=production node server/index.js\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"@mdi/font\": \"^3.3.92\",\n \"@nuxtjs/apollo\": \"^4.0.0-rc2.3\",\n \"@nuxtjs/axios\": \"^5.0.0\",\n \"cross-env\": \"^5.2.0\",\n \"element-ui\": \"^2.4.6\",\n \"express\": \"^4.16.3\",\n \"graphql-tag\": \"^2.10.1\",\n \"less\": \"^3.9.0\",\n \"less-loader\": \"^4.1.0\",\n \"nuxt\": \"^2.0.0\",\n \"vee-validate\": \"^2.1.5\"\n },\n \"devDependencies\": {\n \"babel-preset-env\": \"^1.7.0\",\n \"babel-register\": \"^6.26.0\",\n \"nodemon\": \"^1.11.0\"\n }\n}\n```\n\n```text\nhttp://localhost:3000/\n```\n\n```text\npackage.json\n```\n\n```text\nplugins: [\n {src: '~/plugins/element-ui', ssr: false},\n {src: '~/plugins/vee-validate.js', ssr: true},\n],\n```\n\n```text\nexport default {\n ...\n build: {\n ...\n transpile: ['@stylelib']\n }\n}\n```\n\n```text\ntranspile\n```\n\n```text\nbuild\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n@stylelib\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nenv: { \n strapiBaseUri: process.env.API_URL || \"http://localhost:1337\"\n},\n```\n\n```text\nnpm run start\n```\n\n```text\nnpm run dev\n```\n\n========================================\n\nComments:\n- Not familiar with Nuxt but it looks like it's a syntax error before an export statement, have you checked for syntax errors in the `./package` directory?\n- @Azeame I installed a new nuxt app, but still getting the same error message.\n- @Azeame package is actually the package.json file.\n- Can you make sure it's valid (package.json) ?\n- @BeniaminH package.json is added.\n- @BeniaminH package.json is valid\n- I tried this issue on others computer and still the same error.\n- It's just a guess - what if you change this: `build: { babel: { presets: ['es2015', 'stage-0'] } }` in your nuxt config link\n- or `presets: ['@nuxt/babel-preset-app']`\n- I will try this...............\n- @BeniaminH no luck\n- :/ sorry, I have no other ideas.\n- @BeniaminH I completely created a new nuxt app still the same issue.\n- @BeniaminH I am glad that you give time.\n- @BeniaminH are you sure this is babel issue?\n- could be caused by a plugin creating an issue with ssr. could you try and change nuxt.config.js like this. `plugins: [{src: '~/plugins/element-ui', ssr: false},{src: '~/plugins/vee-validate.js', ssr: false}]` and in the build section, `build: { transpile :[ '/plugins'], //leave other elements in...}`\n- It looks like, but I'm not 100% sure. You may want to read this\n- @Andrew1325 I just checked and vee-validate with srr false create errors when you reload the page. Keep true\n- Yeah fair enough. I didn't test it but figured it had to be one of the two.\n- I tested your snippet and its okay.","metadata":{"transformedAt":"2026-08-18T18:33:07.836Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":407,"estimatedTokens":2541}}84{"id":"stack-53410728","source":"stackoverflow","questionId":53410728,"title":"How to update Nuxt.js to the latest version","tags":["javascript","vue.js","nuxt.js"],"text":"Title: How to update Nuxt.js to the latest version\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt.js 1.2 in my project, but I want to update it to latest version. How to do it? What needs to be considered when updating the version?\n\n========================================\n\nCode:\n```text\nyarn upgrade nuxt@^2.3.2\n```\n\n```text\npackage.json\n```\n\n```text\nnode_modules\n```\n\n```text\nnode_modules\n```\n\n```text\nyarn.lock/package-lock.json\n```\n\n========================================\n\nComments:\n- nuxtjs.org/guide/release-notes/#migration-guide-for-2-0-0\n- nuxtjs.org/guide/upgrading\n- another simple way: `yarn upgrade nuxt --latest`\n- obviously for npm users, just change yarn -> npm\n- getting this error: Usage Error: Couldn't find a script named \"upgrade\". $ yarn run [--inspect] [--inspect-brk] [-T,--top-level] [-B,--binaries-only] [--require #0] ...","metadata":{"transformedAt":"2026-08-18T18:33:07.836Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":38,"estimatedTokens":222}}85{"id":"stack-63693060","source":"stackoverflow","questionId":63693060,"title":"Nuxt.js - The best place for API calls","tags":["vue.js","axios","nuxt.js","vuex"],"text":"Title: Nuxt.js - The best place for API calls\nTags: vue.js, axios, nuxt.js, vuex\nSource: Stack Overflow\n\nQuestion:\nI'm new to Vue.js Nuxt and all front-end stuff.\n\nI have a question about API calls. I'm not sure what is the right way, the best practice here.\n\nI have a store. In that store, I have actions that are calling my API and sets state eg.\n\n```\nasync fetchArticle({ state, commit }, uuid) {\n const response = await this.$axios.get(`articles/${uuid}/`)\n commit('SET_ARTICLE', response.data)\n},\n```\n\nAnd that is fine it is working for one component.\n\nBut what if I want to just fetch the article and not changing the state.\n\nTo be DRY first thing that comes to my mind is to create the service layer that is fetching the data and is used where it is needed.\n\nIs it the right approach? Where can I find some real-world examples that I can take inspiration from?\n\n========================================\n\nTop Answer:\nI will an example of a service layer implementation for my portfolio to create my dashboard that shows some statics about my github and stackoverflow profiles, to do this i created a folder called `services` inside the project root :\n\n```\npages\nservices\n |_AxiosConfig.js\n |_GitHubService.js\n |_StackoverflowService.js\n ...\n```\n\nin the `AxiosConfig.js` file i put i created an axios instance with its configuration :\n\n```\nimport axios from 'axios';\n\nconst clientAPI = url =>\n axios.create({\n baseURL: url,\n withCredentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n \n });\n\nexport default clientAPI;\n```\n\nthen in my `GitHubService.js` i imported that axios instance called `clientAPI` which i used to my requests :\n\n```\nimport clientAPI from './AxiosConfig';\n\nconst baseURL = 'https://api.github.com';\nexport default {\n getUser(name) {\n return clientAPI(baseURL).get('/users/' + name);\n },\n getRepos(name){\n return clientAPI(baseURL).get('/users/' + name+'/repos');\n\n },\n getEvents(name,page){\n\n return clientAPI(baseURL).get('/users/' + name+'/events?per_page=100&page='+page);\n\n },\n getLastYearCommits(name,repo){\n\n return clientAPI(baseURL).get('/repos/' + name+'/'+repo+'/stats/commit_activity');\n\n }\n\n};\n```\n\nthen in my page i used `asyncData` hook to fetch my data :\n\n```\nimport GitHubService from '../../services/GitHubService'\n\nexport default {\n ...\n async asyncData({ error }) {\n try {\n const { data } = await GitHubService.getUser(\"boussadjra\");\n const resRepos = await GitHubService.getRepos(\"boussadjra\");\n return {\n user: data,\n repos: resRepos.data\n };\n } catch (e) {\n error({\n statusCode: 503,\n message: \"We cannot find the user\"\n });\n }\n }\n```\n\n========================================\n\nCode:\n```text\nasync fetchArticle({ state, commit }, uuid) {\n const response = await this.$axios.get(`articles/${uuid}/`)\n commit('SET_ARTICLE', response.data)\n},\n```\n\n```js\nexport default $axios => resource => ({\n index() {\n return $axios.$get(`/${resource}`)\n },\n\n create(payload) {\n return $axios.$post(`/${resource}`, payload)\n },\n\n show(id) {\n return $axios.$get(`/${resource}/${id}`)\n },\n\n\n update(payload, id) {\n return $axios.$put(`/${resource}/${id}`, payload)\n },\n\n delete(id) {\n return $axios.$delete(`/${resource}/${id}`)\n }\n\n})\n```\n\n```js\nimport createRepository from '~/path/to/repository.js'\n\nexport default (ctx, inject) => {\n const repositoryWithAxios = createRepository(ctx.$axios)\n\n const repositories = {\n posts: repositoryWithAxios('posts'),\n users: repositoryWithAxios('users')\n //...\n }\n\n inject('repositories', repositories)\n}\n```\n\n```text\n@nuxtjs/axios\n```\n\n```text\n@nuxt/http\n```\n\n```text\npages\nservices\n |_AxiosConfig.js\n |_GitHubService.js\n |_StackoverflowService.js\n ...\n```\n\n```js\nimport axios from 'axios';\n\nconst clientAPI = url =>\n axios.create({\n baseURL: url,\n withCredentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n \n });\n\nexport default clientAPI;\n```\n\n```js\nimport clientAPI from './AxiosConfig';\n\nconst baseURL = 'https://api.github.com';\nexport default {\n getUser(name) {\n return clientAPI(baseURL).get('/users/' + name);\n },\n getRepos(name){\n return clientAPI(baseURL).get('/users/' + name+'/repos');\n\n },\n getEvents(name,page){\n\n return clientAPI(baseURL).get('/users/' + name+'/events?per_page=100&page='+page);\n\n },\n getLastYearCommits(name,repo){\n\n return clientAPI(baseURL).get('/repos/' + name+'/'+repo+'/stats/commit_activity');\n\n }\n\n};\n```\n\n```js\nimport GitHubService from '../../services/GitHubService'\n\nexport default {\n ...\n async asyncData({ error }) {\n try {\n const { data } = await GitHubService.getUser(\"boussadjra\");\n const resRepos = await GitHubService.getRepos(\"boussadjra\");\n return {\n user: data,\n repos: resRepos.data\n };\n } catch (e) {\n error({\n statusCode: 503,\n message: \"We cannot find the user\"\n });\n }\n }\n```\n\n```text\nservices\n```\n\n```text\nAxiosConfig.js\n```\n\n```text\nGitHubService.js\n```\n\n```text\nclientAPI\n```\n\n```text\nasyncData\n```\n\n```text\nexport default {\n async fetchArticle() {\n let response = await $nuxt.$axios.$get('/api-url')\n return response\n },\n}\n```\n\n========================================\n\nComments:\n- Thanks for your replay. In the end, I used a similar approach but also utilizing the power of plugins in nuxt dynamically injecting the $axios instance.\n- Now if we register that repositories file in the plugin array in nuxt.config.js, then isn't a bad practice? Because in that way, it will be imported to each vue component, however, each repo should be imported where is required. I'm thinking in terms of memory optimization.\n- I had asked the same thing as a separate question here stackoverflow.com/questions/70185004/…","metadata":{"transformedAt":"2026-08-18T18:33:07.836Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":280,"estimatedTokens":1454}}86{"id":"stack-53668165","source":"stackoverflow","questionId":53668165,"title":"Where is safest to store Json Web Tokens JWTs in client side?","tags":["security","jwt","token","nuxt.js"],"text":"Title: Where is safest to store Json Web Tokens JWTs in client side?\nTags: security, jwt, token, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHello stackoverflow community!\n\nWe build an SPA app with nuxts.js framework and we arrived to the point which is the safest way to store a JWT token from our backend API service. \n\nWe have two options cookies with httpOnly flag versus localStorage. I read a ton of articles about the comparison of this two options, althought half of developers support cookies and half of developers support localstorage.\n\nFor my point of view cookies seems safer way than localStorage to store a JWT in client side but i wonder if there is even a safer way than the above options.\n\nSo i thought about something. Nuxt.js framework offer us the opportunity to store environmental variables. Is it safer to store a JWT token as an environmental variable or is exact the same like the above options or is even worst.\n\nThank you in advance!\n\n========================================\n\nCode:\n```text\nset-cookie\n```\n\n```text\nhttpOnly\n```\n\n```text\nsecure\n```\n\n```text\nCSRF\n```\n\n```text\nXSS\n```\n\n```text\nXSS\n```\n\n```text\ncsp\n```\n\n```text\nhttps\n```\n\n```text\nsecure\n```\n\n========================================\n\nComments:\n- jwt token is per user. environmental variable is per server. Idk how u want to use them for jwt tokens..\n- @Aldarund Take a look on this: nuxtjs.org/api/configuration-env . By the way do you prefer cookies or localStorage for JWT storing?\n- and as i said its env for per server. You cant store individual user tokens there :)\n- If you want other answers, there are great discussions here too : stackoverflow.com/questions/27067251/…\n- Wow, really nice and detailed answer Reza! Personally i prefer cookies with httpFlag because you can prevent more easily CSRF attacks, i mean it's more under control, on the other hand XSS it's a big mess, it's not all under control, very good example is what you told about external scripts from CDN, scripts for Ads, tracking scripts for marketing purposes and general scripts that can be vulnerable. Anyways depends on each developer but for me the RULE is never trust Javascript. :) Have a nice day!\n- By general I can say, If your sure that your code is not vulnerable to XSS and framework is updated with no xss reported yet, then localStorage could be the best option, But if you even have a little possibility of that, then use Cookie but implement it completely. Cause lot's of new attacks are reported for it nowadays (check blackhat talks)\n- Good answer, personally I'm a bit paranoid when it comes to storing secrets, against CSRF it's easy to protect, however against XSS it's almost impossible. I usually go with cookies.","metadata":{"transformedAt":"2026-08-18T18:33:07.836Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":66,"estimatedTokens":679}}87{"id":"stack-66030282","source":"stackoverflow","questionId":66030282,"title":"How to catch server errors in Nuxt.js so it doesn't crash page render? (Vue)","tags":["javascript","vue.js","nuxt.js","apollo"],"text":"Title: How to catch server errors in Nuxt.js so it doesn't crash page render? (Vue)\nTags: javascript, vue.js, nuxt.js, apollo\nSource: Stack Overflow\n\nQuestion:\n**Context**\n\nThis question is related to my other question, How to handle apollo client errors crashing page render in Nuxt?\n, but I'll try to keep this isolated since I'd like this question focused only on Nuxt (minus apollo). However, I decided to ask this separate since I'm looking for an entirely different response/solution.\n\n**The problem**\n\nI'm currently maintaining a production Nuxt/Vue app that is using the `@nuxt/apollo` module to make GraphQL requests.\n\nThe problem, is that every now and then, the GraphQL server we rely on goes down and returns an HTML error page, which crashes the Apollo client. But because we're loading Apollo as a nuxt module, it crashes the page render pipeline as well. Giving us a generic server error page that looks like this;\n\nhttps://i.sstatic.net/OTNr4.png\n\nServer error\nAn error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.\n\nAnd the following stack trace:\n\n```\nERROR Network error: Unexpected token )\n at node_modules/apollo-client/bundle.umd.js:2006:26\n at Map.forEach ()\n at QueryManager.broadcastQueries (node_modules/apollo-client/bundle.umd.js:2004:20)\n at node_modules/apollo-client/bundle.umd.js:1483:29\n at processTicksAndRejections (node:internal/process/task_queues:94:5)\n```\n\nHowever, none of this stack trace allows us to see where nuxt is throwing the error, so we can handle it.\n\n**What we tried**\n\nWe've exhausted all our options looking into this issue for the past couple of weeks. We first tried to solve it by handling the error directly at Apollo level using all 3 apollo library abstractions's error handling solutions:\n\n- `@nuxt/apollo` module\n\n- `vue-apollo`\n\n- `apollo-client`\n\nIf you'd like to read up more on that (even though its kind of irrelevant to this question), you can read more on my original question here\n\nHowever, right now I'd prefer to know if there's a way to somehow handle these page render errors either by:\n\n- Making the errors fail silently, so the page still renders as normal\n\n- Allowing us to redirect to another page.\n\nSince the apollo nuxt module we are using currently isn't working for that, I'd like to know if Nuxt supports some kind of way to handle errors.\n\nIt didn't help much that Nuxt's documentation is pretty limited when it comes to error handling. At best, it has information regarding the error pages and how to redirect to the error pages using `context.error`. But it doesn't have a dedicated page on how to catch common errors. I have a feeling Nuxt hooks could be the answer, but documentation on them is hard to navigate and also sparse.\n\nThe most complete information source I found on nuxt error handling was this article, Error handling in NuxtJS, of which nothing suggested worked for us.\n\n**Summary**\n\nOur nuxt app is crashing when the `@nuxt/apollo` nuxt module we are using crashes. We'd like to know if there's some kind of standard nuxt way of catching it, or if the only solution possible is just migrating our entire app to not use `@nuxt/apollo` module and use the ES6 promise syntax and load `apollo-client` manually into the app as a standalone library that's not deeply integrated into the nuxt lifecycle.\n\n========================================\n\nTop Answer:\nTo prevent pages from being crashed, you need to handle errors and isolate them so they won't affect the rendering of other components. This can be achieved with the error handling concept of `ErrorBoundary`. You can create a common component to reuse the `ErrorBoundary` logic. There are several other benefits of this approach.\n\n- Helps to keep components free from error handling logic\n\n- Allows us to use declarative component composition instead of relying on imperative try/catch\n\n- We can be as granular as we want with it — wrap individual components or entire application pieces.\n\nHere is the example of how to create an error boundary.\n\n```\nexport default {\n name: 'ErrorBoundary',\n data: () => ({\n error: false\n }),\n errorCaptured (err, vm, info) {\n this.error = true\n },\n render (h) {\n return this.error ? h('p', 'Something went wrong') : this.$slots.default[0]\n }\n}\n```\n\nNow, you can wrap any component to the error boundary and isolate the error as given,\n\n```\n\n \n\n```\n\n### Caveats of `ErrorBoundary` component\n\nThere are some caveats when utilizing the `errorCaptured` hook. Currently, errors are only captured in:\n\n- render functions\n\n- watcher callbacks\n\n- lifecycle hooks\n\n- component event handlers\n\n========================================\n\nCode:\n```text\nERROR Network error: Unexpected token < in JSON at position 0 08:11:04\n\n at new ApolloError (node_modules/apollo-client/bundle.umd.js:92:26)\n at node_modules/apollo-client/bundle.umd.js:1588:34\n at node_modules/apollo-client/bundle.umd.js:2008:15\n at Set.forEach (<anonymous>)\n at node_modules/apollo-client/bundle.umd.js:2006:26\n at Map.forEach (<anonymous>)\n at QueryManager.broadcastQueries (node_modules/apollo-client/bundle.umd.js:2004:20)\n at node_modules/apollo-client/bundle.umd.js:1483:29\n at processTicksAndRejections (node:internal/process/task_queues:94:5)\n```\n\n```text\n@nuxt/apollo\n```\n\n```text\n@nuxt/apollo\n```\n\n```text\nvue-apollo\n```\n\n```text\napollo-client\n```\n\n```text\ncontext.error\n```\n\n```text\n@nuxt/apollo\n```\n\n```text\n@nuxt/apollo\n```\n\n```text\napollo-client\n```\n\n```js\nexport default {\n mounted() {\n if (!this.books.length) {\n // client side\n this.fetchBooks()\n }\n },\n\n serverPrefetch() {\n this.fetchBooks()\n },\n methods: {\n fetchBooks() {\n this.$apollo\n .query({\n query: gql`\n query books {\n books {\n title\n author\n test\n }\n }\n `,\n })\n .catch((e) => {\n console.log(e)\n })\n .then((data) => {\n /// set books\n })\n },\n },\n}\n```\n\n```js\n//nuxt.config.js\n hooks: {\n render: {\n errorMiddleware(app) {\n app.use((error, req, res, next) => {\n res.writeHead(307, {\n Location: '/network-error',\n })\n res.end()\n })\n },\n },\n },\n```\n\n```js\nexport default {\n apollo: {\n books: {\n query() {\n return gql`\n query books {\n books {\n title\n author\n test\n }\n }\n `\n },\n error() {\n return false\n },\n },\n },\n}\n```\n\n```text\nrenderRoute\n```\n\n```text\nerrorMiddleware\n```\n\n```text\nerrorMiddleware\n```\n\n```text\nerror\n```\n\n```text\nexport default {\n name: 'ErrorBoundary',\n data: () => ({\n error: false\n }),\n errorCaptured (err, vm, info) {\n this.error = true\n },\n render (h) {\n return this.error ? h('p', 'Something went wrong') : this.$slots.default[0]\n }\n}\n```\n\n```text\n<error-boundary>\n <counter />\n</error-boundary>\n```\n\n```text\nErrorBoundary\n```\n\n```text\nErrorBoundary\n```\n\n```text\nErrorBoundary\n```\n\n```text\nerrorCaptured\n```\n\n========================================\n\nComments:\n- It looks like you already found a solution for your problem and to answer your question there is no default way to handle error in Nuxt it all depends on where the error accurse (damirscorner.com/blog/posts/20200904-ErrorHandlingInNuxtjs.‌​html). The easiest way to solve the problem is where it accurse what is in Apollo module. And it looks like you solve it in your last version on Git\n- Actually, I still have the error @VictorPerez, I \"patched\" it by using the apollo link error middleware, but this causes a \"vnodes mismatch\" nuxt issue that ends up with a white screen in prod mode. So not really a solution either I'm afraid\n- I actually already went over that article a few times before asking this question, but that only gave me ways to log the error to the console or report it to Sentry. Not so much in terms of catching the error so it fails silently, unless I missed something? If you know of a way to handle this error silently without relying on the apollo link error middleware, that would solve all our issues\n- yup, we already plan to switch to this approach. Sorry I didn't mention this before. However, the codebase is quite large and migrating every single vue apollo smart query to this will take a long time. So we are hoping there's some way to handle these errors without a full refactor. I agree with you though, its likely something to do with the nuxt apollo module.\n- @sgarcia.dev please see my edit version, with more detailed explanation\n- Thank you for elaborating @victor-perez, step #2 of your update proved very helpful. Does that mean that the most we can do with SSR errors, is catch them with the error hook, and use `res.writeHead` to redirect to a new route? Asking in case there's a way to get access to the Nuxt context somehow, but I imagine that's probably not possible on SSR errors, correct?\n- Hey Kiran! I tried your Error Boundary solution by creating a new `` wrapper component and adding your code there, and wrapping a component that caused this Apollo Client error, but the error still crashed page render. Just letting you know","metadata":{"transformedAt":"2026-08-18T18:33:07.836Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":298,"estimatedTokens":2342}}88{"id":"stack-76803864","source":"stackoverflow","questionId":76803864,"title":"Eslint with Nuxt3 auto-import","tags":["javascript","vue.js","nuxt.js","eslint","nuxt3.js"],"text":"Title: Eslint with Nuxt3 auto-import\nTags: javascript, vue.js, nuxt.js, eslint, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nSeems very basic but I can't find anywhere an eslint setup that works with Nuxt3 auto-import, to avoid `no-undef` errors. I'm not using typescript.\n\nI tried the following packages: `@antfu/eslint-config`, `plugin:nuxt/recommended`, `@nuxt/eslint-config`, `@nuxtjs/eslint-config`, `@nuxt/eslint-config-typescript`, with no luck so far.\n\nThe only thing that works for now is setting each reference in .eslintrc `globals`...\n\n========================================\n\nCode:\n```text\nno-undef\n```\n\n```text\n@antfu/eslint-config\n```\n\n```text\nplugin:nuxt/recommended\n```\n\n```text\n@nuxt/eslint-config\n```\n\n```text\n@nuxtjs/eslint-config\n```\n\n```text\n@nuxt/eslint-config-typescript\n```\n\n```text\nglobals\n```\n\n```text\n\"@antfu/eslint-config\": \"^0.42.0\"\n\"eslint\": \"^8.49.0\"\n```\n\n```text\ndbaeumer.vscode-eslint\nvue.volar\n```\n\n```text\nmodule.exports = {\n extends: [\n '@antfu',\n ],\n};\n```\n\n```text\n{\n \"editor.formatOnSave\": false,\n \"editor.codeActionsOnSave\": {\n \"source.fixAll.eslint\": true\n },\n \"eslint.options\": {\n \"extensions\": [\n \".js\",\n \".vue\"\n ]\n },\n}\n```\n\n```text\nnuxt dev\n```\n\n```text\n.nuxt\n```\n\n========================================\n\nComments:\n- You can use explicit imports to avoid this problem. Implicit identifiers (whether global or scoped) are historically a common source of bugs — ESLint is trying to help you here.\n- Maybe, but Nuxt encourages using auto-imports, so you'd expect there to be a recommended solution.\n- There is now an experimental cli tool that works pretty well, I tried it on Nuxt3 and Vue project as well. It will install required packages, update you eslint config and even .vscode settings, if that is what you're into. Simply run `npx @antfu/eslint-config@latest`. Read more on antfu/eslint-config.\n- savior!! works with the @antfu you linked, not with the (not that) older one I was using, thanks.","metadata":{"transformedAt":"2026-08-18T18:33:07.836Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":90,"estimatedTokens":503}}89{"id":"stack-52793331","source":"stackoverflow","questionId":52793331,"title":"How to add meta in nuxt router?","tags":["javascript","vue.js","nuxt.js"],"text":"Title: How to add meta in nuxt router?\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn vue, we defined meta like this:\n\n```\nconst router = new VueRouter({\n routes: [\n {\n path: '/foo',\n component: Foo,\n children: [\n {\n path: 'bar',\n component: Bar,\n // a meta field\n meta: { requiresAuth: true }\n }\n ]\n }\n ]\n})\n```\n\nBut how do we define meta in nuxt?\n\n========================================\n\nTop Answer:\nI built a Nuxt module that basically injects page variables into the `route.meta` property at build time. Then you can use it inside `this.extendRoutes` or to generate sitemap routes with @nuxtjs/sitemap.\n\nInstall it via `npm install nuxt-route-meta` and add it to your `nuxt.config.js`:\n\n```\n// nuxt.config.js\n\nexport default {\n modules: [\n 'nuxt-route-meta',\n ],\n}\n```\n\nAdd meta properties in a page:\n\n```\nexport default {\n auth: true,\n meta: {\n theme: 'water',\n },\n}\n```\n\nAnd now you have the properties in `route.meta` in each route. You can for example check it by using `this.extendRoutes` inside a module:\n\n```\nexport default function () {\n this.extendRoutes(routes =>\n routes.forEach(route => {\n if (route.meta.auth) {\n // do something with auth routes\n }\n })\n )\n}\n```\n\n========================================\n\nCode:\n```text\nconst router = new VueRouter({\n routes: [\n {\n path: '/foo',\n component: Foo,\n children: [\n {\n path: 'bar',\n component: Bar,\n // a meta field\n meta: { requiresAuth: true }\n }\n ]\n }\n ]\n})\n```\n\n```text\nvue-router\n```\n\n```text\nmeta\n```\n\n```js\n// nuxt.config.js\n\nexport default {\n modules: [\n 'nuxt-route-meta',\n ],\n}\n```\n\n```js\nexport default {\n auth: true,\n meta: {\n theme: 'water',\n },\n}\n```\n\n```js\nexport default function () {\n this.extendRoutes(routes =>\n routes.forEach(route => {\n if (route.meta.auth) {\n // do something with auth routes\n }\n })\n )\n}\n```\n\n```text\nroute.meta\n```\n\n```text\nthis.extendRoutes\n```\n\n```text\nnpm install nuxt-route-meta\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nroute.meta\n```\n\n```text\nthis.extendRoutes\n```\n\n========================================\n\nComments:\n- There is an answer been accepted but bear in mind that when using Nuxt (in SSR mode), you don't get middleware to run anything initialy (pageload)... I chose to disregard middleware alltogether in Nuxt.\n- How can auth: true become part of meta. It is outside the {}?\n- It's the way the module is implemented. It adds all data inside the page object + the ones inside meta to route.meta.\n- I implemented it, but my route.meta is just {}.\n- @jolly Ah alright. It could be related to some feature used in the file that's not yet supported by nuxt-route-meta, but we could make it support it. Or it's some other small issue. I'd say best is to create an issue on github.com/dword-design/nuxt-route-meta/issues and link it here. So we do not debug stuff here on stack overflow :).","metadata":{"transformedAt":"2026-08-18T18:33:07.836Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":163,"estimatedTokens":736}}90{"id":"stack-74516951","source":"stackoverflow","questionId":74516951,"title":"How to use useQuery() for API route parameters in Nuxt 3?","tags":["javascript","vue.js","nuxt.js","nuxt3.js"],"text":"Title: How to use useQuery() for API route parameters in Nuxt 3?\nTags: javascript, vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm following a guide in which `api routes` are built like so:\n\n1 create `server/api/route.js` file:\n\n```\nexport default defineEventHandler((event) => {\n\n return {\n message: `hello api route`\n }\n})\n```\n\n2 use api route in component like so:\n\n```\n\nconst { data: message } = await useFetch('/api/route')\n\n \n api data {{ message }}\n\n \n\n```\n\nThis works but when I try to add a `query parameter` in `1.`:\n\n```\nexport default defineEventHandler((event) => {\n\n const { name } = useQuery(event)\n\n return {\n message: `hello api name parameter ${name}`\n }\n})\n```\n\nand call it in a component `2.`:\n\n```\n\nconst { data: message } = await useFetch('/api/route?name=mario')\n\n \n api data {{ message }}\n\n \n\n```\n\nthe `message` property is empty. It seems that `useQuery(event)` produces an empty variable. Any idea why this is not working?\n\n========================================\n\nTop Answer:\nTry `getQuery` instead of `useQuery`\n\n```\nexport default defineEventHandler((event) => {\n const { name } = getQuery(event);\n return {\n message: `hello api name parameter ${name}`,\n };\n});\n```\n\n========================================\n\nCode:\n```text\nexport default defineEventHandler((event) => {\n\n return {\n message: `hello api route`\n }\n})\n```\n\n```text\n<script setup>\nconst { data: message } = await useFetch('/api/route')\n</script>\n\n<template>\n <div>\n <p>api data {{ message }}</p>\n </div>\n</template>\n```\n\n```text\nexport default defineEventHandler((event) => {\n\n const { name } = useQuery(event)\n\n return {\n message: `hello api name parameter ${name}`\n }\n})\n```\n\n```text\n<script setup>\nconst { data: message } = await useFetch('/api/route?name=mario')\n</script>\n\n<template>\n <div>\n <p>api data {{ message }}</p>\n </div>\n</template>\n```\n\n```text\napi routes\n```\n\n```text\nserver/api/route.js\n```\n\n```text\nquery parameter\n```\n\n```text\n1.\n```\n\n```text\n2.\n```\n\n```text\nmessage\n```\n\n```text\nuseQuery(event)\n```\n\n```text\nuseQuery(event)\n```\n\n```text\ngetQuery(event)\n```\n\n```text\nexport default defineEventHandler((event) => {\n const { name } = getQuery(event);\n return {\n message: `hello api name parameter ${name}`,\n };\n});\n```\n\n```text\ngetQuery\n```\n\n```text\nuseQuery\n```\n\n```text\nuseBody(event)\n```\n\n```text\nreadBody(event)\n```\n\n```text\nuseQuery(event)\n```\n\n```text\ngetQuery(event)\n```\n\n========================================\n\nComments:\n- useBody(event) is also no longer supported. Replacement is readBody(event)","metadata":{"transformedAt":"2026-08-18T18:33:07.836Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":193,"estimatedTokens":645}}91{"id":"stack-75503557","source":"stackoverflow","questionId":75503557,"title":"How to watch route in Nuxt 3?","tags":["nuxt.js","nuxt3.js"],"text":"Title: How to watch route in Nuxt 3?\nTags: nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI can't figure out how to watch routes in Nuxt3.\n\nIn Nuxt2 was very easy to make it in any component. Did anyone knows how can i write this in Nuxt3?\n\n```\n\nexport default {\n ....\n watch: {\n $route(to, from) {\n console.log('route change to', to)\n console.log('route change from', from)\n },\n },\n ....\n}\n\n```\n\n========================================\n\nTop Answer:\nThe \"myvariable\" either can be boolean or string or whatever.\n\n```\n\nconst myvariable = ref(true)\n\nwatch(\n () => route.path,\n () => {\n do my function or\n myvariable.value = false\n },\n);\n```\n\nThe \"myvariable\" either can be boolean or string or whatever.\n\n========================================\n\nCode:\n```html\n<script>\nexport default {\n ....\n watch: {\n $route(to, from) {\n console.log('route change to', to)\n console.log('route change from', from)\n },\n },\n ....\n}\n</script>\n```\n\n```html\n<script lang=\"ts\" setup>\n const menu = reactive({isOpen: false});\n\n const route = useRoute();\n\n watch(route, value => {\n menu.isOpen = false\n }, {deep: true, immediate: true})\n</script>\n```\n\n```text\nwatch(\n () => route.fullPath,\n () => {\n set(menuOpened, false);\n },\n);\n```\n\n```text\n<script setup>\n\nconst myvariable = ref(true)\n\nwatch(\n () => route.path,\n () => {\n do my function or\n myvariable.value = false\n },\n);\n```\n\n```text\n<script setup lang=\"ts\">\n\nconst route = useRoute();\nconst isMobileNavOpen = ref(false);\n\nwatch(() => route.fullPath, () => {\n isMobileNavOpen.value = false;\n});\n</script>\n```\n\n```text\nwatch(\n () => route.path,\n (newRoute) => {\n // your code here on route change...\n }\n)\n```\n\n```text\nroute\n```\n\n```text\nroute\n```\n\n```text\nwatch\n```\n\n```text\n<nuxt-link>\n```\n\n```text\nconst objToWatch = (any object that changes on route change, like asyncData);\n\n watchEffect(async () => {\n objToWatch\n console.log(\"route changed\")\n })\n```\n\n```text\nconst { name: routeName } = useRoute();\nconst isHome = computed(() => routeName === Route.HOME);\n```\n\n```text\nconst route = useRoute()\n\nwatch(() => route, (newRoute) => {\n console.log('track route: ', newRoute)\n}, { immediate: true, deep: true })\n```\n\n========================================\n\nComments:\n- u have really saved my day\n- This used to work fine but not anymore, maybe something changed in the last Nuxt version or so. Anyway, the hadicodes' answer is working fine, and it maybe makes more sense since it watches only for the path to change, not the route as the whole object.\n- Not working. hadicodes Answer should be the accepted one.\n- Be careful to use the watch method in a component that is not unmounted/mounted on route change so that the watcher can run !\n- @GeorgesA vuejs.org/guide/essentials/watchers#stopping-a-watcher > Watchers declared synchronously inside setup() or are bound to the owner component instance, and will be automatically stopped when the owner component is unmounted. In most cases, you don't need to worry about stopping the watcher yourself. The key here is that the watcher must be created synchronously: if the watcher is created in an async callback, it won't be bound to the owner component and must be stopped manually to avoid memory leaks.","metadata":{"transformedAt":"2026-08-18T18:33:07.836Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":164,"estimatedTokens":817}}92{"id":"stack-48436017","source":"stackoverflow","questionId":48436017,"title":"nuxt.js - how to set css background image dynamicaly","tags":["javascript","css","vuejs2","nuxt.js"],"text":"Title: nuxt.js - how to set css background image dynamicaly\nTags: javascript, css, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIm using Nuxt.js, and have a custom component. \n\nThis component has css in the component that sets a background image using css.\n\nI've tried the following but I get an error when I run this.\nThe error is:\n\n```\ninvalid expression: Invalid regular expression flags in\n```\n\n**Component**\n\n```\n\n \n \n \n \n \n {{ result }}\n \n \n Hero subtitle\n \n \n \n \n\nexport default {\n props: ['result', 'image']\n}\n\n.bg-img {\n background-image: url(~/assets/autumn-tree.jpg);\n background-position: center center;\n background-repeat: no-repeat;\n background-attachment: fixed;\n background-size: cover;\n background-color: #999;\n\n }\n\n```\n\n========================================\n\nTop Answer:\n`url('~@/assets/autumn-tree.jpg')`\n\nI made the same mistake thinking this was a nuxtjs problem. Webpack uses syntax to resolve assets.\n\n~ enforces webpack to treat the request as a module request. \nAnd then @ start at root.\n\n========================================\n\nCode:\n```text\ninvalid expression: Invalid regular expression flags in\n```\n\n```text\n<template>\n <section class=\"bg-img hero is-mobile header-image\" v-bind:style=\"{ backgroundImage: 'url(' + image + ')' }\">\n <div class=\"\">\n <div class=\"hero-body\">\n <div class=\"container\">\n <h1 class=\"title\">\n {{ result }}\n </h1>\n <h2 class=\"subtitle \">\n Hero subtitle\n </h2>\n </div>\n </div>\n </div>\n\n</section>\n</template>\n\n<script>\n\nexport default {\n props: ['result', 'image']\n}\n</script>\n\n\n<style>\n\n\n\n.bg-img {\n background-image: url(~/assets/autumn-tree.jpg);\n background-position: center center;\n background-repeat: no-repeat;\n background-attachment: fixed;\n background-size: cover;\n background-color: #999;\n\n }\n\n</style>\n```\n\n```text\n<div :style=\"{ backgroundImage: `url(${backgroundUrl})` }\">Content with background here</div>\n```\n\n```text\nv-bind:style=\"{ 'background-image': 'url(' + api.url + ')' }\"\n```\n\n```text\nurl('~@/assets/autumn-tree.jpg')\n```\n\n```text\n<template>\n <div>\n <div class=\"backgroundImage\" :style=\"{ backgroundImage: `url(${backgroundImagePath})` }\">\n </div>\n</template>\n\n<script>\nimport backgroundImagePath from '~/assets/image.jpeg'\nexport default {\n data() {\n return { backgroundImagePath }\n }\n}\n</script>\n```\n\n```html\n<b-col cols=\"8\" class=\"hj_projectImage justify-content-center text-center\" :style=\"{backgroundImage: `url(` + require(`~/assets/ProjectPictures/${this.ProjectPicture}`) + `)`}\">\n </b-col>\n```\n\n```text\nbackground-image: url(\"~assets/autumn-tree.jpg\");\n```\n\n```text\n<img :src=\"require(`~/assets/img/${image}.jpg`)\" />\n```\n\n```text\n${image}.jpg\n```\n\n```js\nexport default {\n computed: {\n backgroundStyles() {\n const imgUrl = this.$img('https://github.com/nuxt.png', { width: 100 })\n return {\n backgroundImage: `url('${imgUrl}')`\n }\n }\n }\n}\n```\n\n```text\n<template>\n <div class=\"flex flex-col h-screen\">\n <NavHeader />\n <HeroPage\n :pageImage=\"pageImage\"\n />\n <NavFooter />\n </div>\n</template>\n\n<script>\n//Import the banner image.\nimport pageImage from \"~/assets/banner/page-banner-about-us.jpg\";\n\nexport default {\n data() {\n return {\n pageImage: pageImage\n };\n },\n};\n</script>\n```\n\n```text\n<template>\n <div\n class=\"mx-auto relative block w-[1200px] top-0 z-10 overflow-hidden mt-0 mb-0 bg-cover py-16 rounded-b-lg\"\n :style=\"bgImage\"\n >\n </div>\n</template>\n\n<script>\nexport default {\n props: {\n pageImage: {\n type: String,\n default: \"\",\n },\n },\n\n data() {\n return {\n bgImage: {\n \"background-size\": \"cover\",\n \"background-image\": `url(${this.pageImage})`,\n },\n };\n },\n};\n</script>\n```\n\n========================================\n\nComments:\n- Just to note, this isn't specific to Nuxt, rather it's just a Vue template convention for binding a data value to the style attribute on an HTML element.\n- adding a verbal explanation is often helpful\n- I'm using nuxt image at the moment, Is using the $img, the recommended way to get background images to work while keeping the sizing properties?","metadata":{"transformedAt":"2026-08-18T18:33:07.836Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":231,"estimatedTokens":1060}}93{"id":"stack-72139073","source":"stackoverflow","questionId":72139073,"title":"Nuxt3 Vite server port","tags":["vue.js","nuxt.js","vite","nuxt3.js"],"text":"Title: Nuxt3 Vite server port\nTags: vue.js, nuxt.js, vite, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI need to config server port for Nuxt3. I try to do it so:\n\n`nuxt.config.ts`\n\n```\nimport { defineNuxtConfig } from 'nuxt3'\n\nexport default defineNuxtConfig(\n vite: {\n server: {\n port: 5000,\n },\n },\n})\n```\n\nBut it doesn't work. How to set server port in Nuxt3?\n\n========================================\n\nTop Answer:\nAs of the time of writing the answer, you can now define the port in your `nuxt.config` as follows:\n\n```\nexport default defineNuxtConfig({\n devServer: {\n port: 3001,\n },\n})\n```\n\nSource\n\n========================================\n\nCode:\n```js\nimport { defineNuxtConfig } from 'nuxt3'\n\nexport default defineNuxtConfig(\n vite: {\n server: {\n port: 5000,\n },\n },\n})\n```\n\n```text\nnuxt.config.ts\n```\n\n```json\n{\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev --port=5678\", // here\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\"\n },\n \"devDependencies\": {\n \"nuxt\": \"3.0.0-rc.1\"\n }\n}\n```\n\n```bash\nsudo npm i cross-env -g\n```\n\n```json\n{\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev --port=8001\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"cross-env PORT=8001 node .output/server/index.mjs\"\n },\n \"devDependencies\": {\n \"nuxt\": \"3.0.0-rc.4\"\n },\n}\n```\n\n```bash\nyarn run preview\n```\n\n```text\ndev\n```\n\n```text\nproduction\n```\n\n```text\ncross-env\n```\n\n```text\npackage.json\n```\n\n```js\nmodule.exports = {\n apps: [\n {\n name: 'NuxtAppName',\n exec_mode: 'cluster',\n instances: 'max',\n script: './.output/server/index.mjs',\n port: 5000\n }\n ]\n}\n```\n\n```js\nmodule.exports = {\n apps: [\n {\n name: 'NuxtApp',\n port: 3001,\n exec_mode: 'cluster',\n instances: '1',\n script: './.output/server/index.mjs',\n args: 'preview',\n },\n ],\n}\n```\n\n```text\necosystem.config.js\n```\n\n```text\nServer: {\n port: 'xxxx'\n}\n```\n\n```text\nhost: '0'\n```\n\n```text\nserver?: Omit<ServerOptions, 'port' | 'host'>;\n```\n\n```text\n\"dev\": \"nuxt dev --host=0 --port=3000\"\n```\n\n```js\nexport default defineNuxtConfig({\n devServer: {\n port: 3001,\n },\n})\n```\n\n```text\nnuxt.config\n```\n\n```text\nPORT=5000\n```\n\n```text\n.env\n```\n\n```text\nPORT\n```\n\n```text\nexport default defineNuxtConfig({\n devServer: {\n port: 3030\n },\n})\n```\n\n========================================\n\nComments:\n- Btw, as a side note since the RC1, you only need `import { defineNuxtConfig } from 'nuxt'` (no need for `nuxt3`). As shown here: nuxtjs.org/announcements/nuxt3-rc/#vite--webpack\n- product **PORT=5000 node .output/server/index.mjs**\n- The `devServer` configuration is available to set the port. stackoverflow.com/a/76281156/3247405\n- devServer did not work for me, this does. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:07.836Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":200,"estimatedTokens":696}}94{"id":"stack-51747207","source":"stackoverflow","questionId":51747207,"title":"Nuxt.js - How to use component inside layout?","tags":["javascript","vue.js","vuejs2","nuxt.js"],"text":"Title: Nuxt.js - How to use component inside layout?\nTags: javascript, vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSo I started playing around with Nuxt.js. \nI want to modify the default layout file to have a header and a footer.\nFor that I want to create a Header and a Footer component and place the page content tag (``) between them. However nothing happens. \n\nHere is my default.vue layout file:\n\n```\n\n \n \n \n \n\n### Footer\n\n \n\nimport Header from \"~/components/Header.vue\";\n\nexport default {\n components: {\n Header\n }\n};\n\n...\n\n```\n\nHere is my Header.vue component file:\n\n```\n\n### Header\n\n \n Home\n About\n \n\n.links {\n padding-top: 15px;\n}\n\n```\n\nIs there something wrong with this? Can I use components inside layouts files in the first place? Do I have to register newly created components separately somewhere else? \n\nSadly, there isn't much information specifically about this. How can I achieve it? \n\nThanks in advance!\n\n========================================\n\nTop Answer:\nYou can't use reserved HTML tags for component names. It includes footer, header etc. Here full list of reserved tag names.\n\nSo you need to rename your component to something different, for example my-header\n\n========================================\n\nCode:\n```text\n<template>\n <div>\n <header/>\n <nuxt/>\n <h1>Footer</h1>\n </div>\n</template>\n\n<script>\nimport Header from \"~/components/Header.vue\";\n\nexport default {\n components: {\n Header\n }\n};\n</script>\n\n<style>\n...\n</style>\n```\n\n```text\n<template>\n<div>\n<h1>Header</h1>\n <div class=\"links\">\n <nuxt-link to=\"/\" class=\"button--grey\">Home</nuxt-link>\n <nuxt-link to=\"/about\" class=\"button--grey\">About</nuxt-link>\n </div>\n</div>\n</template>\n\n<style>\n.links {\n padding-top: 15px;\n}\n</style>\n```\n\n```text\n<nuxt/>\n```\n\n```text\n<header />\n```\n\n```text\n<Header />\n```\n\n```text\nheader\n```\n\n========================================\n\nComments:\n- What does `nothing happend` means? no header and footer rendered out? just a blank page? any error in the browser console? or nodejs console?\n- This seems not to be the case anymore. Just created a \"Footer\" component just fine\n- @brpaz Footer != footer. It's still a case","metadata":{"transformedAt":"2026-08-18T18:33:07.837Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":131,"estimatedTokens":548}}95{"id":"stack-55124672","source":"stackoverflow","questionId":55124672,"title":"Load data from JSON file in assets with NUXT.js","tags":["json","vue.js","axios","nuxt.js"],"text":"Title: Load data from JSON file in assets with NUXT.js\nTags: json, vue.js, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSuppose I have `assets/data/geo/regions.json` file in my NUXT.js project folders structure. How can I read data from this file into my project?\n\nI have tried **axios** but I don't know what URL will have this file, I have tried all possible URLs. What is the better solution to do that? Maybe better to hold JSON files in `static` folder?\n\nThanks!\n\n========================================\n\nTop Answer:\nYou can import JSON files with `import data from 'data.json'` and use the `data` property straight in your component.\n\n========================================\n\nCode:\n```text\nassets/data/geo/regions.json\n```\n\n```text\nstatic\n```\n\n```text\nregions.json\n```\n\n```text\nstatic\n```\n\n```text\n/data/geo/regions.json\n```\n\n```text\nimport data from 'data.json'\n```\n\n```text\ndata\n```\n\n```text\njsons = [\"json_one\",\"json_two\"]\njsons_readed = []\n\n// In the loop\nfile = require(`./assets/data/geo/${jsons[i]}`)\njsons_readed.push(file)\n```\n\n```text\nconst content = await this.$content('regions').fetch()\n```\n\n```text\ncontent\n```\n\n========================================\n\nComments:\n- Moved my JSON files to the `static/` folder and loaded them with **axios**. The link from this answer is useful. Thanks!\n- Can you please your solution @Dmytro Zarezenko ? just try and get the error: Module not found: Error: Can't resolve 'fs'\n- @ÂngeloRigo you can try this: `import json from \"~/static/json/sample.json\";`. By prepending `~/static`\n- Ok, but what if the filename is dynamic and I want to load few files in a loop?\n- this approach works nicely when you place your JSON in @/store\n- @DmytroZarezenko you will need to use dynamic imports for that\n- worked perfectly for storing something in the assets folder `import data from '~/assets/countries_states.json'`\n- I've tried nuxt content with the example given in the doc. It works with the example, however, if you change just the attributes name by something else then the example in the doc, you get nothing. So, when I read all this I kind of assumed that you could give any json with any attribute to Content and get the result in your component...but no.\n- Yes you can. You should ask a new question and add details.","metadata":{"transformedAt":"2026-08-18T18:33:07.837Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":76,"estimatedTokens":578}}96{"id":"stack-76839341","source":"stackoverflow","questionId":76839341,"title":"Which to use: $fetch, useAsyncData or useFetch for GET and POST requests in Nuxt 3?","tags":["laravel","nuxt.js","fetch-api","nuxt3.js"],"text":"Title: Which to use: $fetch, useAsyncData or useFetch for GET and POST requests in Nuxt 3?\nTags: laravel, nuxt.js, fetch-api, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt 3 with a Laravel API backend and trying to figure out which composable `useAsyncData` or `useFetch`, or just `$fetch` I should use for different API requests in CRUD and authentication.\n\nThe documentation says:\n\nuseFetch is the most straightforward way to handle data fetching in a component setup function. On the other hand, when wanting to make a network request based on user interaction, $fetch is almost always the right handler to go for.\n\nHowever, using $fetch in components without wrapping it with useAsyncData causes fetching the data twice: initially on the server, then again on the client-side during hydration, because $fetch does not transfer state from the server to the client. Thus, the fetch will be executed on both sides because the client has to get the data again. We recommend to use useFetch or useAsyncData + $fetch to prevent double data fetching when fetching the component data.\n\nYou can use $fetch for any method that are executed only on client-side.\n\nThe only example I saw of a `POST` request in the documentation uses `$fetch`. Almost all other examples are `GET` requests that use `useFetch`.\n\nDoes this mean `useFetch` should generally be used for `GET` requests and `$fetch` for `POST` and `PUT` requests?\n\nI'm confused because I've seen many tutorials of `POST` requests that use `useFetch` and `GET` requests that use `$fetch`.\n\nIs it just easier to use `useFetch` for all requests since it has lots of Params, Options and Return Values that `$fetch` doesn't have, and also because it avoids the risk of fetching data twice in components?\n\nIn any case, is error handling for `useFetch`, `$fetch` and `useAsyncData` the same? Can I just use the same error handling in all 3 that I would for the Fetch API?\n\n========================================\n\nCode:\n```text\nuseAsyncData\n```\n\n```text\nuseFetch\n```\n\n```text\n$fetch\n```\n\n```text\nPOST\n```\n\n```text\n$fetch\n```\n\n```text\nGET\n```\n\n```text\nuseFetch\n```\n\n```text\nuseFetch\n```\n\n```text\nGET\n```\n\n```text\n$fetch\n```\n\n```text\nPOST\n```\n\n```text\nPUT\n```\n\n```text\nPOST\n```\n\n```text\nuseFetch\n```\n\n```text\nGET\n```\n\n```text\n$fetch\n```\n\n```text\nuseFetch\n```\n\n```text\n$fetch\n```\n\n```text\nuseFetch\n```\n\n```text\n$fetch\n```\n\n```text\nuseAsyncData\n```\n\n```js\n// useAsyncData\nconst { data } = await useAsyncData('item', () => $fetch('/api/item'))\n\n// useFetch ✅ Cleaner and easy to read.\nconst { data } = await useFetch('/api/item')\n```\n\n```js\n<script setup lang=\"ts\">\nfunction contactForm() {\n $fetch('/api/contact', {\n method: 'POST',\n body: { hello: 'world '}\n })\n}\n</script>\n\n<template>\n <button @click=\"contactForm\">Contact</button>\n</template>\n```\n\n```js\nexport default defineEventHandler(async () => {\n const sendEmail = await $fetch('https//send-email.com/api/send-email')\n return sendEmail\n})\n```\n\n```text\nuseFetch\n```\n\n```text\nuseFetch\n```\n\n```text\nuseAsyncData\n```\n\n```text\n$fetch\n```\n\n```text\nuseAsyncData\n```\n\n```text\nuseAsyncData\n```\n\n```text\nuseFetch\n```\n\n```text\nuseFetch\n```\n\n```text\n$fetch\n```\n\n```text\n$fetch\n```\n\n```text\n$fetch\n```\n\n```text\nuseFetch\n```\n\n```text\naysncData\n```\n\n```text\nuseFetch\n```\n\n========================================\n\nComments:\n- Nuxt team member here. It is important to note that `useFetch` is reactive (thus re-triggering when dependencies change) and might send more request than wanted. This can be undesired behavior (e.g. when submitting a login form on every keystroke after the first request failed because the password was wrong).\n- @manniL, If I understood your comment correctly. Any methods that are executed online on the client-side, you can use `$fetch`. Similar to my example when posting a data to the event handler?\n- You can use `$fetch` or `useFetch` for these, yes. But with `$fetch`, it is guaranteed to be a \"one-off\" call. `useFetch` can have unwanted side effects when e.g. sending a POST request - as it will send the request again in case the dependencies (e.g. username) change.\n- So it is not a good idea to use useFetch in another composable? 🤔\n- I'm from Brazil. Thanks for the answer.\n- For API routes event handler & client event handler always use `$fetch`.","metadata":{"transformedAt":"2026-08-18T18:33:07.837Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":38,"totalLines":207,"estimatedTokens":1076}}97{"id":"stack-62007932","source":"stackoverflow","questionId":62007932,"title":"How to set global $axios header in NuxtJS","tags":["vue.js","axios","nuxt.js"],"text":"Title: How to set global $axios header in NuxtJS\nTags: vue.js, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI've been trying to get this to work for two days now. I'm a brand new user to Nuxt (although I've used Vue for a few years now), so I'm just trying to wrap my brain around how this all works. \n\nIn my Nuxt project I have the Axios module installed:\n\n*nuxt.config.js*\n\n```\nexport default {\n plugins: [\n ...\n '~/plugins/axios',\n ],\n axios: {\n baseURL: 'https://my-url.com/wp-json/wp-v2',\n https: true,\n },\n}\n```\n\n*plugins/axios.js*\n\n```\nexport default ({ $axios, env }) => {\n $axios.onRequest(config => {\n $axios.setToken(env.WP_API_KEY, 'Bearer');\n });\n}\n```\n\nAnd in my page, I'm trying to use the `asyncData` function to pull data from my WordPress API, as such:\n\n```\nexport default {\n async asyncData(context) {\n const data = await context.$axios.$get('/media');\n console.log(data);\n return { data };\n }\n}\n```\n\nI keep receiving a 401 Not Authorized error however, essentially stating that my `Authorization: Bearer ` isn't being passed through. Using Postman however, I can verify that this endpoint does indeed work and returns all of the JSON I need, so the problem must lie in the way I have the axios global header set up. \n\nIt's been tough finding any real example on how to set a global header using the Nuxt/Axios module. I see in the docs how to use `setToken`, however it doesn't exactly show where to place that.\n\nWhat do I have set up wrong, and how do I fix it?\n\n========================================\n\nTop Answer:\nIf you are using Nuxt auth module, Here is how I have achived.\n\n```\n// nuxt.config.js\nmodules: [\n '@nuxtjs/auth',\n '@nuxtjs/axios',\n],\nauth: {\nstrategies: {\n local: {\n endpoints: {\n login: { url: '/auth/login', method: 'post', propertyName: 'accessToken' },\n logout: false,\n user: { url: '/auth/me', method: 'get', propertyName: false }\n },\n }\n},\nredirect: {\n login: '/auth/signin',\n logout: '/auth/signin',\n callback: false,\n home: false,\n},\ncookie: false,\ntoken: {\n prefix: 'token',\n},\n plugins: ['~/plugins/auth.js'],\n},\n\n// plugins/axios.js\nexport default function ({ $axios, $auth, redirect, store }) {\n$axios.onRequest((config) => {\n config.headers = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n 'Authorization': store.state.auth.tokenlocal, // refers to nuxt.config.js->auth.token\n }\n})\n\n $axios.onError((error) => {\n if (error.response.status === 500) {\n redirect('/error')\n }\n })\n}\n\n// store/index.js\nexport const getters = {\n authenticated(state) {\n return state.loggedIn;\n },\n user(state) {\n return state.user;\n }\n};\n\nexport const state = () => ({\n busy: false,\n loggedIn: false,\n strategy: \"local\",\n user: false,\n});\n```\n\n========================================\n\nCode:\n```text\nexport default {\n plugins: [\n ...\n '~/plugins/axios',\n ],\n axios: {\n baseURL: 'https://my-url.com/wp-json/wp-v2',\n https: true,\n },\n}\n```\n\n```text\nexport default ({ $axios, env }) => {\n $axios.onRequest(config => {\n $axios.setToken(env.WP_API_KEY, 'Bearer');\n });\n}\n```\n\n```text\nexport default {\n async asyncData(context) {\n const data = await context.$axios.$get('/media');\n console.log(data);\n return { data };\n }\n}\n```\n\n```text\nasyncData\n```\n\n```text\nAuthorization: Bearer <token>\n```\n\n```text\nsetToken\n```\n\n```text\nexport default ({ $axios, env }) => {\n $axios.onRequest(config => {\n config.headers.common['Authorization'] = `Bearer ${env.WP_API_KEY}`;\n });\n}\n```\n\n```text\nsetToken\n```\n\n```text\n// nuxt.config.js\nmodules: [\n '@nuxtjs/auth',\n '@nuxtjs/axios',\n],\nauth: {\nstrategies: {\n local: {\n endpoints: {\n login: { url: '/auth/login', method: 'post', propertyName: 'accessToken' },\n logout: false,\n user: { url: '/auth/me', method: 'get', propertyName: false }\n },\n }\n},\nredirect: {\n login: '/auth/signin',\n logout: '/auth/signin',\n callback: false,\n home: false,\n},\ncookie: false,\ntoken: {\n prefix: 'token',\n},\n plugins: ['~/plugins/auth.js'],\n},\n\n\n\n// plugins/axios.js\nexport default function ({ $axios, $auth, redirect, store }) {\n$axios.onRequest((config) => {\n config.headers = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n 'Authorization': store.state.auth.tokenlocal, // refers to nuxt.config.js->auth.token\n }\n})\n\n $axios.onError((error) => {\n if (error.response.status === 500) {\n redirect('/error')\n }\n })\n}\n\n\n\n// store/index.js\nexport const getters = {\n authenticated(state) {\n return state.loggedIn;\n },\n user(state) {\n return state.user;\n }\n};\n\nexport const state = () => ({\n busy: false,\n loggedIn: false,\n strategy: \"local\",\n user: false,\n});\n```\n\n```text\nexport default ({ $axios, env }) => {\n $axios.onRequest(config => {\n config.headers.common['Authorization'] = `Bearer ${env.WP_API_KEY}`;\n });\n}\n```\n\n========================================\n\nComments:\n- where do you put this?\n- Is this code in a separated file and where is this located?\n- @ST80 I haven't looked at this code in months, but I'm assuming that I kept it in the same `plugins/axios.js` file that I mentioned in the original post","metadata":{"transformedAt":"2026-08-18T18:33:07.837Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":261,"estimatedTokens":1291}}98{"id":"stack-51875055","source":"stackoverflow","questionId":51875055,"title":"How to run nuxt under pm2?","tags":["node.js","npm","ubuntu-16.04","pm2","nuxt.js"],"text":"Title: How to run nuxt under pm2?\nTags: node.js, npm, ubuntu-16.04, pm2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have 2 nuxt projects that need to be run on the server. Whenever I run the app locally it seems to be working with:`npm run dev`, but on the server this needs to be ran under a subprocess, so I use pm2 for that. But whenever I start running the same npm script with pm2 the process gets errored.\n\nThe command used for this is: `sudo pm2 start npm --name \"dev\" -- dev`, even when I run the apps separately it gets errored. `sudo pm2 start npm --name \"app1\" -- app1:dev` and `sudo pm2 start npm --name \"app2\" -- app2:dev`\n\n**package.json** \n\n```\n{\n ...\n \"scripts\": {\n \"app1:dev\": \"nuxt --config-file src/app1/nuxt.config.js -p=3000\",\n \"app2:dev\": \"nuxt --config-file src/app2/nuxt.config.js -p=4000\",\n \"dev\": \"concurrently \\\"npm run app1:dev\\\" \\\"npm run app2:dev\\\"\",\n },\n \"dependencies\": {\n ...\n },\n \"devDependencies\": {\n \"concurrently\": \"^3.6.0\",\n \"cross-env\": \"^5.2.0\"\n }\n}\n```\n\n**pm2 logs**\n\n```\n/home/ubuntu/.pm2/pm2.log :\nPM2 | [2018-08-16T10:05:55.046Z] PM2 log: ===============================================================================\n ...\nPM2 | [2018-08-16T10:07:32.825Z] PM2 log: App [app1] with id [0] and pid [11135], exited with code [1] via signal [SIGINT]\nPM2 | [2018-08-16T10:07:32.827Z] PM2 log: Starting execution sequence in -fork mode- for app name:app1 id:0\nPM2 | [2018-08-16T10:07:32.828Z] PM2 log: App name:app1 id:0 online\nPM2 | [2018-08-16T10:07:33.105Z] PM2 log: App [app1] with id [0] and pid [11145], exited with code [1] via signal [SIGINT]\nPM2 | [2018-08-16T10:07:33.106Z] PM2 log: Starting execution sequence in -fork mode- for app name:app1 id:0\nPM2 | [2018-08-16T10:07:33.108Z] PM2 log: App name:app1 id:0 online\nPM2 | [2018-08-16T10:07:33.383Z] PM2 log: App [app1] with id [0] and pid [11155], exited with code [1] via signal [SIGINT]\nPM2 | [2018-08-16T10:07:33.383Z] PM2 log: Script /usr/local/bin/npm had too many unstable restarts (16). Stopped. \"errored\"\n\n/home/ubuntu/.pm2/logs/app1-error.log :\n/home/ubuntu/.pm2/logs/app1-out.log :\n ...\n0|app1 | Specify configs in the ini-formatted file:\n0|app1 | /home/ubuntu/.npmrc\n0|app1 | or on the command line via: npm --key value\n0|app1 | Config info can be viewed via: npm help config\n0|app1 |\n0|app1 | npm@5.6.0 /usr/local/lib/node_modules/npm\n0|app1 |\n0|app1 | Usage: npm \n0|app1 |\n0|app1 | where is one of:\n0|app1 | access, adduser, bin, bugs, c, cache, completion, config,\n0|app1 | ddp, dedupe, deprecate, dist-tag, docs, doctor, edit,\n0|app1 | explore, get, help, help-search, i, init, install,\n0|app1 | install-test, it, link, list, ln, login, logout, ls,\n0|app1 | outdated, owner, pack, ping, prefix, profile, prune,\n0|app1 | publish, rb, rebuild, repo, restart, root, run, run-script,\n0|app1 | s, se, search, set, shrinkwrap, star, stars, start, stop, t,\n0|app1 | team, test, token, tst, un, uninstall, unpublish, unstar,\n0|app1 | up, update, v, version, view, whoami\n0|app1 |\n0|app1 | npm -h quick help on \n0|app1 | npm -l display full usage info\n0|app1 | npm help search for help on \n0|app1 | npm help npm involved overview\n0|app1 |\n ...\n```\n\nWhat does all of this mean, doesn't pm2 recognize the npm command? Is there a parameter I'm missing here? ... \n\n***extra info:*** \n\nserver: `Ubuntu 16.04`\n\nnpm version: `5.6.0`\n\nnuxt version: `1.4.2`\n\npm2 version: `3.0.3` \n\nnode version: `8.11.1`\n\n========================================\n\nTop Answer:\nThe code below: \n\n```\npm2 start npm --name \"anyName\" -- run dev\n```\n\n========================================\n\nCode:\n```text\n{\n ...\n \"scripts\": {\n \"app1:dev\": \"nuxt --config-file src/app1/nuxt.config.js -p=3000\",\n \"app2:dev\": \"nuxt --config-file src/app2/nuxt.config.js -p=4000\",\n \"dev\": \"concurrently \\\"npm run app1:dev\\\" \\\"npm run app2:dev\\\"\",\n },\n \"dependencies\": {\n ...\n },\n \"devDependencies\": {\n \"concurrently\": \"^3.6.0\",\n \"cross-env\": \"^5.2.0\"\n }\n}\n```\n\n```text\n/home/ubuntu/.pm2/pm2.log :\nPM2 | [2018-08-16T10:05:55.046Z] PM2 log: ===============================================================================\n ...\nPM2 | [2018-08-16T10:07:32.825Z] PM2 log: App [app1] with id [0] and pid [11135], exited with code [1] via signal [SIGINT]\nPM2 | [2018-08-16T10:07:32.827Z] PM2 log: Starting execution sequence in -fork mode- for app name:app1 id:0\nPM2 | [2018-08-16T10:07:32.828Z] PM2 log: App name:app1 id:0 online\nPM2 | [2018-08-16T10:07:33.105Z] PM2 log: App [app1] with id [0] and pid [11145], exited with code [1] via signal [SIGINT]\nPM2 | [2018-08-16T10:07:33.106Z] PM2 log: Starting execution sequence in -fork mode- for app name:app1 id:0\nPM2 | [2018-08-16T10:07:33.108Z] PM2 log: App name:app1 id:0 online\nPM2 | [2018-08-16T10:07:33.383Z] PM2 log: App [app1] with id [0] and pid [11155], exited with code [1] via signal [SIGINT]\nPM2 | [2018-08-16T10:07:33.383Z] PM2 log: Script /usr/local/bin/npm had too many unstable restarts (16). Stopped. \"errored\"\n\n/home/ubuntu/.pm2/logs/app1-error.log :\n/home/ubuntu/.pm2/logs/app1-out.log :\n ...\n0|app1 | Specify configs in the ini-formatted file:\n0|app1 | /home/ubuntu/.npmrc\n0|app1 | or on the command line via: npm <command> --key value\n0|app1 | Config info can be viewed via: npm help config\n0|app1 |\n0|app1 | npm@5.6.0 /usr/local/lib/node_modules/npm\n0|app1 |\n0|app1 | Usage: npm <command>\n0|app1 |\n0|app1 | where <command> is one of:\n0|app1 | access, adduser, bin, bugs, c, cache, completion, config,\n0|app1 | ddp, dedupe, deprecate, dist-tag, docs, doctor, edit,\n0|app1 | explore, get, help, help-search, i, init, install,\n0|app1 | install-test, it, link, list, ln, login, logout, ls,\n0|app1 | outdated, owner, pack, ping, prefix, profile, prune,\n0|app1 | publish, rb, rebuild, repo, restart, root, run, run-script,\n0|app1 | s, se, search, set, shrinkwrap, star, stars, start, stop, t,\n0|app1 | team, test, token, tst, un, uninstall, unpublish, unstar,\n0|app1 | up, update, v, version, view, whoami\n0|app1 |\n0|app1 | npm <command> -h quick help on <command>\n0|app1 | npm -l display full usage info\n0|app1 | npm help <term> search for help on <term>\n0|app1 | npm help npm involved overview\n0|app1 |\n ...\n```\n\n```text\nnpm run dev\n```\n\n```text\nsudo pm2 start npm --name \"dev\" -- dev\n```\n\n```text\nsudo pm2 start npm --name \"app1\" -- app1:dev\n```\n\n```text\nsudo pm2 start npm --name \"app2\" -- app2:dev\n```\n\n```text\nUbuntu 16.04\n```\n\n```text\n5.6.0\n```\n\n```text\n1.4.2\n```\n\n```text\n3.0.3\n```\n\n```text\n8.11.1\n```\n\n```text\nmodule.exports = {\n apps: [\n {\n name: 'nuxt-v2-app',\n port: 3000,\n script: './node_modules/nuxt/bin/nuxt-start',\n cwd: '/home/user/your-nuxt-project/nuxt-v2-app',\n env: {\n NODE_ENV: 'development'\n },\n env_production: {\n NODE_ENV: 'production'\n }\n },\n {\n name: 'nuxt-v3-app',\n port: 4000,\n script: '.output/server/index.mjs',\n cwd: '/home/user/your-nuxt-project/nuxt-v3-app',\n env: {\n NODE_ENV: 'development'\n },\n env_production: {\n NODE_ENV: 'production'\n }\n }\n ]\n};\n```\n\n```text\nnuxt-start\n```\n\n```text\n./node_modules/nuxt/bin/nuxt-start\n```\n\n```text\n.output/server/index.mjs\n```\n\n```text\nsudo pm2 start\n```\n\n```text\nsudo pm2 start npm -- app1:dev\n```\n\n```text\npm2 start npm --name \"anyName\" -- run dev\n```\n\n```text\nconst dotenv = require('dotenv')\n\nconst autorestart = true\nconst watch = false\nconst maxMemoryRestart = '512M'\n\nmodule.exports = {\n apps: [\n {\n name: 'myapp_dev',\n script: 'npm run clear && npm run dev',\n instances: 1,\n autorestart,\n watch,\n max_memory_restart: maxMemoryRestart,\n env: dotenv.config({ path: './config/.env.dev' }).parsed\n },\n {\n name: 'myapp_deb',\n script: 'npm run clear && npm run deb',\n instances: 1,\n autorestart,\n watch,\n max_memory_restart: maxMemoryRestart,\n env: dotenv.config({ path: './config/.env.deb' }).parsed\n },\n {\n name: 'myapp_sta',\n script: 'npm run clear && npm run sta',\n instances: 1,\n autorestart,\n watch,\n max_memory_restart: maxMemoryRestart,\n env: dotenv.config({ path: './config/.env.sta' }).parsed\n },\n {\n name: 'myapp_pro',\n script: 'npm run clear && npm run build && npm run start',\n instances: 1,\n autorestart,\n watch,\n max_memory_restart: maxMemoryRestart,\n env: dotenv.config({ path: './config/.env.pro' }).parsed\n }\n ],\n\n deploy: {\n myapp_dev: {\n user: 'zupstock',\n host: '192.168.1.103',\n ref: 'origin/master',\n repo: 'git@github.com:owner/myapp_v1.git',\n path: '/',\n 'post-deploy':\n 'cd myapp_v1 && npm install && pm2 startOrRestart ecosystem.config.js --only myapp_dev'\n }\n }\n}\n```\n\n```text\npm2 start ecosystem.config.js --only myapp_sta\n```\n\n```js\nmodule.exports = {\n apps: [\n {\n name: 'NuxtAppName',\n exec_mode: 'cluster', // Optional: If you want it run multiple instances.\n instances: 'max', // Or a number of instances.\n // 'max' auto detects how many CPU cores there are.\n // The previous option must exist to use the 'instances' option.\n script: '.output/server/index.mjs', // Nuxt v3\n // script: './node_modules/nuxt/bin/nuxt.js', // Nuxt v2\n args: 'start',\n port: 3000, // Optional: If you have multiple apps running,\n // that each need a specific port.\n },\n ],\n}\n```\n\n```text\necosystem.config.js\n```\n\n```text\nnpm run build\n```\n\n```text\npm2 start\n```\n\n```text\npm2 ls\n```\n\n```text\nmodule.exports = {\n apps: [\n {\n name: 'NuxtAppName',\n exec_mode: 'cluster',\n instances: 'max', // Or a number of instances\n script: './node_modules/nuxt/bin/nuxt.js',\n args: 'start'\n }\n ]\n}\n```\n\n```text\npm2 start ./node_modules/nuxt/bin/nuxt.js --name=\"<AppName>\" -- start\n```\n\n========================================\n\nComments:\n- This gives the same output in pm2 logs as posted in my question, status=errored as well. logs output\n- This works like a charm, thanks! The guide is indeed a must read for people who have the same problem.\n- upvoted, how do you specify the mode here though I keep getting an error saying No SSR build! Please start with `nuxt start --spa` or build using `nuxt build --universal`\n- Add `\"build\": \"nuxt build --universal\"` to your package.json\n- is newer version of nuxt no longer use nuxt-start ? I can't seem to find it in node_modules/nuxt/bin. There's only nuxt.js on that folder. I'm using 2.4.3\n- @AzDesign don't know if they removed it can't find it in their release notes, but you can get the nuxt-start package here npmjs.com/package/nuxt-start\n- No way to run it in production via a similar command?\n- It's okay, I found the official way: nuxtjs.org/faq/deployment-pm2","metadata":{"transformedAt":"2026-08-18T18:33:07.837Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":383,"estimatedTokens":2769}}99{"id":"stack-53346558","source":"stackoverflow","questionId":53346558,"title":"vue-devtools always disabled with nuxt.js","tags":["vue.js","nuxt.js","vue-devtools"],"text":"Title: vue-devtools always disabled with nuxt.js\nTags: vue.js, nuxt.js, vue-devtools\nSource: Stack Overflow\n\nQuestion:\nI am creating a new project using nuxt.js `v2.3.0`. When I run `npm run dev` in my IDE console everything compiles correctly but when I go to the page I get the following error: `Nuxt.js + Vue.js is detected on this page. Devtools inspection is not available because it's in production mode or explicitly disabled by the author.`\n\nHere is my `nuxt.config.js` file:\n\n```\nconst pkg = require('./package');\n\nmodule.exports = {\n mode: 'spa',\n\n dev: true,\n /*\n ** Headers of the page\n */\n head: {\n title: pkg.name,\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: pkg.description }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ],\n bodyAttrs: {\n class: 'h-100'\n },\n htmlAttrs: {\n class: 'h-100'\n }\n },\n\n /*\n ** Global CSS\n */\n css: [\n '@/assets/app.css'\n ],\n\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n '~/plugins/vue-notifications',\n '~/plugins/vue2-sidebar'\n ],\n\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://github.com/nuxt-community/axios-module#usage\n '@nuxtjs/axios',\n // Doc: https://bootstrap-vue.js.org/docs/\n 'bootstrap-vue/nuxt',\n // Doc: https://auth.nuxtjs.org/getting-starterd/setup\n '@nuxtjs/auth',\n '@nuxtjs/toast',\n '@nuxtjs/font-awesome'\n ],\n /*\n ** Axios module configuration\n */\n axios: {\n baseURL: 'http://users:8000'\n },\n\n /*\n ** Auth module configuration\n */\n auth: {\n strategies: {\n password_grant: {\n _scheme: 'local',\n endpoints: {\n login: {\n url: '/oauth/token',\n method: 'post',\n propertyName: 'access_token'\n },\n logout: 'api/logout',\n user: {\n url: 'api/user',\n method: 'get',\n propertyName: false\n },\n },\n tokenRequired: true,\n tokenType: 'Bearer'\n }\n },\n redirect: {\n login: \"/account/login\",\n logout: \"/\",\n callback: \"/account/login\",\n user: \"/\"\n },\n },\n\n /*\n ** Toast configuration\n */\n toast: {\n position: 'top-right',\n duration: 2000\n },\n\n loading: {\n name: 'chasing-dots',\n color: '#ff5638',\n background: 'white',\n height: '4px'\n },\n\n /*\n ** Router configuration\n */\n router: {\n middleware: ['auth']\n },\n\n /*\n ** Build configuration\n */\n build: {\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n\n }\n }\n};\n```\n\nIf I was running in production mode then I could understand but I'm not. I would expect vue-devtools to be running as normal.\n\n========================================\n\nTop Answer:\n### tl:dr:\n\n- `vue.config.devtools = true` in my `nuxt.config.js` does not work for me.\n\n- I ran `nuxt generate --devtools`, then `nuxt start` and opened the website in my browser. Doing so I could use the Vue-Devtools.\n\n- After that I now can still use the Vue-Devtools, even when running `nuxt dev` and no `vue.config.devtools` flag set in my `nuxt.config.js`\n\n### Full story\n\nSo enabling the `devtools` flag in `vue.config` as in the accepted answer did not work for me either.\n\nI first tried forcing the Vue-Devtools as described here. Adding a Plugin to set the `window` properties as described in the link. But without luck.\n\nDigging in the Nuxt code I noticed the `--devtools` flag for the `generate` command and wanted to see if the Vue-Devtools work at all with Nuxt.\n\nAfter running `nuxt generate --devtools`, then serving the application with `nuxt start`, I finally could access the devtools. \n\nAnd now, even when running `nuxt dev` they are still accessible. And I don't have `vue.config.devtools` set at all in my `nuxt.config.js`. Weird. But maybe that helps someone.\n\nMore context: I am running Nuxt in `spa` mode, with target `static` as I don't have a Node server in the Backend and just want to build an SPA.\n\n========================================\n\nCode:\n```js\nconst pkg = require('./package');\n\nmodule.exports = {\n mode: 'spa',\n\n dev: true,\n /*\n ** Headers of the page\n */\n head: {\n title: pkg.name,\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: pkg.description }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ],\n bodyAttrs: {\n class: 'h-100'\n },\n htmlAttrs: {\n class: 'h-100'\n }\n },\n\n /*\n ** Global CSS\n */\n css: [\n '@/assets/app.css'\n ],\n\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n '~/plugins/vue-notifications',\n '~/plugins/vue2-sidebar'\n ],\n\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://github.com/nuxt-community/axios-module#usage\n '@nuxtjs/axios',\n // Doc: https://bootstrap-vue.js.org/docs/\n 'bootstrap-vue/nuxt',\n // Doc: https://auth.nuxtjs.org/getting-starterd/setup\n '@nuxtjs/auth',\n '@nuxtjs/toast',\n '@nuxtjs/font-awesome'\n ],\n /*\n ** Axios module configuration\n */\n axios: {\n baseURL: 'http://users:8000'\n },\n\n /*\n ** Auth module configuration\n */\n auth: {\n strategies: {\n password_grant: {\n _scheme: 'local',\n endpoints: {\n login: {\n url: '/oauth/token',\n method: 'post',\n propertyName: 'access_token'\n },\n logout: 'api/logout',\n user: {\n url: 'api/user',\n method: 'get',\n propertyName: false\n },\n },\n tokenRequired: true,\n tokenType: 'Bearer'\n }\n },\n redirect: {\n login: \"/account/login\",\n logout: \"/\",\n callback: \"/account/login\",\n user: \"/\"\n },\n },\n\n /*\n ** Toast configuration\n */\n toast: {\n position: 'top-right',\n duration: 2000\n },\n\n\n loading: {\n name: 'chasing-dots',\n color: '#ff5638',\n background: 'white',\n height: '4px'\n },\n\n /*\n ** Router configuration\n */\n router: {\n middleware: ['auth']\n },\n\n /*\n ** Build configuration\n */\n build: {\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n\n }\n }\n};\n```\n\n```text\nv2.3.0\n```\n\n```text\nnpm run dev\n```\n\n```text\nNuxt.js + Vue.js is detected on this page. Devtools inspection is not available because it's in production mode or explicitly disabled by the author.\n```\n\n```text\nnuxt.config.js\n```\n\n```js\nvue: {\n config: {\n productionTip: false,\n devtools: true\n }\n}\n```\n\n```js\nexport default {\n mode: 'universal',\n devtools: true,\n\n ...\n}\n```\n\n```js\nvue: {\n config: {\n productionTip: false,\n devtools: true\n }\n}\n```\n\n```text\ndevtools: true\n```\n\n```text\nvue.config.devtools = true\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt generate --devtools\n```\n\n```text\nnuxt start\n```\n\n```text\nnuxt dev\n```\n\n```text\nvue.config.devtools\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ndevtools\n```\n\n```text\nvue.config\n```\n\n```text\nwindow\n```\n\n```text\n--devtools\n```\n\n```text\ngenerate\n```\n\n```text\nnuxt generate --devtools\n```\n\n```text\nnuxt start\n```\n\n```text\nnuxt dev\n```\n\n```text\nvue.config.devtools\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nspa\n```\n\n```text\nstatic\n```\n\n```js\nserver: {\n port: process.env.PORT || 5000,\n host: '0.0.0.0'\n},\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nvue.config.devtools = true\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- How do u run your app?\n- @Aldarund I use 'npm run dev' in my IDE console and run the app in Chrome\n- What version were you running when this worked? I'm on the latest v2.4.5 and had no luck. nuxtjs.org/api/configuration-build#devtools indicates we should be able to set `devtools` to `true` in the build config but that doesn't work for me either (nor in combination with this).\n- I found the snippet here: nuxtjs.org/api/configuration-vue-config\n- I like this answer. Because, code change just for debugging doesn't make sense.\n- Thank you, helped me with Nuxt 3 as well\n- I'm using Nuxt 2.16 for a legacy app. THIS was the only way I got it to work. Thank you!!!\n- to add to this, if you force a different port without specifying it in nuxt config as shown above it will always struggle to load dev tools. Keeping it on 3000 has always worked best for me","metadata":{"transformedAt":"2026-08-18T18:33:07.837Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":455,"estimatedTokens":2034}}100{"id":"stack-68728903","source":"stackoverflow","questionId":68728903,"title":"How to setup SASS/SCSS/sass-loader in Nuxt","tags":["vue.js","sass","nuxt.js"],"text":"Title: How to setup SASS/SCSS/sass-loader in Nuxt\nTags: vue.js, sass, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a Nuxt app and I want to use the CSS pre-processor.\n\nI installed the `sass-loader` fibers dependencies, but after installation, a message appears in the application console, which I presented in the image and in the code\n\nThis is code err:\n\n```\nWARN webpack@5.49.0 is installed but ^4.46.0 is expected 17:22:44\n\n WARN sass-loader@12.1.0 is installed but ^10.1.1 is expected\n\n \n\nRule can only have one resource source (provided resource and test + include + exclude) in { 17:22:46\n \"use\": [\n {\n \"loader\": \"/home/sergey/all_project/pro_projects_all_language/empty/node_modules/babel-loader/lib/index.js\",\n \"options\": {\n \"configFile\": false,\n \"babelrc\": false,\n \"cacheDirectory\": true,\n \"envName\": \"server\",\n \"presets\": [\n [\n \"/home/sergey/all_project/pro_projects_all_language/empty/node_modules/@nuxt/babel-preset-app/src/index.js\",\n {\n \"corejs\": {\n \"version\": 3\n }\n }\n ]\n ]\n },\n \"ident\": \"clonedRuleSet-29[0].rules[0].use[0]\"\n }\n ]\n}\n\n \"use\": [\n {\n \"loader\": \"node_modules/babel-loader/lib/index.js\",\n \"options\": {\n \"configFile\": false,\n \"babelrc\": false,\n \"cacheDirectory\": true,\n \"envName\": \"server\",\n \"presets\": [\n [\n \"node_modules/@nuxt/babel-preset-app/src/index.js\",\n {\n \"corejs\": {\n \"version\": 3\n }\n }\n ]\n ]\n },\n \"ident\": \"clonedRuleSet-29[0].rules[0].use[0]\"\n }\n ]\n }\n at checkResourceSource (node_modules/@nuxt/webpack/node_modules/webpack/lib/RuleSet.js:167:11)\n at Function.normalizeRule (node_modules/@nuxt/webpack/node_modules/webpack/lib/RuleSet.js:198:4)\n at node_modules/@nuxt/webpack/node_modules/webpack/lib/RuleSet.js:110:20\n at Array.map ()\n at Function.normalizeRules (node_modules/@nuxt/webpack/node_modules/webpack/lib/RuleSet.js:109:17)\n at new RuleSet (node_modules/@nuxt/webpack/node_modules/webpack/lib/RuleSet.js:104:24)\n at new NormalModuleFactory (node_modules/@nuxt/webpack/node_modules/webpack/lib/NormalModuleFactory.js:115:18)\n at Compiler.createNormalModuleFactory (node_modules/@nuxt/webpack/node_modules/webpack/lib/Compiler.js:636:31)\n at Compiler.newCompilationParams (node_modules/@nuxt/webpack/node_modules/webpack/lib/Compiler.js:653:30)\n at Compiler.compile (node_modules/@nuxt/webpack/node_modules/webpack/lib/Compiler.js:661:23)\n at node_modules/@nuxt/webpack/node_modules/webpack/lib/Watching.js:77:18\n at AsyncSeriesHook.eval [as callAsync] (eval at create (node_modules/tapable/lib/HookCodeFactory.js:33:10), :24:1)\n at AsyncSeriesHook.lazyCompileHook (node_modules/tapable/lib/Hook.js:154:20)\n at Watching._go (node_modules/@nuxt/webpack/node_modules/webpack/lib/Watching.js:41:32)\n at node_modules/@nuxt/webpack/node_modules/webpack/lib/Watching.js:33:9\n at Compiler.readRecords (node_modules/@nuxt/webpack/node_modules/webpack/lib/Compiler.js:529:11)\n```\n\nI tried reinstalling dependencies, reinstalling a completely clean Nuxt application, and still the problem remains.\n\n========================================\n\nTop Answer:\nYou don't need Sass loader in Nuxt 3, just use this command to install sass in Nuxt 3:\n\n```\nnpm install sass --save-dev\n```\n\nFor Nuxt 2 you need the sass loader, try this for Nuxt 2:\n\n```\nnpm install --save-dev sass sass-loader@10\n```\n\n========================================\n\nCode:\n```text\nWARN webpack@5.49.0 is installed but ^4.46.0 is expected 17:22:44\n\n\n WARN sass-loader@12.1.0 is installed but ^10.1.1 is expected\n\n \n\n\nRule can only have one resource source (provided resource and test + include + exclude) in { 17:22:46\n \"use\": [\n {\n \"loader\": \"/home/sergey/all_project/pro_projects_all_language/empty/node_modules/babel-loader/lib/index.js\",\n \"options\": {\n \"configFile\": false,\n \"babelrc\": false,\n \"cacheDirectory\": true,\n \"envName\": \"server\",\n \"presets\": [\n [\n \"/home/sergey/all_project/pro_projects_all_language/empty/node_modules/@nuxt/babel-preset-app/src/index.js\",\n {\n \"corejs\": {\n \"version\": 3\n }\n }\n ]\n ]\n },\n \"ident\": \"clonedRuleSet-29[0].rules[0].use[0]\"\n }\n ]\n}\n\n \"use\": [\n {\n \"loader\": \"node_modules/babel-loader/lib/index.js\",\n \"options\": {\n \"configFile\": false,\n \"babelrc\": false,\n \"cacheDirectory\": true,\n \"envName\": \"server\",\n \"presets\": [\n [\n \"node_modules/@nuxt/babel-preset-app/src/index.js\",\n {\n \"corejs\": {\n \"version\": 3\n }\n }\n ]\n ]\n },\n \"ident\": \"clonedRuleSet-29[0].rules[0].use[0]\"\n }\n ]\n }\n at checkResourceSource (node_modules/@nuxt/webpack/node_modules/webpack/lib/RuleSet.js:167:11)\n at Function.normalizeRule (node_modules/@nuxt/webpack/node_modules/webpack/lib/RuleSet.js:198:4)\n at node_modules/@nuxt/webpack/node_modules/webpack/lib/RuleSet.js:110:20\n at Array.map (<anonymous>)\n at Function.normalizeRules (node_modules/@nuxt/webpack/node_modules/webpack/lib/RuleSet.js:109:17)\n at new RuleSet (node_modules/@nuxt/webpack/node_modules/webpack/lib/RuleSet.js:104:24)\n at new NormalModuleFactory (node_modules/@nuxt/webpack/node_modules/webpack/lib/NormalModuleFactory.js:115:18)\n at Compiler.createNormalModuleFactory (node_modules/@nuxt/webpack/node_modules/webpack/lib/Compiler.js:636:31)\n at Compiler.newCompilationParams (node_modules/@nuxt/webpack/node_modules/webpack/lib/Compiler.js:653:30)\n at Compiler.compile (node_modules/@nuxt/webpack/node_modules/webpack/lib/Compiler.js:661:23)\n at node_modules/@nuxt/webpack/node_modules/webpack/lib/Watching.js:77:18\n at AsyncSeriesHook.eval [as callAsync] (eval at create (node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:24:1)\n at AsyncSeriesHook.lazyCompileHook (node_modules/tapable/lib/Hook.js:154:20)\n at Watching._go (node_modules/@nuxt/webpack/node_modules/webpack/lib/Watching.js:41:32)\n at node_modules/@nuxt/webpack/node_modules/webpack/lib/Watching.js:33:9\n at Compiler.readRecords (node_modules/@nuxt/webpack/node_modules/webpack/lib/Compiler.js:529:11)\n```\n\n```text\nsass-loader\n```\n\n```js\nexport default {\n build: {\n loaders: {\n sass: {\n implementation: require('sass'),\n },\n scss: {\n implementation: require('sass'),\n },\n },\n }\n}\n```\n\n```html\n<template>\n <div>\n <span class=\"test\">\n Hello there\n </span>\n </div>\n</template>\n\n<style lang=\"sass\" scoped>\ndiv\n .test\n color: red\n</style>\n```\n\n```text\nyarn add -D sass sass-loader@10.1.1\n```\n\n```text\nnpm i -D sass-loader@10.1.1 --save-exact && npm i -D sass\n```\n\n```text\nsass-loader\n```\n\n```text\n10.x.x\n```\n\n```text\n11.0.0\n```\n\n```text\n<style lang=\"sass\">\n```\n\n```text\n.vue\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nsass\n```\n\n```text\n/ for divison\n```\n\n```text\nnpm install sass --save-dev\n```\n\n```text\nnpm install --save-dev sass sass-loader@10\n```\n\n========================================\n\nComments:\n- I have been writing on Nuxt for 1 year now. I have always used scss, I have a project, everything works there, but I wanted to change the concept of the application and decided to rewrite some binders, and in my empty project, when I do - it says an error, I can also show it, but it is already different from the one I have just given. And I used the Nuxt documentation, but still nothing helped. I did as you said, I have the same error... Can you try to install a clean project and do the same thing and say the result?\n- I do not doubt your qualifications) The fact is that I know how to work with SASS and SCSS, I have already worked with them for a long time, but I have an error when starting the application, I have not even written style in the component yet. And the application does not start anymore.\n- I ask the messenger to show a video from the screen, what happens and when\n- The profile was essentially for you to contact me. I don't know what is your setup and what you're used to but I can at least give you a working setup (present in my answer). For you to then investigate and find out where is the issue coming from on your side. @dotenv9\n- what about `nuxt3`?\n- @NtwariClaranceLiberiste not sure, didn't tried it myself.\n- I have a similar problem but fixes here didn't work please refer to my post: stackoverflow.com/questions/74798698/…\n- Strange that you needed to do that one. Glad it works at least!","metadata":{"transformedAt":"2026-08-18T18:33:07.837Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":273,"estimatedTokens":2139}}101{"id":"stack-57277941","source":"stackoverflow","questionId":57277941,"title":"Redirect after checking in Nuxt Asyncdata","tags":["javascript","vuejs2","nuxt.js"],"text":"Title: Redirect after checking in Nuxt Asyncdata\nTags: javascript, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am running Nuxt and I have the below function. I want to check if authenticated then redirect to the login page if not. I am getting the error `window is undefined` This make since because it is my understanding that `asyncdata()` is evaluated server side. What is the correct way to redirect. I tried to use the redirect method in `context` but it just brings up my 404. Thanks\n\n```\nasync asyncData(context) {\n if (!context.authenticated) {\n window.location = `${config.url}/sign_in`;\n }\n }\n```\n\n========================================\n\nTop Answer:\nThe accepted answer is probably for v1.\n\nFor Nuxt v2:\n\n```\nexport default {\n async asyncData({ redirect }) {\n redirect('/page');\n }\n}\n```\n\nhttps://nuxtjs.org/docs/internals-glossary/context/#redirect\n\n========================================\n\nCode:\n```text\nasync asyncData(context) {\n if (!context.authenticated) {\n window.location = `${config.url}/sign_in`;\n }\n }\n```\n\n```text\nwindow is undefined\n```\n\n```text\nasyncdata()\n```\n\n```text\ncontext\n```\n\n```text\nasync asyncData(context) {\n if (!context.authenticated) {\n context.redirect(`${config.url}/sign_in`);\n }\n }\n```\n\n```text\ncontext\n```\n\n```text\nexport default {\n async asyncData({ redirect }) {\n redirect('/page');\n }\n}\n```\n\n========================================\n\nComments:\n- Will not it cause the `Error: Redirected when going from \"/XXX\" to \"/XXX\" via a navigation guard.` error?","metadata":{"transformedAt":"2026-08-18T18:33:07.837Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":79,"estimatedTokens":387}}102{"id":"stack-67575652","source":"stackoverflow","questionId":67575652,"title":"How to access .env variables in a Nuxt plugin?","tags":["vue.js","environment-variables","nuxt.js","analytics","segment"],"text":"Title: How to access .env variables in a Nuxt plugin?\nTags: vue.js, environment-variables, nuxt.js, analytics, segment\nSource: Stack Overflow\n\nQuestion:\nSegment Analytics provides a snippet with a secret API key in it. In my `Nuxt.js` project I created a plugin called `segment.js` which I registered in my `nuxt.config.js`:\n\n`nuxt.config.js`\n\n```\nplugins: [\n {\n src: \"~/plugins/segment.js\",\n mode: 'client'\n }\n]\n```\n\nIn my `plugins/segment.js` file I have my snippet:\n\n```\n!function(){var analytics=window.analytics=...analytics.SNIPPET_VERSION=\"4.13.2\";\nanalytics.load(process.env.SEGMENT_API_SECRET);\nanalytics.page();\n}}();\n```\n\nObviously I don't want to have my secret API key exposed there so I have it stored in my `.env` file instead:\n\n`.env`\n\n```\nSEGMENT_API_SECRET=FR4....GSDF3S\n```\n\nProblem: `process.env.SEGMENT_API_SECRET` in `plugins/segment.js` is `undefined` so the snippet doesn't work. How can I access my `.env` variable `SEGMENT_API_SECRET` from my plugin `plugins/segment.js`?\n\n========================================\n\nTop Answer:\nFor me, I wanted to use my environment (.env) variables in my Nuxt Firebase Plugin: `/plugins/firebase.js`. Usually with Vue, you have to prefix these .env variables with `VUE_APP_`, for example: `VUE_APP_yourKeyName=YOUR_SECRET_VALUE`\n\nBut with Nuxt, you have to then set these .env variables in the Nuxt Config `nuxt.config.js` like so:\n\n```\n// .env\nVUE_APP_yourKeyName=YOUR_SECRET_VALUE\n```\n\n```\n// nuxt.config.js\nexport default {\n env: {\n NUXT_VAR_NAME: process.env.VUE_APP_yourKeyName,\n },\n}\n```\n\n```\n// /plugins/firebase.js\nconst firebaseConfig = {\n apiKey: process.env.NUXT_VAR_NAME,\n}\n```\n\nYou can read more about using Nuxt Environment Variables here.\n\nNOTE: For Nuxt versions > 2.12+, in cases where environment variables are required at runtime (not build time) it is recommended to replace the env property with runtimeConfig properties : publicRuntimeConfig and privateRuntimeConfig.\n\n========================================\n\nCode:\n```js\nplugins: [\n {\n src: \"~/plugins/segment.js\",\n mode: 'client'\n }\n]\n```\n\n```js\n!function(){var analytics=window.analytics=...analytics.SNIPPET_VERSION=\"4.13.2\";\nanalytics.load(process.env.SEGMENT_API_SECRET);\nanalytics.page();\n}}();\n```\n\n```text\nSEGMENT_API_SECRET=FR4....GSDF3S\n```\n\n```text\nNuxt.js\n```\n\n```text\nsegment.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nplugins/segment.js\n```\n\n```text\n.env\n```\n\n```text\n.env\n```\n\n```text\nprocess.env.SEGMENT_API_SECRET\n```\n\n```text\nplugins/segment.js\n```\n\n```text\nundefined\n```\n\n```text\n.env\n```\n\n```text\nSEGMENT_API_SECRET\n```\n\n```text\nplugins/segment.js\n```\n\n```js\nexport default {\n publicRuntimeConfig: {\n segmentApiSecret: process.env.SEGMENT_API_SECRET,\n }\n}\n```\n\n```js\n// segment.js\nexport default ({ $config: { segmentApiSecret } }) => {\n !function(){var analytics=window.analytics=...analytics.SNIPPET_VERSION=\"4.13.2\";\n analytics.load(segmentApiSecret);\n analytics.page();\n }}();\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```js\n// .env\nVUE_APP_yourKeyName=YOUR_SECRET_VALUE\n```\n\n```js\n// nuxt.config.js\nexport default {\n env: {\n NUXT_VAR_NAME: process.env.VUE_APP_yourKeyName,\n },\n}\n```\n\n```js\n// /plugins/firebase.js\nconst firebaseConfig = {\n apiKey: process.env.NUXT_VAR_NAME,\n}\n```\n\n```text\n/plugins/firebase.js\n```\n\n```text\nVUE_APP_\n```\n\n```text\nVUE_APP_yourKeyName=YOUR_SECRET_VALUE\n```\n\n```text\nnuxt.config.js\n```\n\n```ini\n// .env\nNUXT_PUBLIC_G_RECAPTCHA_SITE_KEY='xyz'\n```\n\n```js\n// nuxt.config.js\nruntimeConfig: {\n public: {\n GRecaptchaSiteKey: process.env.G_RECAPTCHA_SITE_KEY;\n }\n}\n```\n\n```js\n// /plugins/recaptch.js\nimport { VueReCaptcha } from \"vue-recaptcha-v3\";\nexport default defineNuxtPlugin((nuxtApp) => {\n const config = useRuntimeConfig();\n nuxtApp.vueApp.use(VueReCaptcha, {\n siteKey: `${config.public.GRecaptchaSiteKey}`,\n loaderOptions: {\n autoHideBadge: false,\n explicitRenderParameters: {\n badge: \"bottomleft\",\n },\n },\n });\n});\n```\n\n```text\n.env\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nuseRuntimeConfig()\n```\n\n```text\nvue-recaptcha-v3\n```\n\n========================================\n\nComments:\n- Just curious to know about potential harm these API key exposure can do, as I personally seen a few websites using segment and directly putting their API key like analytics.load('').\n- Please don't just post code that works but help point the user in the right direction with regard to the concepts they are asking about, and post links to documentation like Greg did below.\n- Hi @DanielStorey, I did not gave a lot of details here because the question was quite specific (usage of envs in a plugin), rather than generic explanation of env variables. That and the fact that drake is somebody that I helped quite a lot overall daily for some months. It was not his first nor last question regarding env variables: I cannot 100% duplicate my answers on each question too. I've actually wrote quite a more in-depth answer just few days after this one as you can see here and referenced several times to the OP afterwards.\n- This works, but does mean the secret value will be available from the client side. All someone has to do in the browser console is type `__NUXT__.config` and they'll be able to see all values from pubilcRuntimeConfig.\n- @sobmortin354 I never said the opposite, hence why it's called `public`RuntimeConfig. More details can be found here: stackoverflow.com/a/73139341/8816585\n- I know, I just thought it would be worth saying explicitly","metadata":{"transformedAt":"2026-08-18T18:33:07.837Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":33,"totalLines":259,"estimatedTokens":1381}}103{"id":"stack-52022541","source":"stackoverflow","questionId":52022541,"title":"export 'AddPlaceModal' was not found in '~/components/AddPlaceModal.vue'","tags":["javascript","vue.js","nuxt.js"],"text":"Title: export 'AddPlaceModal' was not found in '~/components/AddPlaceModal.vue'\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI just started using nuxt for vue. I added a component in the /components folder and I am trying to use it in one of my pages.\n\nUnfortunately, I get this warning, upon compilation: \n\n```\n\"export 'AddPlaceModal' was not found in '~/components/AddPlaceModal.vue'\n```\n\nI am trying to use it via:\n\n```\n\nimport {mapActions, mapGetters} from 'vuex';\nimport {AddPlaceModal} from '~/components/AddPlaceModal.vue'; \n\nexport default {\n components: {\n 'add-place-modal': AddPlaceModal\n },\n...\n```\n\nThe component itself looks like:\n\n```\n\nexport default {\n data() {\n googleLocation: null;\n },\n...\n```\n\nAny ideas why this may be?\n\n========================================\n\nTop Answer:\n**you have to remove the curly brackets**\n\n**do this:**\n\n https://i.sstatic.net/OZcXp.png\n\n**instead of:**\n\nhttps://i.sstatic.net/NRRFk.png\n\n========================================\n\nCode:\n```text\n\"export 'AddPlaceModal' was not found in '~/components/AddPlaceModal.vue'\n```\n\n```text\n<script>\nimport {mapActions, mapGetters} from 'vuex';\nimport {AddPlaceModal} from '~/components/AddPlaceModal.vue'; \n\nexport default {\n components: {\n 'add-place-modal': AddPlaceModal\n },\n...\n```\n\n```text\n<script>\nexport default {\n data() {\n googleLocation: null;\n },\n...\n```\n\n```text\nimport AddPlaceModal from '~/components/AddPlaceModal.vue';\n```\n\n========================================\n\nComments:\n- Yeah, thank you. If someone interested in what that curly-braces mean, open that link.\n- Thanks a lot. I'm used to angular so wasn't understanding why it was not working","metadata":{"transformedAt":"2026-08-18T18:33:07.837Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":90,"estimatedTokens":426}}104{"id":"stack-56013561","source":"stackoverflow","questionId":56013561,"title":"Nuxt render function for a string of HTML that contains Vue components","tags":["vue.js","dom","render","nuxt.js"],"text":"Title: Nuxt render function for a string of HTML that contains Vue components\nTags: vue.js, dom, render, nuxt.js\nSource: Stack Overflow\n\nQuestion:\n**I'm trying to solve this for Nuxt**\n\n**Codesandbox of a WIP not working: https://codesandbox.io/s/zw26v3940m**\n\nOK, so I have WordPress as a CMS, and it's outputting a bunch of HTML. A sample of the HTML looks like this:\n\n```\n'\n\n### A heading tag\n\nSlot text here\nsome text\n\n'\n```\n\nNotice that it contains a Vue component `` that has some props on it (the `image` prop is a JSON object I left out for brevity). That component is registered globally.\n\nI have a component that we wrote, called `` that works great in Vue, but doesn't work in Nuxt. Note the two render functions, one is for Vue the other is for Nuxt (obviously this is for examples sake, I wouldn't use both).\n\n```\nexport default {\n props: {\n html: {\n type: String,\n default: \"\"\n }\n },\n render(h, context) {\n // Worked great in Vue\n return h({ template: this.html })\n } \n render(createElement, context) {\n // Kind of works in Nuxt, but doesn't render Vue components at all\n return createElement(\"div\", { domProps: { innerHTML: this.html } })\n } \n}\n```\n\nSo the last render function works in Nuxt except it won't actually render the Vue components in `this.html`, it just puts them on the page as HTML.\n\nSo how do I do this in Nuxt? I want to take a string of HTML from the server, and render it on the page, and turn any registered Vue components into proper full-blown Vue components. Basically a little \"VueifyThis(html)\" factory.\n\n========================================\n\nTop Answer:\nAnd if you use the v-html directive to render the html?\n\nlike:\n\n```\n\n```\n\nI think it will do the job.\n\n========================================\n\nCode:\n```text\n'<h2>A heading tag</h2>\n<site-banner image=\"{}\" id=\"123\">Slot text here</site-banner>\n<p>some text</p>'\n```\n\n```text\nexport default {\n props: {\n html: {\n type: String,\n default: \"\"\n }\n },\n render(h, context) {\n // Worked great in Vue\n return h({ template: this.html })\n } \n render(createElement, context) {\n // Kind of works in Nuxt, but doesn't render Vue components at all\n return createElement(\"div\", { domProps: { innerHTML: this.html } })\n } \n}\n```\n\n```text\n<site-banner>\n```\n\n```text\nimage\n```\n\n```text\n<wp-content>\n```\n\n```text\nthis.html\n```\n\n```text\nexport default {\n props: {\n html: {\n type: String,\n default: \"\"\n }\n },\n render(h) {\n return h({\n template: `<div>${this.html}</div>`\n });\n }\n};\n```\n\n```text\nbuild: {\n extend(config, ctx) {\n // Include the compiler version of Vue so that <component-name> works\n config.resolve.alias[\"vue$\"] = \"vue/dist/vue.esm.js\"\n }\n }\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n<div v-html=\"html\"></div>\n```\n\n```text\n<div>\n```\n\n```text\ndynamicComponent()\n```\n\n```text\nWpContent\n```\n\n```text\n<script setup lang=\"ts\">\nimport { h } from 'vue';\n\nconst props = defineProps<{\n class: string;\n HTML: string\n}>();\nconst VNode = () => h('div', { class: props.class, innerHTML: props.HTML })\n</script>\n<template>\n <VNode />\n</template>\n```\n\n```text\nnuxt.config.ts\n```\n\n========================================\n\nComments:\n- One idea I had was trying to turn the HTML \"string\" into just a JSX template (by removing the \" from the string basically). But I'm not sure that's possible, I couldn't figure it out.\n- That exact function that works in Vue, doesn't it work in nuxt?\n- @acdcjunior no it doesn't in Nuxt 2.6.3\n- Did you add the `nuxt.render` to your app variables?\n- @jalil no I did not, what is that and how?\n- No, that won't unpack the Vue components unfortunately.\n- And if you use this one? alligator.io/vuejs/v-runtime-template\n- thanks for this example for me didn't work with 'vue-feather-icons' did you have any idea why?\n- What is exactly you were trying to do? Do you have your code online?\n- Hm need to help with this, this is my no TS version ``` import { h } from '@nuxtjs/composition-api' const VNode = () => h('div', { class: 'test-class', innerHTML: 'html test' }) ``` It gives me this error `VNode is not defined`, but it's definitely defined! Im using **Nuxt v2** with **@nuxtjs/composition-api**","metadata":{"transformedAt":"2026-08-18T18:33:07.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":183,"estimatedTokens":1067}}105{"id":"stack-54605923","source":"stackoverflow","questionId":54605923,"title":"Redirect to previous url after login in nuxt.js","tags":["vue.js","nuxt.js"],"text":"Title: Redirect to previous url after login in nuxt.js\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI basically want to redirect to the previous url when a user has successfully logged in.\n\nI redirect to the login page with the previous url such as `/login?redirect=/page1/page2`.\n\nAnd I want when a user authenticates to be redirected back to that url.\nI am using the `auth-module` here: https://auth.nuxtjs.org/\n\nHow I login the user.\n\n```\nmethods: {\n async submit() {\n await this.$auth.loginWith('local', {\n data: this.form\n })\n }\n}\n```\n\nThe only thing that I could found in the docs is this: https://auth.nuxtjs.org/getting-started/options#redirect\n\nwhich however only redirects to a specific page instead of the previous page in the query.\n\nAny ideas on how to achieve this?\n\n========================================\n\nTop Answer:\nThere is a fairly detailed discussion in github about Nuxt having an issue with a redirect when you are hitting a protected page directly. The redirect goes to the default page redirect rather than the previously hit page. The correct behavior should be to store the `redirect` and then proceed to it after authentication (login) with correct credentials.\n\n3 days ago (Apr 14, 2019), MathiasCiarlo submitted a PR on the `auth-module` repo to fix this. The base reason why the redirect was \"lost\" has to do with the state of the redirect value not being allowed to be set as a cookie in SSR mode. His code impacts the `storage.js` file, in particular the `setCookie()` method. I've included that changed method here just for reference.\n\n```\nsetCookie (key, value, options = {}) {\n if (!this.options.cookie) {\n return\n }\n\n const _key = this.options.cookie.prefix + key\n\n const _options = Object.assign({}, this.options.cookie.options, options)\n\n if (isUnset(value)) {\n Cookies.remove(_key, _options)\n } else {\n\n // Support server set cookies\n if (process.server) {\n this.ctx.res.setHeader('Set-Cookie', [_key + '=' + value])\n } else {\n Cookies.set(_key, value, _options)\n }\n }\n\n return value\n }\n```\n\nI've personally just altered my npm myself, but you could probably fork the repo and use that forked npm for the time being. Or you could wait until the PR is merged into the mainline of the `auth-module` repo.\n\n========================================\n\nCode:\n```text\nmethods: {\n async submit() {\n await this.$auth.loginWith('local', {\n data: this.form\n })\n }\n}\n```\n\n```text\n/login?redirect=/page1/page2\n```\n\n```text\nauth-module\n```\n\n```text\nthis.$router.back()\n```\n\n```text\nsetCookie (key, value, options = {}) {\n if (!this.options.cookie) {\n return\n }\n\n const _key = this.options.cookie.prefix + key\n\n const _options = Object.assign({}, this.options.cookie.options, options)\n\n if (isUnset(value)) {\n Cookies.remove(_key, _options)\n } else {\n\n // Support server set cookies\n if (process.server) {\n this.ctx.res.setHeader('Set-Cookie', [_key + '=' + value])\n } else {\n Cookies.set(_key, value, _options)\n }\n }\n\n return value\n }\n```\n\n```text\nredirect\n```\n\n```text\nauth-module\n```\n\n```text\nstorage.js\n```\n\n```text\nsetCookie()\n```\n\n```text\nauth-module\n```\n\n========================================\n\nComments:\n- what if I wanna keep going to the previous page, not go back. but go forward.\n- If i was on facebook for example first this would make me leave my website.. its not a good answer.","metadata":{"transformedAt":"2026-08-18T18:33:07.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":141,"estimatedTokens":856}}106{"id":"stack-53721468","source":"stackoverflow","questionId":53721468,"title":"Issue with dev-tools style editing in Nuxt.js","tags":["javascript","vue.js","google-chrome-devtools","nuxt.js"],"text":"Title: Issue with dev-tools style editing in Nuxt.js\nTags: javascript, vue.js, google-chrome-devtools, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm working on a Nuxt.js application, and I often need to check styles in my browser's dev-tools, but when I do make a change to the styles in the dev-tools all the styles reset in the browser? Has anyone one else had the same issue? I can't seem to find anything anywhere else about this??\n\n========================================\n\nCode:\n```js\nexport default {\n // ...\n build: {\n loaders: {\n scss: { sourceMap: false },\n },\n },\n // ...\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nsourceMaps\n```\n\n========================================\n\nComments:\n- Sometimes I got the same issue. It's appear when I'm editing complex dom tree with scoped css. It's not happen with firefox devtools.\n- In my case, I was importing a file 2 times\n- Thank you very much, I was close to give up in this issue :)\n- Source maps is an idea that made things so much more complicated than they needed to be...\n- In my case I am using Stylus, so I had to make it `stylus: { sourceMap: false }` Others might run into this depending on their CSS flavor\n- This doesn't seem to work with Nuxt v3. Can you provide guidance on how? (my detailed question is at stackoverflow.com/questions/77474831/…)","metadata":{"transformedAt":"2026-08-18T18:33:07.838Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":39,"estimatedTokens":334}}107{"id":"stack-64974790","source":"stackoverflow","questionId":64974790,"title":"Disable 2xl breakpoint for container class","tags":["nuxt.js","tailwind-css"],"text":"Title: Disable 2xl breakpoint for container class\nTags: nuxt.js, tailwind-css\nSource: Stack Overflow\n\nQuestion:\nTailwind 2.0.1 has a `2xl` breakpoint set to `1536px`. I would like to disable this breakpoint and set the max `container` width to the `xl` breakpoint. According to the docs, I can disable all responsive variants for the `container`, but I just want to disable this single breakpoint. Instead I have tried to disable the `2xl` breakpoint by updating the Tailwind configuration as follows:\n\n```\nmodule.exports = {\n theme: {\n screens: {\n '2xl': '1280px'\n }\n }\n}\n```\n\nThis does not work, nor do I think this would be correct when I only want to target a single class and a single breakpoint.\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n theme: {\n screens: {\n '2xl': '1280px'\n }\n }\n}\n```\n\n```text\n2xl\n```\n\n```text\n1536px\n```\n\n```text\ncontainer\n```\n\n```text\nxl\n```\n\n```text\ncontainer\n```\n\n```text\n2xl\n```\n\n```text\nmodule.exports = {\n theme: {\n container: {\n screens: {\n 'sm': '640px',\n 'md': '768px',\n 'lg': '1024px',\n 'xl': '1280px',\n }\n }\n }\n}\n```\n\n```text\nconst defaultTheme = require('tailwindcss/defaultTheme')\n\nlet containerScreens = Object.assign({}, defaultTheme.screens)\n\n// Delete the 2xl breakpoint from the object\ndelete containerScreens['2xl']\n\nmodule.exports = {\n theme: {\n container: {\n screens: containerScreens\n }\n }\n},\n```\n\n```text\ntheme.container.screens\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.838Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":91,"estimatedTokens":391}}108{"id":"stack-52683062","source":"stackoverflow","questionId":52683062,"title":"Loading og:image from assets in nuxt.config.js","tags":["nuxt.js"],"text":"Title: Loading og:image from assets in nuxt.config.js\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIs there a way to import an image and apply it to the og:image meta tag?\nI have the following nuxt.config.js:\n\n```\nmodule.exports = {\n mode: 'universal',\n\n head: {\n title: 'title name',\n meta: [\n // { hid: 'og:image', property: 'og:image', content: process.env.BASE_URL + ogImage },\n ],\n },\n\n // ...\n};\n```\n\nIn a normal vue project this is done easily by using import:\n\n```\nimport ogImage from '@/path/to/image.png';\n```\n\nHowever, import statements aren't available in nuxt.config.js and using require only results in loading the binary, instead of the asset path.\n\n========================================\n\nTop Answer:\nSave the image in static folder.\n\nCreate a publicRuntimeConfig in nuxt.config.js\n\n\r\n\r\n\n```\npublicRuntimeConfig: { baseURL: process.env.NUXT_BASE_URL }\n```\n\n\r\n\r\n\r\n\nIn the layout file add this:\n\n\r\n\r\n\n```\nhead() {\n return {\n title: 'PAGE TITLE',\n meta: [ { hid: 'og:image', property: 'og:image', content: `${this.$config.baseURL}/logo.png` } ]\n }\n}\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n mode: 'universal',\n\n head: {\n title: 'title name',\n meta: [\n // { hid: 'og:image', property: 'og:image', content: process.env.BASE_URL + ogImage },\n ],\n },\n\n // ...\n};\n```\n\n```text\nimport ogImage from '@/path/to/image.png';\n```\n\n```text\nimport ogImage from '@/path/to/image.png';\n export default {\n head () {\n return {\n meta: [\n { hid: 'og:image', property: 'og:image', content: this.BASE_URL+ ogImage }\n ]\n }\n },\n```\n\n```js\npublicRuntimeConfig: { baseURL: process.env.NUXT_BASE_URL }\n```\n\n```js\nhead() {\n return {\n title: 'PAGE TITLE',\n meta: [ { hid: 'og:image', property: 'og:image', content: `${this.$config.baseURL}/logo.png` } ]\n }\n}\n```\n\n```text\nhead() {\n meta: [\n { charset: 'utf-8' },\n {\n hid: 'og:image',\n property: 'og:image',\n content: '/my_image.jpg',\n },\n],\n}\n```\n\n========================================\n\nComments:\n- Is there any way to enable these loaders, or should i have to wait untill nuxt officially supports it in their docu?\n- @user1213904 what u mean? This loaders enabled, but after nuxt config processed .\n- That if there is a way to enable usage of import statements, considering that they have made it available in nuxt 2.0. Or is the nuxt.config.js too limited by node.js reading it\n- @user1213904 u can use import in nuxt config in nuxt 2.0. But it wont give you path of image, it will give your content of image.\n- Ah ok now it's clear. Ill implement my options in the layout file!\n- Please read Discourage screenshots of code and/or errors\n- `og:image` should not use a relative url.\n- Cannot read properties of undefined (reading '$config') Do you know what is wrong?","metadata":{"transformedAt":"2026-08-18T18:33:07.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":134,"estimatedTokens":704}}109{"id":"stack-61348142","source":"stackoverflow","questionId":61348142,"title":"Navigate to nuxt error page via client side?","tags":["vue.js","axios","nuxt.js","vue-router"],"text":"Title: Navigate to nuxt error page via client side?\nTags: vue.js, axios, nuxt.js, vue-router\nSource: Stack Overflow\n\nQuestion:\nWhen I deploy a universal app with nuxt, I'm noticing client-side $axios requests that throw an exception are merely returning the error code to the console. Is there a way to have nuxt redirect to the error.vue we specify in the layouts folder? I only seem to be able to get to this page by calling the `context.error` method on the server side.\n\ni've been approaching it as below:\n\n```\nasync submit (evt) {\n try {\n const { data } = await this.$axios.get(`some/url`)\n ...\n } catch (e) {\n throw new Error(e) // assume, for the sake of argument, that the error is: { 'statusCode': 403, 'message': 'Forbidden' }\n }\n}\n```\n\n========================================\n\nTop Answer:\nYou should have access to the same error method on the client-side via `$nuxt` utility. Works exactly the same, so you can throw an error for example like this:\n\n`$nuxt.error({ statusCode: 404 })`\n\n========================================\n\nCode:\n```js\nasync submit (evt) {\n try {\n const { data } = await this.$axios.get(`some/url`)\n ...\n } catch (e) {\n throw new Error(e) // assume, for the sake of argument, that the error is: { 'statusCode': 403, 'message': 'Forbidden' }\n }\n}\n```\n\n```text\ncontext.error\n```\n\n```text\nreturn this.$nuxt.error({ statusCode: 404, message: 'err message' })\n```\n\n```text\n<h1>{{ error.statusCode }}</h1>\n<h2>{{ error.message }} </h2>\n```\n\n```text\ncatch\n```\n\n```text\nerror.vue\n```\n\n```text\nerror\n```\n\n```text\n$nuxt\n```\n\n```text\n$nuxt.error({ statusCode: 404 })\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":73,"estimatedTokens":402}}110{"id":"stack-67182172","source":"stackoverflow","questionId":67182172,"title":"Nuxt.js: How to include local images in Markdown blog content?","tags":["vue.js","nuxt.js","markdown"],"text":"Title: Nuxt.js: How to include local images in Markdown blog content?\nTags: vue.js, nuxt.js, markdown\nSource: Stack Overflow\n\nQuestion:\nI created a blog in Nuxt.js which uses Markdown for my articles. When writing my first article, I realized I can't include images in my markdown article from my `assets` folder. It only works if it's a link like the example below:\n\nMarkdown Image:\n\nHow can insert an image in Nuxt.js Markdown from this location? `assets/images/blog/trees.png`\n\n========================================\n\nTop Answer:\nIn your vue files, you can access images in `assets` folder with:\n\n```\n\n \n\n```\n\nIn markdown file, you can do the same with Markdown syntax:\n\n```\n\n```\n\nBut as your files in `content` folder is independent of webpack, you have to run `nuxt generate` each time you add a file in `assets` folder.\n\nMore info here:\nhttps://nuxtjs.org/docs/2.x/directory-structure/assets/\nhttps://github.com/nuxt/content/issues/106\n\n========================================\n\nCode:\n```text\nassets\n```\n\n```text\nassets/images/blog/trees.png\n```\n\n```text\n\n```\n\n```text\n/static\n```\n\n```html\n<template>\n <img src=\"~/assets/your_image.png\" />\n</template>\n```\n\n```markdown\n\n```\n\n```text\nassets\n```\n\n```text\ncontent\n```\n\n```text\nnuxt generate\n```\n\n```text\nassets\n```\n\n```text\nstatic/images/img1.png\n```\n\n```text\n\n```\n\n```text\n<template>\n <img src=\"/images/img1.png\" />\n</template>\n```\n\n```text\n---\ntitle: Title\ndescription: This is description\nimg: /images/img1.png\nalt: Article 1\n---\n\n## Example\n```\n\n```text\n<template>\n <div>\n <div v-for=\"article of articles\" :key=\"article.slug\">\n <h1>{{ article.title }}</h1>\n <img\n v-if=\"article.img\"\n class=\"h-48 xxlmin:w-1/2 xxlmax:w-full object-cover\"\n :src=\"article.img\"\n />\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n async asyncData({ $content, params }) {\n const articles = await $content('articles', params.slug)\n .only(['title', 'description', 'img'])\n .fetch()\n\n return {\n articles,\n }\n },\n}\n</script>\n```\n\n========================================\n\nComments:\n- When you say your blog use markdown. Do you mean using nuxt-content?\n- Yes, using nuxt-content.\n- I tried using `` but it doesn't work.\n- You must reload webpack with `nuxt export`. See my answer.\n- Crazy. Atinux answer this issue, but this is a fast response because you can use assets folder. You just need to run `nuxt export` each time you add an image in it. See here: github.com/nuxt/content/issues/106\n- Placing images in static folder and then including the images like this `` worked! I only needed to include images locally not necessarily from assets folder. Thank you @kissu.\n- I tried using `nuxt export` but still it wont show the image in my article. Its also says `nuxt export` is deprecated.\n- Sorry, it's `nuxt generate` now\n- @ManUtopiK damn, generating a whole new project each time is really time consuming. Good if you know where to go but faster to specify it in the absolute way IMO.\n- How to add classes with this method?","metadata":{"transformedAt":"2026-08-18T18:33:07.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":146,"estimatedTokens":827}}111{"id":"stack-56665934","source":"stackoverflow","questionId":56665934,"title":"Nuxt & Vuetify: how to control the order in which CSS files are loaded?","tags":["css","vue.js","vuetify.js","nuxt.js"],"text":"Title: Nuxt & Vuetify: how to control the order in which CSS files are loaded?\nTags: css, vue.js, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn my `Nuxt/Vuetify` app I'm trying to load my custom CSS *after* `Vuetify`'s CSS, but `Vuetify`'s CSS gets loaded afterwards no matter what. I tried to reverse the order in the CSS array:\n\n```\ncss: [\n '~/assets/style/main.scss',\n '~/assets/style/app.styl'\n ],\n```\n\n... and swap these around, to no avail. \n\nThe popularity of a previous question on this topic combined with its lack of answer makes me think the problem is on `Vuetify`' side and authors didn't bother to fix the issue. \n\nBut maybe that's not the right explanation and there's indeed a solution?\n\n========================================\n\nTop Answer:\nAs noted, this is an ongoing issue with Nuxt. However, you have a few options.\n\n### **Option 1 The dirty but easy way...**\n\nRemove your override CSS from the nuxt.config.js (keep Vuetify)\nthen add your override code a `style` block in your `default` layout.\n\n```\n\n @import assets/style/main.scss\n\n```\n\nThe problem with this approach is you'll have to duplicate it if you add additional layouts.\n\n### **Option #2 The better but possibly more complex way**\n\nCreate an \"all\" css file and import both into it. I say more complex as you may need to compile your stylus into CSS before it can be imported. However, I assume you're not changing the Vuetify styles so that likely won't be an issue.\n\n**all.scss** (make sure to name it .scss so it gets processed)\n\n```\n@import \"app.styl\";\n@import \"main.scss\";\n```\n\nImport all your CSS (in any order you want) to that one CSS file.\n\n**nuxt.config.js**\n\n```\ncss: [\n '~/assets/style/all.scss',\n ],\n```\n\n========================================\n\nCode:\n```text\ncss: [\n '~/assets/style/main.scss',\n '~/assets/style/app.styl'\n ],\n```\n\n```text\nNuxt/Vuetify\n```\n\n```text\nVuetify\n```\n\n```text\nVuetify\n```\n\n```text\nVuetify\n```\n\n```text\n^2.7.1\n```\n\n```text\n<style lang=\"sass\">\n @import assets/style/main.scss\n</style>\n```\n\n```text\n@import \"app.styl\";\n@import \"main.scss\";\n```\n\n```text\ncss: [\n '~/assets/style/all.scss',\n ],\n```\n\n```text\nstyle\n```\n\n```text\ndefault\n```\n\n```text\ncss: [\n // ~/assets/style/app.styl,\n // ~/assets/style/custom.styl,\n],\n```\n\n```text\nimport Vue from 'vue'\nimport Vuetify from 'vuetify/lib'\nimport colors from 'vuetify/es5/util/colors'\n\nimport 'assets/style/app.styl'\nimport 'assets/style/custom.styl'\n\nVue.use(Vuetify)\n```\n\n```text\ncss: [\n 'vuetify/dist/vuetify.min.css',\n '@mdi/font/css/materialdesignicons.css',\n '~/assets/styles/main.scss'\n]\n```\n\n```text\nimport Vue from 'vue'\nimport Vuetify from 'vuetify'\nimport en from 'vuetify/lib/locale/en'\nimport lt from 'vuetify/lib/locale/lt'\nimport pl from 'vuetify/lib/locale/pl'\nimport colors from '~/config/colors'\n\nVue.use(Vuetify)\n\nexport default ({ app }) => {\n app.vuetify = new Vuetify({\n lang: {\n locales: { en, lt, pl },\n current: 'en'\n },\n icons: {\n iconfont: 'mdi'\n },\n theme: {\n options: {\n customProperties: true\n },\n themes: {\n light: colors\n }\n }\n })\n}\n```\n\n```text\nvuetify 2.2.19\n```\n\n```text\nnuxt 2.0.0\n```\n\n```text\n@nuxt/vuetify\n```\n\n```text\nextractCss: true\n```\n\n```text\nnuxt.config.json\n```\n\n```text\n@nuxt/vuetify\n```\n\n```text\n'@nuxtjs/vuetify\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt.config.js:\n\nbuild: {\n postcss: false\n }\n```\n\n========================================\n\nComments:\n- I believe you'd have to edit nuxt.config.js. The technique of importing vuetify css in your custom css, and disabled automatic load of it outside your custom CSS might be a solution as well.\n- But with this way you loose treeshaking feature on css, right ?\n- I guess you will lose the ability to customize your `tailwind.config.js`","metadata":{"transformedAt":"2026-08-18T18:33:07.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":217,"estimatedTokens":952}}112{"id":"stack-54925723","source":"stackoverflow","questionId":54925723,"title":"NuxtServerInit not working on Vuex module mode - Nuxt.js","tags":["vue.js","vuex","nuxt.js","vuex-modules"],"text":"Title: NuxtServerInit not working on Vuex module mode - Nuxt.js\nTags: vue.js, vuex, nuxt.js, vuex-modules\nSource: Stack Overflow\n\nQuestion:\nNuxtServerInit is not working on initial page render on nuxt js vuex module mode. But it works on Classic mode. Following code is the flow I used.\n\nMy api call\n\napi/CategoryApi.js\n\n```\nimport axios from 'axios';\n\nconst HEADERS = {\n Accept: 'application/json'\n};\n\nexport default {\n getCategory(payload) {\n return axios.get(`${process.env.apiUrl}/category`, {\n payload,\n headers: HEADERS\n });\n }\n}\n```\n\nstore/modules/CategoryStore.js\n\n```\nimport api from '~/api/CategoryApi'\n\nconst state = () => ({\n categories: []\n});\n\nconst getters = {\n allCategories: state => state.categories\n};\n\nconst actions = {\n async nuxtServerInit({commit}) {\n const payload = {\n per_page: 6,\n page: 1\n };\n const response = await api.getCategory(payload);\n commit('setCategories', response.data.data);\n },\n};\n\nconst mutations = {\n setCategories: (state, data) => {\n state.categories = data;\n }\n};\n\nexport default {\n state,\n getters,\n actions,\n mutations\n}\n```\n\npages/index.vue\n\n```\n\n \n \n {{ category.name }}\n \n \n\n import { mapGetters } from 'vuex';\n\n export default {\n layout: 'default',\n computed: {\n ...mapGetters({\n allCategories: 'modules/CategoryStore/allCategories',\n })\n },\n }\n\n```\n\nAm I doing this wrong? :/ I want to know the right way to implement this.\n\n**Edit: How I did with Aldarund answer** (This might help someone)\n\nEdited store/modules/CategoryStore.js\n\n```\nconst actions = {\n async fetchCategories({commit}) {\n const payload = {\n per_page: 6,\n page: 1\n };\n const response = await api.getCategory(payload);\n commit('setCategories', response.data.data);\n },\n};\n```\n\nAdded store/index.js\n\n```\nconst actions = {\n async nuxtServerInit({dispatch}) {\n await dispatch('modules/CategoryStore/fetchCategories');\n },\n};\n\nexport default {\n actions\n}\n```\n\n========================================\n\nTop Answer:\ntry use that code, clear file index.js, and run.. on server console you see message.\n\n```\nexport const actions = {\n\n nuxtServerInit ({ dispatch }) {\n console.log(\"troololollo\")\n }\n}\n```\n\nmaybe also can try nuxt.config.js\n\n```\nmodule.exports = {\n //mode: 'spa',\n mode: 'universal',\n```\n\n========================================\n\nCode:\n```text\nimport axios from 'axios';\n\nconst HEADERS = {\n Accept: 'application/json'\n};\n\nexport default {\n getCategory(payload) {\n return axios.get(`${process.env.apiUrl}/category`, {\n payload,\n headers: HEADERS\n });\n }\n}\n```\n\n```text\nimport api from '~/api/CategoryApi'\n\nconst state = () => ({\n categories: []\n});\n\nconst getters = {\n allCategories: state => state.categories\n};\n\nconst actions = {\n async nuxtServerInit({commit}) {\n const payload = {\n per_page: 6,\n page: 1\n };\n const response = await api.getCategory(payload);\n commit('setCategories', response.data.data);\n },\n};\n\nconst mutations = {\n setCategories: (state, data) => {\n state.categories = data;\n }\n};\n\nexport default {\n state,\n getters,\n actions,\n mutations\n}\n```\n\n```text\n<template>\n <div>\n <v-flex xs6 sm4 md2 class=\"text-xs-center my-2 pa-2\" v-for=\"category in allCategories\" :key=\"category.id\">\n {{ category.name }}\n </v-flex>\n </div>\n</template>\n\n<script>\n import { mapGetters } from 'vuex';\n\n export default {\n layout: 'default',\n computed: {\n ...mapGetters({\n allCategories: 'modules/CategoryStore/allCategories',\n })\n },\n }\n</script>\n```\n\n```text\nconst actions = {\n async fetchCategories({commit}) {\n const payload = {\n per_page: 6,\n page: 1\n };\n const response = await api.getCategory(payload);\n commit('setCategories', response.data.data);\n },\n};\n```\n\n```text\nconst actions = {\n async nuxtServerInit({dispatch}) {\n await dispatch('modules/CategoryStore/fetchCategories');\n },\n};\n\nexport default {\n actions\n}\n```\n\n```text\nexport const actions = {\n\n nuxtServerInit ({ dispatch }) {\n console.log(\"troololollo\")\n }\n}\n```\n\n```text\nmodule.exports = {\n //mode: 'spa',\n mode: 'universal',\n```\n\n```js\nnuxtServerInit(vuexContext, {req, redirect, params})\n {\n vuexContext.dispatch('someAction',someArguments)\n }\n```\n\n```js\nnuxtServerInit({dispatch})\n {\n dispatch('someAction',someArguments)\n }\n```\n\n```text\nexport const actions = {\n // This isn't called unless it is \"chained\"\n nuxtServerInit(vuexContext, context) {\n return new Promise((resolve, reject) => {\n // do a thing\n resolve()\n })\n },\n}\n```\n\n```text\nimport { actions as postActions } from './posts' ;\n\nexport const actions = {\n nuxtServerInit(vuexContext, context) {\n return new Promise(async (resolve, reject) => {\n // \"chain\" the desired method\n await postActions.nuxtServerInit(vuexContext, context)\n resolve();\n })\n }\n}\n```\n\n```js\nstore/modules/user.js\nstore/modules/todo.js\nstore/index.js\n```\n\n```js\nstore/user.js\nstore/todo.js\nstore/index.js\n```\n\n```js\n'/store/index.js'\nimport todos from './todos'\n\nconst state = () => ({})\nconst getters = {}\nconst mutations = {}\n\nconst actions = {\n async nuxtServerInit(vuexContext, context) {\n await Promise.all([\n todos.actions.nuxtServerInit(vuexContext, context)\n ])\n },\n}\n\nexport default {\n state,\n getters,\n mutations,\n actions,\n}\n```\n\n```js\n'/store/todos.js'\n\n...\n\nconst actions = {\n async nuxtServerInit(vuexContext, context) {\n return await vuexContext.commit('todos/setTodos', todos)\n },\n}\n\n...\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nstore/index.js\n```\n\n```text\nindex.js\n```\n\n```text\nindex.js\n```\n\n```text\nnuxtServerInit\n```\n\n```text\ntodos.nuxtServerInit\n```\n\n```text\nstore/index.js\n```\n\n```text\nstore/todos.js\n```\n\n```text\nvuexContext.commit('todos/setTodos', todos)\n```\n\n```text\nvuexContext.commit('setTodos', todos)\n```\n\n```text\nthis.$store.getters\n```\n\n```text\nthis.$store.getters['todos/todos']\n```\n\n```text\nexport default {\n state: () => ({\n context: undefined\n }),\n\n actions: {\n nuxtServerInit ({ state }, ctx) {\n state.context = () => ctx;\n }\n }\n};\n```\n\n```text\nrootState.context().<some object hanging off of the context>\n```\n\n========================================\n\nComments:\n- Can you please give an example of how to do that.\n- @Ninja it is in docs and in examples. github.com/nuxt/nuxt.js/blob/…\n- Yes but my Vuex is in Module mode. So Kind of confused.\n- @Ninja the example i linked in module mode too\n- @Aldarund Not sure if your example changed, but it does not appear to be in module mode?\n- `mode: spa` won't make the nuxtServerInit call. I learned this the hard way. Thank you for this comment.\n- hey Andre, when you just want to indicate that it's code, you can use the \"pre-code\" formatting ({} icon) instead of the executable snippet formatting (<> icon).\n- About your new Promise with async and await. It's actually not recommended by ESLint. eslint.org/docs/rules/no-async-promise-executor","metadata":{"transformedAt":"2026-08-18T18:33:07.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":430,"estimatedTokens":1779}}113{"id":"stack-53500137","source":"stackoverflow","questionId":53500137,"title":"Nuxt.js and handle API 404 response for dynamic pages","tags":["vue.js","nuxt.js"],"text":"Title: Nuxt.js and handle API 404 response for dynamic pages\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI use Nuxt.js and I have dynamic page `/items/{id}`:\n\n```\n\n \n \n\n### Item #{{ item.id }} «{{ item.title }}»\n\n \n\nimport { api } from '../../mo/api'\n\nexport default {\n asyncData({ params }) {\n return api(`items/${params.id}`)\n },\n}\n\n```\n\nBackend API returns object {item: {id: .., title: \"...\", ...}}.\nBut if an item with specified ID not exist API returns 404 response.\nAnd Vue crash with \"[Vue warn]: Property or method \"item\" is not defined on the instance but referenced during render.\"\n\nHow can I handle 404 response?\n\nMy `api.js` module:\n\n```\nimport axios from 'axios'\n\nexport function api(url) {\n url = encodeURIComponent(url)\n return axios\n .get(`http://localhost:4444/?url=${url}`)\n .then(({ data }) => {\n return data\n })\n .catch((err) => {\n // 404 catch there\n })\n}\n```\n\n**Solution:**\n\nNeed to read manual: https://nuxtjs.org/guide/async-data/#handling-errors\n\n========================================\n\nTop Answer:\nIf you're using the `fetch()` hook, this is how it should be written\n\n```\n\nexport default {\n async fetch() {\n try {\n await fetch('https://non-existent-website.commmm')\n .then((response) => response.json())\n } catch (error) {\n this.$nuxt.context.error({\n status: 500,\n message: 'Something bad happened',\n })\n }\n },\n}\n\n```\n\nMore context available here: https://nuxtjs.org/announcements/understanding-how-fetch-works-in-nuxt-2-12/#error-handling\n\n========================================\n\nCode:\n```html\n<template>\n <div>\n <h1>Item #{{ item.id }} «{{ item.title }}»</h1>\n </div>\n</template>\n\n<script>\nimport { api } from '../../mo/api'\n\nexport default {\n asyncData({ params }) {\n return api(`items/${params.id}`)\n },\n}\n</script>\n```\n\n```js\nimport axios from 'axios'\n\nexport function api(url) {\n url = encodeURIComponent(url)\n return axios\n .get(`http://localhost:4444/?url=${url}`)\n .then(({ data }) => {\n return data\n })\n .catch((err) => {\n // 404 catch there\n })\n}\n```\n\n```text\n/items/{id}\n```\n\n```text\napi.js\n```\n\n```html\n<script>\nexport default {\n asyncData({ params, error }) {\n return axios\n .get(`https://my-api/posts/${params.id}`)\n .then((res) => {\n return { title: res.data.title }\n })\n .catch((e) => {\n error({ statusCode: 404, message: 'Post not found' })\n })\n },\n}\n</script>\n```\n\n```html\n<script>\nexport default {\n async fetch() {\n try {\n await fetch('https://non-existent-website.commmm')\n .then((response) => response.json())\n } catch (error) {\n this.$nuxt.context.error({\n status: 500,\n message: 'Something bad happened',\n })\n }\n },\n}\n</script>\n```\n\n```text\nfetch()\n```\n\n========================================\n\nComments:\n- Initialize `item` with `null` or `undefined` and use `v-if` / `v-else`.\n- can I use standard 404 page from my project instead use v-if for all these situations?\n- yes. and didn't it work! but as usual now it work :)) thank you!\n- Glad I could help. Please make sure to add the solution to your question or post it as an answer so that other people can benefit from it.","metadata":{"transformedAt":"2026-08-18T18:33:07.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":170,"estimatedTokens":799}}114{"id":"stack-74485982","source":"stackoverflow","questionId":74485982,"title":"Favicon loading from assets is not working in nuxt3","tags":["nuxt.js","nuxt3.js"],"text":"Title: Favicon loading from assets is not working in nuxt3\nTags: nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to load favicon from assets in nuxt 3 but it does not work except if I hardcode _nuxt in front of it. My config looks like this and this works:\n\n```\nexport default defineNuxtConfig({\n app: {\n head: {\n link: [{ rel: 'icon', type: 'image/png', href: '_nuxt/assets/favicon.png' }]\n }\n },\n```\n\nBut according to documentation it should be something like this:\n\n```\n~assets/favicon.png\n```\n\nor\n\n```\n~/assets/favicon.png\n```\n\nbut both don't work.\n\nAny way to do it as documented or is this a bug?\n\nAddOn Info: If using the links in a vue component it works and the favicon loads correctly if I show it on the page.\n\n========================================\n\nTop Answer:\nYou can fix it with static folder settings.\n\n```\nexport default {\n static: {\n prefix: false\n }\n}\n```\n\nor\n\n```\nexport default {\n build: {\n publicPath: 'https://cdn.nuxtjs.org'\n }\n}\n```\n\nhttps://nuxtjs.org/docs/directory-structure/static/\n\n========================================\n\nCode:\n```js\nexport default defineNuxtConfig({\n app: {\n head: {\n link: [{ rel: 'icon', type: 'image/png', href: '_nuxt/assets/favicon.png' }]\n }\n },\n```\n\n```js\n~assets/favicon.png\n```\n\n```js\n~/assets/favicon.png\n```\n\n```text\nexport default defineNuxtConfig({\n app: {\n buildAssetsDir: '/something/',\n head: {\n htmlAttrs: { dir: 'rtl', lang: 'fa' },\n link: [{ rel: 'icon', type: 'image/png', href: \"/something/assets/images/logo.png\" }]\n },\n },\n})\n```\n\n```text\nexport default defineNuxtConfig({\n app: {\n head: {\n link: [{ rel: 'icon', type: 'image/png', href: '/favicon.png' }]\n }\n },\n```\n\n```text\n_nuxt\n```\n\n```text\n_nuxt\n```\n\n```text\nexport default {\n static: {\n prefix: false\n }\n}\n```\n\n```text\nexport default {\n build: {\n publicPath: 'https://cdn.nuxtjs.org'\n }\n}\n```\n\n========================================\n\nComments:\n- using the static folder works but the folder settings you describe using \"static\" and \"prefix\" is not available in Nuxt3. But that means that assets-folder cannot be used in the nuxt.config.ts !?\n- Actually I was wrong. static folder does not work. public folder works.\n- Made an error testing this. It does not work! It is serving from public folder. Not static.\n- This works. Both solutions. The first does not remove all occurrences of nuxt word but at least I can load from assets folder if I want.\n- Actually the assets solution only runs with the dev server. If I npm run build and npm run preview it does not server the favicon anymore from assets. But the second solution works in nuxt3 also in production.\n- \"Why do you need a module bundler to process your favicon?\" Because my source svg file usually contains additional layers and meta information that I do not want to publish.","metadata":{"transformedAt":"2026-08-18T18:33:07.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":133,"estimatedTokens":732}}115{"id":"stack-57074134","source":"stackoverflow","questionId":57074134,"title":"Understanding State and Getters in Nuxt.js: Getters won't working","tags":["vue.js","vuex","nuxt.js"],"text":"Title: Understanding State and Getters in Nuxt.js: Getters won't working\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\ni'm new to Vue and Nuxt and i'm building my first website in Universal mode with these framework. \n\nI'm a bit confused on how the store works in nuxt, since following the official documentation i can't achieve what i have in mind.\n\nIn my store folder i have placed for now only one file called \"products.js\", in there i export the state like this:\n\n```\nexport const state = () => ({\n\n mistica: {\n id: 1,\n name: 'mistica'\n }\n})\n```\n\n(The object is simplified in order to provide a cleaner explanation)\n\nIn the same file i set up a simple getter, for example:\n\n```\nexport const getters = () => ({\n\n getName: (state) => {\n return state.mistica.name\n }\n})\n```\n\nNow, according to the documentation, in the component i set up like this:\n\n```\ncomputed: {\n getName () {\n return this.$store.getters['products/getName']\n }\n}\n```\n\nor either (don't know what to use):\n\n```\ncomputed: {\n getName () {\n return this.$store.getters.products.getName\n }\n}\n```\n\nbut when using \"getName\" in template is \"undefined\", in the latter case the app is broken and it says \"Cannot read property 'getName' of undefined\"\n\nNote that in the template i can access directly the state value with \"$store.state.products.mistica.name\" with no problems, why so?\n\nWhat am i doing wrong, or better, what didn't i understand?\n\n========================================\n\nTop Answer:\nCouple of things. In your \"store\" folder you might need an index.js for nuxt to set a root module. This is the only module you can use `nuxtServerInit` in also and that can be very handy.\n\nIn your products.js you are part of the way there. Your state should be exported as a function but actions, mutations and getters are just objects. So change your getters to this: \n\n```\nexport const getters = {\n getName: state => {\n return state.mistica.name\n }\n}\n```\n\nThen your second computed should get the getter. I usually prefer to use \"mapGetters\" which you can implement in a page/component like this:\n\n```\n\nimport { mapGetters } from 'vuex'\nexport default {\n computed: {\n ...mapGetters({\n getName: 'products/getName'\n })\n}\n\n```\n\nThen you can use getName in your template with `{{ getName }}` or in your script with `this.getName`.\n\n========================================\n\nCode:\n```text\nexport const state = () => ({\n\n mistica: {\n id: 1,\n name: 'mistica'\n }\n})\n```\n\n```text\nexport const getters = () => ({\n\n getName: (state) => {\n return state.mistica.name\n }\n})\n```\n\n```text\ncomputed: {\n getName () {\n return this.$store.getters['products/getName']\n }\n}\n```\n\n```text\ncomputed: {\n getName () {\n return this.$store.getters.products.getName\n }\n}\n```\n\n```js\nexport const getters = {\n getName: (state) => {\n return state.mistica.name\n }\n}\n```\n\n```js\nimport { mapGetters } from \"vuex\";\n\n...\n\ncomputed: {\n ...mapGetters(\"products\", [\n \"getName\",\n // Here you can import other getters from the products.js\n ])\n}\n```\n\n```text\nstate\n```\n\n```text\ngetters\n```\n\n```text\ngetters\n```\n\n```text\nthis.$store.getters['products/getName']\n```\n\n```text\nthis.$store.getters.products.getName\n```\n\n```text\nmapGetters\n```\n\n```text\nvuex\n```\n\n```text\nexport const getters = {\n getName: state => {\n return state.mistica.name\n }\n}\n```\n\n```text\n<script>\nimport { mapGetters } from 'vuex'\nexport default {\n computed: {\n ...mapGetters({\n getName: 'products/getName'\n })\n}\n</script>\n```\n\n```text\nnuxtServerInit\n```\n\n```text\n{{ getName }}\n```\n\n```text\nthis.getName\n```\n\n========================================\n\nComments:\n- why or how are `export const state / getters` functions ? haven't seen this on vuex.vuejs.org - is this nuxt stuff ?\n- @birdspider for the state is correct, but as pointed by the guys here for the getters exporting a function is incorrect because getters, actions and mutations are objects. Nuxt has vuex integrated and it uses modules and namespacing by default\n- Thank you very much. That makes sense but i didn't even think about it, just copied the syntax without wondering what i was actually doing.\n- Another question: For what reason i can access the state with the syntax $store.state.products.mistica.name?\n- This is because the state of store modules are merged into the root state object under the keys associated with the names of the modules. However the getters of store modules are prefixed and merged into a single plain array. I'm not really sure why it works this way.\n- Thanks a million. Accessing the getters for me using `this.$store.getters.products.getName` seemed cumbersome but the above syntax works\n- @NinaLisitsinskaya Thanks for the answer, but if we have another file in store (like `user.js`) and want to use getters of both `product.js` and `user.js`, what would be the syntax with the help of `...mapGetters`?","metadata":{"transformedAt":"2026-08-18T18:33:07.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":220,"estimatedTokens":1218}}116{"id":"stack-49144599","source":"stackoverflow","questionId":49144599,"title":"Using webpack worker-loader with nuxt.js","tags":["webpack","nuxt.js"],"text":"Title: Using webpack worker-loader with nuxt.js\nTags: webpack, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use Web Worker within the nuxt.js framework but keep getting a reference error. `ReferenceError: Worker is not defined`.\n\nI have installed worker-loader 1.1.1 via npm and added the following rule to my `nuxt.config.js`:\n\n```\nmodule.exports = {\n build: {\n extend (config, { isDev, isClient }) {\n if (isDev && isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n // Web Worker support\n config.module.rules.push({\n test: /\\.worker\\.js$/,\n use: { loader: 'worker-loader' },\n exclude: /(node_modules)/\n })\n }\n }\n}\n```\n\nIf I create a build via `nuxt build` it looks like the web worker file is created.\n\n```\nAsset Size \n2a202b9d805e69831a05.worker.js 632 bytes [emitted]\n```\n\nI import it inside a vuex module, like so:\n\n```\nimport Worker from '~/assets/js/shared/Loader.worker.js'\n\nconsole.log(Worker)\nconst worker = new Worker // In the console I get what looks like a function to create the worker:\n\n```\nƒ () {\n return new Worker(__webpack_require__.p + \"345c16d02e75e9312f73.worker.js\");\n}\n```\n\nInside the worker, I just have some dummy code to see if it actually works:\n\n```\nconst msg = 'world!'\n\nself.addEventListener('message', event => {\n console.log(event.data)\n self.postMessage({ hello: msg })\n})\n\nself.postMessage({ hello: 'from web worker' })\n```\n\n========================================\n\nTop Answer:\nWith worker-loader, there's the fallback option but personally (and this is what I'm doing) I would keep only the communication code inside the immediate worker file, importing a second file with the actual workload. This way the second file can also be imported serverside.\nMost likely in a forked thread/threadpool, unless you are in a FaaS context and your main thread has literally nothing else to do.\n\nAlso, did you have to use the following in `nuxt.config.js`? For me, without it, it was \"window is undefined\". (in the browser, when trying to instantiate worker)\n\n```\nextend(config, ctx) {\n /*\n ** Required for HotModuleReloading to work with worker-loader\n */\n config.output.globalObject = 'this'\n}\n```\n\n========================================\n\nCode:\n```js\nmodule.exports = {\n build: {\n extend (config, { isDev, isClient }) {\n if (isDev && isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n // Web Worker support\n config.module.rules.push({\n test: /\\.worker\\.js$/,\n use: { loader: 'worker-loader' },\n exclude: /(node_modules)/\n })\n }\n }\n}\n```\n\n```text\nAsset Size \n2a202b9d805e69831a05.worker.js 632 bytes [emitted]\n```\n\n```js\nimport Worker from '~/assets/js/shared/Loader.worker.js'\n\nconsole.log(Worker)\nconst worker = new Worker // <- this line fails!\n```\n\n```js\nƒ () {\n return new Worker(__webpack_require__.p + \"345c16d02e75e9312f73.worker.js\");\n}\n```\n\n```js\nconst msg = 'world!'\n\nself.addEventListener('message', event => {\n console.log(event.data)\n self.postMessage({ hello: msg })\n})\n\nself.postMessage({ hello: 'from web worker' })\n```\n\n```text\nReferenceError: Worker is not defined\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt build\n```\n\n```text\nmode: 'spa',\nbuild: {\n extend(config, { isDev, isClient }) {\n ...\n // Web Worker support\n if (isClient) {\n config.module.rules.push({\n test: /\\.worker\\.js$/,\n use: { loader: 'worker-loader' },\n exclude: /(node_modules)/\n })\n }\n }\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run start\n```\n\n```js\nextend(config, ctx) {\n /*\n ** Required for HotModuleReloading to work with worker-loader\n */\n config.output.globalObject = 'this'\n}\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- I've also tried to use workerize-loader but are getting a different error. I'm sure it has to do with my configuration but I still don't know what to do. github.com/developit/workerize-loader/issues/27\n- shouldn't it be `new Worker()`?\n- @lukas-reineke if you don't send arguments to a constructor in JS then the parentheses are optional. stackoverflow.com/a/3034952/205696 Anyway, I tried both (and many other things) and it all failed.\n- try to import this way **import * as Worker from \"worker-loader!~/assets/js/shared/Loader.worker.js'\";** this type of import and and then create a instance.\n- Finally - Thanks @Greaka! Only now, that I understand why, I got another issue. How do I build a normal SSR capable version of nuxt with a client-side only web worker? My main issue for not using `` is that the web worker is used inside a vuex module, to do pre-fetching.\n- Seems that I can implement it as a plugin - but not sure how to use the plugin in vuex code... github.com/nuxt/nuxt.js/issues/1607#issuecomment-328489139\n- OK. It works in a plugin with ssr set to false. `{ src: '~/plugins/load-ww', ssr: false }` but the vuex files a run before the plugins so I can not make the web worker accessible from to a store file via `Vue.use()`.\n- With the latest source for nuxt, dev modes works fine with worker-loader. I just did a git clone and it works\n- I just rushed here because it struck my mind. Webworkers do get registered in Dev mode, i will update my answer accordingly.\n- You cannot use workers server side. if you just want to prefatch data, use asyncdata. Another option is to write your own loader which you call if `!isClient`. The loader could for example change the path to e.g. instead of `*.worker.js` -> `*.js`. Downside: you have to write the same code multiple times. workaround: import the non worker script in the worker and just call the functions. the webworker will be just a wrapper for offloading it in the client.\n- I figured out to put the web worker instantiation in a `ssr: false` plugin and inject it into nuxt. Then I can use it in a `if (process.browser)` guard in vuex actions. I'm preloading thousands of SVG and images for a viewer. IMHO it's better to use browser caching than anything else for that. I just need vuex to keep track of what I preload. It largely depends on the user navigation in the app, what prefetch strategy I use.\n- I played around with it and ended with an example PR: github.com/nuxt/nuxt.js/pull/3044\n- @dotnetCarpenter thanks for demo, but it seems it doesn't work in hot reloading mode in nuxt-edge\n- @husayt Looks like you answered the question yourself in github.com/nuxt/nuxt.js/pull/3480#issuecomment-404150387\n- Indeed @dotnetCarpenter. Thanks for all the changes\n- This was due to a comment by @husayt github.com/nuxt/nuxt.js/pull/3480#issuecomment-404150387. However in 1.4.0, it doesn't seem to work anyway. So I removed it and in nuxt page I get the reference through `async fetch({app}) { app.$worker` and in a store I can still use `this.$worker`. Sorry for the bad formatting, but SO peeps think it's great(!) - meta.stackexchange.com/questions/216927/…","metadata":{"transformedAt":"2026-08-18T18:33:07.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":211,"estimatedTokens":1796}}117{"id":"stack-60278515","source":"stackoverflow","questionId":60278515,"title":"How to import css file from assets folder in nuxt.js","tags":["css","vue.js","nuxt.js"],"text":"Title: How to import css file from assets folder in nuxt.js\nTags: css, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\n```\n\n \n \n \n \n \n \n\n```\n\nImporting css like above results in this error\n\n```\nvue.runtime.esm.js:5717 GET http://localhost:3000/~assets/css/login-light.css net::ERR_ABORTED 404 (Not Found)\n```\n\nIs there really no other way loading css other than putting the whole css in the template?\n\n========================================\n\nTop Answer:\ntry to import your CSS files in script like this :\n\n```\n\nimport \"@/assets/css/style-light.css\";\nimport \"@/assets/css/login-light.css\";\n\n/// \n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div class=\"container\">\n <head>\n <link rel=\"stylesheet\" href=\"~assets/css/style-light.css\" />\n <link rel=\"stylesheet\" href=\"~assets/css/login-light.css\" />\n </head>\n </div>\n</template>\n```\n\n```text\nvue.runtime.esm.js:5717 GET http://localhost:3000/~assets/css/login-light.css net::ERR_ABORTED 404 (Not Found)\n```\n\n```js\n...\nhead: {\n css: [\n '~/assets/style/app.styl',\n '~/assets/style/main.css'\n ],\n}\n...\n```\n\n```js\nexport default defineNuxtConfig({\n...\n css: [`assets/styles/main.scss`],\n...\n})\n```\n\n```bash\nnpm i D sass sass-loader\n```\n\n```html\n<style lang=\"scss\" scoped>\n@import \"./myCustomCss.css\";\n</style>\n OR\n<style scoped src=\"./myCustomCss.css\">\n</style>\n```\n\n```js\n<script>\nimport \"@/assets/css/style-light.css\";\nimport \"@/assets/css/login-light.css\";\n\n/// \n\n</script>\n```\n\n```text\nhead () {\nreturn {\n link: [\n { rel: 'stylesheet', href: '/style-light.css' },\n { rel: 'stylesheet', href: '/login-light.css' }\n ]\n}\n```\n\n========================================\n\nComments:\n- You can only have one `head` element per page. It cannot reside in the `body`. Aside from that, it would maybe work, but the CSS does not exist at that specified path.\n- now i got this Cannot find module '~assets/css/style-light.css'\n- Use @/ instead of ~\n- I got this instead Error: Can't resolve 'normalize.css'\n- sure you can @HenriqueVanKlaveren , take a look at this codesandbox.io/s/…\n- Using the head() function right now in Nuxt is causing weird failures for me right now on certain pages, so I'm using this method instead since it's working 100% of the time. Thank you for the tip.\n- when should I use static and when should i use assets?\n- I think that the css files that you put into the assets folder are going to be compiled by webpack, so if you're using any pre-processor, this will be transformed into plain old css. Using the static folder webpack doesn't touch anything in this foler.\n- which one do you suggest if I have a bunch of pure css files that needs to be loaded in specific pages?\n- I suppose it really depends how many a 'bunch' is. Are these files already minified etc.. It also depends on which files will be loaded on certain pages. If it's not an enormous amount of code and it's already minified I don't think you should have a problem putting them into the static file.\n- You should probably look at Henriques solution, honestly I think thats a better way of doing it!\n- This the only method I've found that works if you want to include CSS that can't be scoped (for example, because it applies to something outside your page component, like the ) to a single page without it following you as you switch pages.\n- @import '~/assets/style/main.css';\n- interesting, can you try this for us?\n- another thing, do you have a css loader installed? here i have this 2 packages installed: \"stylus\": \"^0.54.7\" and \"stylus-loader\": \"^3.0.2\".","metadata":{"transformedAt":"2026-08-18T18:33:07.839Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":126,"estimatedTokens":892}}118{"id":"stack-51358922","source":"stackoverflow","questionId":51358922,"title":"Load component dynamically based on url parameters in nuxt","tags":["vue.js","vue-component","nuxt.js"],"text":"Title: Load component dynamically based on url parameters in nuxt\nTags: vue.js, vue-component, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a page in nuxt that is divided in two parts. The first part is a normal template structure filled with dynamic content based on the url param. The second part is a component that should be loaded based on this data. I am trying to accomplish it like this:\n\n```\n\n \n \n\n### {{myData.header}}\n\n {{myData.text}}\n\n \n \n\nexport default {\n components: {\n 'my-component': () => import('@/components' + this.myData.component)\n },\n async asyncData(context) {\n return {\n myData: context.params.myData\n }\n }\n}\n\n```\n\nBut this is not working. Is there a way to accomplish this? \n\nI am familiar with the possibility to use ``. However, this requires me to import every component explicitly and I would like to avoid this.\n\n========================================\n\nTop Answer:\nBased on Imre_G's answer, it can be simplified like this:\n\n```\n\n \n \n\n### Hi\n\n Hello World!\n\n \n \n\nexport default {\n computed: {\n component() {\n return () =>\n import(`../../__relative_path__/${this.$route.params.yourParam}`)\n }\n }\n}\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div>\n <h1>{{myData.header}}</h1>\n <p>{{myData.text}}</p>\n <my-component></my-component>\n </div>\n</template>\n\n<script>\nexport default {\n components: {\n 'my-component': () => import('@/components' + this.myData.component)\n },\n async asyncData(context) {\n return {\n myData: context.params.myData\n }\n }\n}\n</script>\n```\n\n```text\n<my-component :is=\"myData.component\"></my-component>\n```\n\n```text\n<template>\n<div>\n <h1>{{myData.header}}</h1>\n <p>{{myData.text}}</p>\n <component :is=\"componentInstance\"></component>\n</div>\n</template>\n\n<script>\nexport default {\n computed: {\n componentInstance () {\n const name = this.myData.component\n return () => import(`./components/${name}`)\n }\n },\n async asyncData(context) {\n return {\n myData: context.params.myData\n }\n }\n}\n</script>\n```\n\n```text\n<template>\n <div>\n <h1>Hi</h1>\n <p>Hello World!</p>\n <Component :is=\"component\"></Component>\n </div>\n</template>\n\n<script>\nexport default {\n computed: {\n component() {\n return () =>\n import(`../../__relative_path__/${this.$route.params.yourParam}`)\n }\n }\n}\n</script>\n```\n\n```text\n<template>\n <my-component></my-component>\n</template>\n\n<script>\n data() {\n return {...}\n },\n mounted() {\n if (process.browser) {\n const component = require(\"~/assets/libs/component\");\n Vue.use(\"my-component\", component); // or just Vue.use(component);\n }\n }\n</script>\n```\n\n========================================\n\nComments:\n- It is working great for one condition but when I want to render components based on conditions, I am getting some issue, stackoverflow.com/questions/72176906/…","metadata":{"transformedAt":"2026-08-18T18:33:07.839Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":163,"estimatedTokens":729}}119{"id":"stack-58940834","source":"stackoverflow","questionId":58940834,"title":"Deploying Nuxt with Docker, env variables not registering and unexpect API call?","tags":["node.js","docker","docker-compose","axios","nuxt.js"],"text":"Title: Deploying Nuxt with Docker, env variables not registering and unexpect API call?\nTags: node.js, docker, docker-compose, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am re-re-re-reading the docs on environment variables and am a bit confused.\n\nMWE repo: https://gitlab.com/SumNeuron/docker-nf\n\nI made a plugin /plugins/axios.js which creates a custom axios instance:\n\n```\nimport axios from 'axios'\n\nconst apiVersion = 'v0'\nconst api = axios.create({\n baseURL: `${process.env.PUBLIC_API_URL}/api/${apiVersion}/`\n})\n\nexport default api\n```\n\nand accordingly added it to nuxt.config.js\n\n```\nimport colors from 'vuetify/es5/util/colors'\n\nimport bodyParser from 'body-parser'\nimport session from 'express-session'\nconsole.log(process.env.PUBLIC_API_URL)\nexport default {\n mode: 'spa',\n env: {\n PUBLIC_API_URL: process.env.PUBLIC_API_URL || 'http://localhost:6091'\n },\n // ...\n plugins: [\n //...\n '@/plugins/axios.js'\n ]\n}\n```\n\nI set `PUBLIC_API_URL` to `http://localhost:9061` in the `.env` file. Oddly, the log statement is correct (port `9061`) but when trying to reach the site there is an api call to port `6091` (the fallback)\n\n### System setup\n\n```\nproject/\n|-- backend (flask api)\n|-- frontend (npx create-nuxt-app frontend)\n |-- assets/\n |-- ...\n |-- plugins/\n |-- axios.js\n |-- restriced_pages\n |-- index.js (see other notes 3)\n |-- ...\n |-- nuxt.config.js\n |-- Dockerfile\n\n|-- .env\n|-- docker-compose.yml\n```\n\n### Docker\n\n### docker-compose.yml\n\n```\nversion: '3'\n\nservices:\n nuxt: # frontend\n image: frontend\n container_name: my_nuxt\n build:\n context: .\n dockerfile: ./frontend/Dockerfile\n restart: always\n ports:\n - \"3000:3000\"\n command: \"npm run start\"\n environment:\n - HOST\n - PUBLIC_API_URL\n\n flask: # backend\n image: backend\n container_name: my_flask\n build:\n context: .\n dockerfile: ./backend/Dockerfile\n command: bash deploy.sh\n\n environment:\n - REDIS_URL\n - PYTHONPATH\n ports:\n - \"9061:9061\"\n expose:\n - '9061'\n depends_on:\n - redis\n\n worker:\n image: backend\n container_name: my_worker\n command: python3 manage.py runworker\n depends_on:\n - redis\n environment:\n - REDIS_URL\n - PYTHONPATH\n\n redis: # for workers\n container_name: my_redis\n image: redis:5.0.3-alpine\n expose:\n - '6379'\n```\n\n### Dockerfile\n\n```\nFROM node:10.15\n\nENV APP_ROOT /src\n\nRUN mkdir ${APP_ROOT}\nWORKDIR ${APP_ROOT}\n\nCOPY ./frontend ${APP_ROOT}\n\nRUN npm install\n\nRUN npm run build\n```\n\n### Other notes:\n\nThe reason the site fails to load is because the new axios plugin (`@/plugins/axios.js`) makes a weird call xhr call when the page is loaded, triggered by `commons.app.js` line 464. I do not know why, this call is no where explicitly in my code.\n\nI see this warning: \n\n WARN Warning: connect.session() MemoryStore is not designed for a production environment, as it will leak memory, and will not scale past a single process.\n\nI do not know what caused it or how to correct it\n\n- I have a \"restricted\" page:\n\n```\n// Create express router\nconst router = express.Router()\n\n// Transform req & res to have the same API as express\n// So we can use res.status() & res.json()\nconst app = express()\nrouter.use((req, res, next) => {\n Object.setPrototypeOf(req, app.request)\n Object.setPrototypeOf(res, app.response)\n req.res = res\n res.req = req\n next()\n})\n\n// Add POST - /api/login\nrouter.post('/login', (req, res) => {\n\n if (req.body.username === username && req.body.password === password) {\n req.session.authUser = { username }\n return res.json({ username })\n }\n res.status(401).json({ message: 'Bad credentials' })\n})\n\n// Add POST - /api/logout\nrouter.post('/logout', (req, res) => {\n delete req.session.authUser\n res.json({ ok: true })\n})\n\n// Export the server middleware\nexport default {\n path: '/restricted_pages',\n handler: router\n\n}\n```\n\nwhich is configured in `nuxt.config.js` as\n\n```\nserverMiddleware: [\n // body-parser middleware\n bodyParser.json(),\n // session middleware\n session({\n secret: 'super-secret-key',\n resave: false,\n saveUninitialized: false,\n cookie: { maxAge: 60000 }\n }),\n // Api middleware\n // We add /restricted_pages/login & /restricted_pages/logout routes\n '@/restricted_pages'\n ],\n```\n\nwhich uses the default `axios` module:\n\n```\n//store/index.js\nimport axios from 'axios'\nimport api from '@/plugins/axios.js'\n\n//...\n\nconst actions = {\n async login(...) {\n // ....\n await axios.post('/restricted_pages/login', { username, password })\n // ....\n }\n}\n\n// ...\n```\n\n========================================\n\nTop Answer:\nThe Nuxt RuntimeConfig properties can be used instead of the `env` configuration:\n\nhttps://nuxtjs.org/docs/2.x/directory-structure/nuxt-config#publicruntimeconfig\n\n`publicRuntimeConfig` is available as `$config` for client and server side and can contain runtime environment variables by configuring it in `nuxt.config.js`:\n\n```\nexport default {\n ...\n publicRuntimeConfig: {\n myEnv: process.env.MYENV || 'my-default-value',\n },\n ...\n}\n```\n\nUse it in your components like so:\n\n```\n// within \n{{ $config.myEnv }}\n\n// within \nthis.$config.myEnv\n```\n\nSee also this blog post for further information.\n\n========================================\n\nCode:\n```js\nimport axios from 'axios'\n\nconst apiVersion = 'v0'\nconst api = axios.create({\n baseURL: `${process.env.PUBLIC_API_URL}/api/${apiVersion}/`\n})\n\nexport default api\n```\n\n```js\nimport colors from 'vuetify/es5/util/colors'\n\nimport bodyParser from 'body-parser'\nimport session from 'express-session'\nconsole.log(process.env.PUBLIC_API_URL)\nexport default {\n mode: 'spa',\n env: {\n PUBLIC_API_URL: process.env.PUBLIC_API_URL || 'http://localhost:6091'\n },\n // ...\n plugins: [\n //...\n '@/plugins/axios.js'\n ]\n}\n```\n\n```text\nproject/\n|-- backend (flask api)\n|-- frontend (npx create-nuxt-app frontend)\n |-- assets/\n |-- ...\n |-- plugins/\n |-- axios.js\n |-- restriced_pages\n |-- index.js (see other notes 3)\n |-- ...\n |-- nuxt.config.js\n |-- Dockerfile\n\n|-- .env\n|-- docker-compose.yml\n```\n\n```text\nversion: '3'\n\nservices:\n nuxt: # frontend\n image: frontend\n container_name: my_nuxt\n build:\n context: .\n dockerfile: ./frontend/Dockerfile\n restart: always\n ports:\n - \"3000:3000\"\n command: \"npm run start\"\n environment:\n - HOST\n - PUBLIC_API_URL\n\n flask: # backend\n image: backend\n container_name: my_flask\n build:\n context: .\n dockerfile: ./backend/Dockerfile\n command: bash deploy.sh\n\n environment:\n - REDIS_URL\n - PYTHONPATH\n ports:\n - \"9061:9061\"\n expose:\n - '9061'\n depends_on:\n - redis\n\n worker:\n image: backend\n container_name: my_worker\n command: python3 manage.py runworker\n depends_on:\n - redis\n environment:\n - REDIS_URL\n - PYTHONPATH\n\n redis: # for workers\n container_name: my_redis\n image: redis:5.0.3-alpine\n expose:\n - '6379'\n```\n\n```text\nFROM node:10.15\n\nENV APP_ROOT /src\n\nRUN mkdir ${APP_ROOT}\nWORKDIR ${APP_ROOT}\n\n\nCOPY ./frontend ${APP_ROOT}\n\nRUN npm install\n\nRUN npm run build\n```\n\n```js\n// Create express router\nconst router = express.Router()\n\n// Transform req & res to have the same API as express\n// So we can use res.status() & res.json()\nconst app = express()\nrouter.use((req, res, next) => {\n Object.setPrototypeOf(req, app.request)\n Object.setPrototypeOf(res, app.response)\n req.res = res\n res.req = req\n next()\n})\n\n// Add POST - /api/login\nrouter.post('/login', (req, res) => {\n\n if (req.body.username === username && req.body.password === password) {\n req.session.authUser = { username }\n return res.json({ username })\n }\n res.status(401).json({ message: 'Bad credentials' })\n})\n\n// Add POST - /api/logout\nrouter.post('/logout', (req, res) => {\n delete req.session.authUser\n res.json({ ok: true })\n})\n\n// Export the server middleware\nexport default {\n path: '/restricted_pages',\n handler: router\n\n}\n```\n\n```js\nserverMiddleware: [\n // body-parser middleware\n bodyParser.json(),\n // session middleware\n session({\n secret: 'super-secret-key',\n resave: false,\n saveUninitialized: false,\n cookie: { maxAge: 60000 }\n }),\n // Api middleware\n // We add /restricted_pages/login & /restricted_pages/logout routes\n '@/restricted_pages'\n ],\n```\n\n```js\n//store/index.js\nimport axios from 'axios'\nimport api from '@/plugins/axios.js'\n\n//...\n\nconst actions = {\n async login(...) {\n // ....\n await axios.post('/restricted_pages/login', { username, password })\n // ....\n }\n}\n\n// ...\n```\n\n```text\nPUBLIC_API_URL\n```\n\n```text\nhttp://localhost:9061\n```\n\n```text\n.env\n```\n\n```text\n9061\n```\n\n```text\n6091\n```\n\n```text\n@/plugins/axios.js\n```\n\n```text\ncommons.app.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\naxios\n```\n\n```text\nnuxt:\n build:\n # ...\n args:\n PUBLIC_API_URL: http://localhost:9061\n```\n\n```text\nARG PUBLIC_API_URL\nENV PUBLIC_API_URL ${PUBLIC_API_URL}\n```\n\n```text\nnuxt:\n build:\n # ...\n args:\n PUBLIC_API_URL: ${PUBLIC_API_URL}\n```\n\n```text\n$ docker run\n```\n\n```text\nENV PUBLIC_API_URL http://localhost:9061\n```\n\n```text\n$ export PUBLIC_API_URL=http://localhost:9061\n```\n\n```js\nexport default {\n ...\n publicRuntimeConfig: {\n myEnv: process.env.MYENV || 'my-default-value',\n },\n ...\n}\n```\n\n```js\n// within <template>\n{{ $config.myEnv }}\n\n// within <script>\nthis.$config.myEnv\n```\n\n```text\nenv\n```\n\n```text\npublicRuntimeConfig\n```\n\n```text\n$config\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- Do you have the environment variables set on the machine on which you're running the Docker container? You need to have HOST, PUBLIC_API_URL, REDIS_URL, and PYTHONPATH set on the machine since they are pass-through environment variables (they come from the machine's environment since they are not set in the docker-compose.yml file).\n- @furman87there is an `.env` file with these specified (sorry if that was not clear in the OP), the `console.log` statement from `nuxt.config.js` suggests that the env variable is picked up, but not carried to client\n- This solution is at built time, not at runtime, it should has a solution for runtime as when we pull docker image to use, it should be able to configure the environment at that time, not fix it at the build time.\n- I'm having the same issue - things only work if i supply the .env file along in the build process. But that apparently embeds the data from it in the image.. which is nonsense - who wants secrets embedded in the image...\n- This solution does not solve the problem","metadata":{"transformedAt":"2026-08-18T18:33:07.840Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":565,"estimatedTokens":2622}}120{"id":"stack-58134718","source":"stackoverflow","questionId":58134718,"title":"How disable default layout on other page","tags":["vue.js","nuxt.js"],"text":"Title: How disable default layout on other page\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a problem with the layout default page on NUXT. I create a new page but by default, nuxt use layout/default.vue. I don't like use default layout page.\n\nIf you have a solution to my problem. Thank you :)\n\nI have tried `layout: 'none'`\n\n========================================\n\nTop Answer:\nIf you really don't want a layout, create one named \"`/layouts/empty.vue`\" that looks like this:\n\n```\n\n \n\n```\n\nspecify it in your page with:\n\n```\n\nexport default {\n layout: \"empty\"\n};\n\n```\n\n========================================\n\nCode:\n```text\nlayout: 'none'\n```\n\n```text\n<template>\n <nuxt />\n</template>\n```\n\n```text\n<script>\nexport default {\n layout: \"empty\"\n};\n</script>\n```\n\n```text\n/layouts/empty.vue\n```\n\n```text\n// error.vue\n<script>\nexport default {\n layout: \"empty\"\n};\n</script>\n```\n\n```text\nlayout: \"empty\"\n```\n\n```text\nlayouts: {\n default: '~/layouts/empty.vue',\n },\n```\n\n```text\n<script setup>\ndefinePageMeta({\n layout: false,\n});\n</script>\n```\n\n```text\n<script setup>\ndefinePageMeta({\n layout: \"custom_layout\",\n});\n</script>\n```\n\n```text\n<script setup>\n```\n\n```text\n<script>\n```\n\n========================================\n\nComments:\n- i don't think you make nuxt page without layout. You can create empty layout as default and make named layout for manual. Or simple create layout with name 'none' and setup him in new pages.\n- Nuxt seems to be overriding the child routes layout. In my case I have the `default` and `no-footer` layouts. The `/checkout` has no layout but it's overriding the value set in `/checkout/something`","metadata":{"transformedAt":"2026-08-18T18:33:07.841Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":105,"estimatedTokens":416}}121{"id":"stack-55445196","source":"stackoverflow","questionId":55445196,"title":"CORS blocking client request in Nuxt.js","tags":["vuejs2","cors","vuex","nuxt.js"],"text":"Title: CORS blocking client request in Nuxt.js\nTags: vuejs2, cors, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am having issues when making a client request.\n\nI have followed the documentation on Nuxt.js and Axios but I still can't seem to get it working. Maybe I am missing something..\n\nMy Vue component calling the **vuex action**:\n\n```\nmethods: {\n open() {\n this.$store.dispatch('events/getEventAlbum');\n }\n}\n```\n\nThe **action** in **vuex**:\n\n```\nexport const actions = {\n async getEventAlbum(store) {\n console.log('album action');\n const response = await Axios.get(url + '/photos?&sign=' + isSigned + '&photo-host=' + photoHost);\n store.commit('storeEventAlbum', response.data.results);\n }\n};\n```\n\nAnd my **nuxt.js.config**\n\n```\nmodules: [\n '@nuxtjs/axios',\n '@nuxtjs/proxy'\n],\n\naxios: {\n proxy: true\n},\n\nproxy: {\n '/api/': {\n target: 'https://api.example.com/',\n pathRewrite: { '^/api/': '' }\n }\n}\n```\n\nAnybody who can help?\n\n========================================\n\nCode:\n```js\nmethods: {\n open() {\n this.$store.dispatch('events/getEventAlbum');\n }\n}\n```\n\n```js\nexport const actions = {\n async getEventAlbum(store) {\n console.log('album action');\n const response = await Axios.get(url + '/photos?&sign=' + isSigned + '&photo-host=' + photoHost);\n store.commit('storeEventAlbum', response.data.results);\n }\n};\n```\n\n```js\nmodules: [\n '@nuxtjs/axios',\n '@nuxtjs/proxy'\n],\n\naxios: {\n proxy: true\n},\n\nproxy: {\n '/api/': {\n target: 'https://api.example.com/',\n pathRewrite: { '^/api/': '' }\n }\n}\n```\n\n```js\nmodules: [\n '@nuxtjs/axios',\n '@nuxtjs/proxy'\n],\n\naxios: {\n proxy: true\n},\n\nproxy: {\n '/api/': { target: 'https://api.example.com/', pathRewrite: {'^/api/': ''}, changeOrigin: true }\n}\n```\n\n```text\nchangeOrigin\n```\n\n```text\n/api\n```\n\n========================================\n\nComments:\n- It will be your api blocking the request. What is the cors error you get in the console? What type of api are you using?\n- Hi @Andrew1325 , it's a **RESTful** API and I am getting the **No 'Access-Control-Allow-Origin' header** error.\n- Is your api an express (node.js) api?\n- @Andrew1325 , yes, Nuxt.js is built on top of Node & Express\n- @Manu No, Nuxt is built on top of Vue.js and apparently Node. Express is just an integration.\n- Hi Daniel, **changeOrigin** did not make much of a difference. Still getting the same error.. `Access to XMLHttpRequest at 'https://api.example.com/2/photos?&sign=true&photo-host=publ‌​ic&event_id=testID' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.`\n- then you're not hitting the proxy at all, so it doesn't matter what you set up through your config, because you're bypassing it completely. Can you show the code for `url` (`const response = await Axios.get(url + ...`)? You probably just need to make that `/api`\n- It works fine if I paste the link `https://api.example.com/2/photos?&sign=true&photo-host=publi‌​c&event_id=testID` in my browser so I am pretty sure it's nothing wrong with anything in my `Axios.get()`\n- It's the browsers' security policy if you paste it in as a link, CORS is not an issue. you need to use `https://api.example.com/2/` as your **proxy target** and use `/api` **within your app**. That's what the proxy is for, it routes the traffic through a server rather than the browser getting it.\n- Is this possible to have this working on a Netlify static site?\n- @FirzokNadeem I don't think so. This is for development purposes only.\n- @FirzokNadeem no, because Netlify does not provide a running Node.js server (as of today). And it's not a good solution for production anyway.\n- Even if the accepted answer works, keep in mind that it's more of a band aid than an actual solution. For a real answer, please check this one. TLDR being that you should ask the backend team to enable it or to whitelist your localhost into an admin dashboard. This will bring the great benefit of not having to rely on SSR (if your project could run on SSG without the proxy module).","metadata":{"transformedAt":"2026-08-18T18:33:07.841Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":131,"estimatedTokens":1038}}122{"id":"stack-64124271","source":"stackoverflow","questionId":64124271,"title":"What version of Vue am I running in Nuxt 2.14.0?","tags":["vue.js","vuejs2","nuxt.js","vuejs3","vue-composition-api"],"text":"Title: What version of Vue am I running in Nuxt 2.14.0?\nTags: vue.js, vuejs2, nuxt.js, vuejs3, vue-composition-api\nSource: Stack Overflow\n\nQuestion:\nI'm trying to identify if my Nuxt app (2.14.0) is using Vue 2 or Vue 3, and I cannot tell. I have dived through `node_modules` and looked at my lock file but can't say for certain. I *think* it's using only Vue 2 -- specifically `vue \"^2.6.12` -- based on what I can tell in the lock file.\n\nDoes anyone know which version of Vue that Nuxt is using in version 2.14.0 ? I tried reading through this issue to better understand when / if Vue 3 has been introduced and release publicly in Nuxt.js but it sounds like Vue 3 is not incorporated inside any release of Nuxt.js.\n\n========================================\n\nTop Answer:\nMaybe you could try `npm why vue` and check for the lines about nuxt (yarn works exactly the same too: `yarn why vue`)\n\n```\nvue@2.6.14\nnode_modules/@nuxt/vue-renderer/node_modules/vue\n vue@\"^2.6.12\" from @nuxt/vue-renderer@2.15.8\n node_modules/@nuxt/vue-renderer\n @nuxt/vue-renderer@\"2.15.8\" from nuxt@2.15.8\n node_modules/nuxt\n nuxt@\"^2.15.8\" from the root project\n @nuxt/vue-renderer@\"2.15.8\" from @nuxt/server@2.15.8\n node_modules/@nuxt/server\n @nuxt/server@\"2.15.8\" from nuxt@2.15.8\n node_modules/nuxt\n nuxt@\"^2.15.8\" from the root project\n @nuxt/server@\"2.15.8\" from @nuxt/core@2.15.8\n node_modules/@nuxt/core\n @nuxt/core@\"2.15.8\" from nuxt@2.15.8\n node_modules/nuxt\n nuxt@\"^2.15.8\" from the root project\n\nvue@2.6.14\nnode_modules/@nuxt/vue-app/node_modules/vue\n vue@\"^2.6.12\" from @nuxt/vue-app@2.15.8\n node_modules/@nuxt/vue-app\n @nuxt/vue-app@\"2.15.8\" from nuxt@2.15.8\n node_modules/nuxt\n nuxt@\"^2.15.8\" from the root project\n @nuxt/vue-app@\"2.15.8\" from @nuxt/builder@2.15.8\n node_modules/@nuxt/builder\n @nuxt/builder@\"2.15.8\" from nuxt@2.15.8\n node_modules/nuxt\n nuxt@\"^2.15.8\" from the root project\n peer vue@\"^2.0.0\" from vuex@3.6.2\n node_modules/@nuxt/vue-app/node_modules/vuex\n vuex@\"^3.6.2\" from @nuxt/vue-app@2.15.8\n node_modules/@nuxt/vue-app\n @nuxt/vue-app@\"2.15.8\" from nuxt@2.15.8\n node_modules/nuxt\n nuxt@\"^2.15.8\" from the root project\n @nuxt/vue-app@\"2.15.8\" from @nuxt/builder@2.15.8\n node_modules/@nuxt/builder\n @nuxt/builder@\"2.15.8\" from nuxt@2.15.8\n node_modules/nuxt\n nuxt@\"^2.15.8\" from the root project\n```\n\nSo nuxt@2.15.8 uses vue@2.6.14 for my example.\n\n========================================\n\nCode:\n```text\nnode_modules\n```\n\n```text\nvue \"^2.6.12\n```\n\n```text\ncomposition-api.nuxtjs\n```\n\n```text\n@nuxtjs/composition-api\n```\n\n```text\nvue@2.6.14\nnode_modules/@nuxt/vue-renderer/node_modules/vue\n vue@\"^2.6.12\" from @nuxt/vue-renderer@2.15.8\n node_modules/@nuxt/vue-renderer\n @nuxt/vue-renderer@\"2.15.8\" from nuxt@2.15.8\n node_modules/nuxt\n nuxt@\"^2.15.8\" from the root project\n @nuxt/vue-renderer@\"2.15.8\" from @nuxt/server@2.15.8\n node_modules/@nuxt/server\n @nuxt/server@\"2.15.8\" from nuxt@2.15.8\n node_modules/nuxt\n nuxt@\"^2.15.8\" from the root project\n @nuxt/server@\"2.15.8\" from @nuxt/core@2.15.8\n node_modules/@nuxt/core\n @nuxt/core@\"2.15.8\" from nuxt@2.15.8\n node_modules/nuxt\n nuxt@\"^2.15.8\" from the root project\n\nvue@2.6.14\nnode_modules/@nuxt/vue-app/node_modules/vue\n vue@\"^2.6.12\" from @nuxt/vue-app@2.15.8\n node_modules/@nuxt/vue-app\n @nuxt/vue-app@\"2.15.8\" from nuxt@2.15.8\n node_modules/nuxt\n nuxt@\"^2.15.8\" from the root project\n @nuxt/vue-app@\"2.15.8\" from @nuxt/builder@2.15.8\n node_modules/@nuxt/builder\n @nuxt/builder@\"2.15.8\" from nuxt@2.15.8\n node_modules/nuxt\n nuxt@\"^2.15.8\" from the root project\n peer vue@\"^2.0.0\" from vuex@3.6.2\n node_modules/@nuxt/vue-app/node_modules/vuex\n vuex@\"^3.6.2\" from @nuxt/vue-app@2.15.8\n node_modules/@nuxt/vue-app\n @nuxt/vue-app@\"2.15.8\" from nuxt@2.15.8\n node_modules/nuxt\n nuxt@\"^2.15.8\" from the root project\n @nuxt/vue-app@\"2.15.8\" from @nuxt/builder@2.15.8\n node_modules/@nuxt/builder\n @nuxt/builder@\"2.15.8\" from nuxt@2.15.8\n node_modules/nuxt\n nuxt@\"^2.15.8\" from the root project\n```\n\n```text\nnpm why vue\n```\n\n```text\nyarn why vue\n```\n\n========================================\n\nComments:\n- Thank you @Boussadjra Brahim -- I was actually trying to install swiper js, swiperjs.com/vue, which requires Vue 3. I'm not too sure if there's a work around here unless Vue 3 is used instead of Vue 2 in nuxt.js.\n- i think you should install an older version of swiper which could be compatible with vue 3\n- That sounds like a good suggestion. But in fact, I found something that works for me github.com/surmon-china/vue-awesome-swiper -- looks like it allows you to use Vue 2 and Swiper JS\n- This is a semi-good answer, problem is, 5 seconds after it is posted, this fact may have changed. There must be some way to find out which version nuxt is using now?\n- Until now, the nuxt 3 which will be based on vue 3 has not released yet, I'm watching the news in Github and Twitter and I'll edit my answer when there'll be a new version\n- But, what is the way to identify the Vue version the nuxtjs im using\n- @Jovylle to get the exact version of any library, check the `node_modules` folder to look for your library's package.json. For example at `node_modules/vue/package.json`.\n- Thank you Vitamin Water I really need you in my life.","metadata":{"transformedAt":"2026-08-18T18:33:07.841Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":144,"estimatedTokens":1341}}123{"id":"stack-64239478","source":"stackoverflow","questionId":64239478,"title":"How to use SSR with Vue 3 - Vue packages version mismatch","tags":["vue.js","nuxt.js","vuejs3","server-side-rendering","nuxt3.js"],"text":"Title: How to use SSR with Vue 3 - Vue packages version mismatch\nTags: vue.js, nuxt.js, vuejs3, server-side-rendering, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI have a working Vue 2 app with server side rendering. Now I'm trying to upgrade to Vue 3 but stuck on the SSR part cuz the vue-server-renderer package throws the following error:\n\n```\nVue packages version mismatch: - vue@3.0.0 - vue-server-renderer@2.6.12 This may cause things to work incorrectly. Make sure to use the same version for both.\n```\n\nBut there is no version 3.0.0 for vue-server-renderer and I have an \"Vue packages version mismatch\" kind of error.\n\nWith googling I found this issue on the vue-next repository: https://github.com/vuejs/vue-next/issues/1327\n\nBut for me it is still unclear how to achieve SSR with version 3 of vue. Is it already possible? Is there an example how to use SSR with Vue 3?\n\n========================================\n\nCode:\n```text\nVue packages version mismatch: - vue@3.0.0 - vue-server-renderer@2.6.12 This may cause things to work incorrectly. Make sure to use the same version for both.\n```\n\n```js\nconst express = require('express');\nconst { createSSRApp } = require('vue');\nconst { renderToString } = require('@vue/server-renderer');\n\nconst app = express();\n\nconst example= {\n template: `\n <div>\n Hello World\n </div>`,\n};\n\nfunction renderVueApp(req, res) {\n const vueApp = createSSRApp(example);\n\n (async () => {\n const html = await renderToString(vueApp);\n\n res.send(`\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <script src=\"https://unpkg.com/vue@next\"></script>\n <title>About blank</title>\n </head>\n <body>\n <div id=\"app\">${html}</div>\n <script>\n const example = { template: '<div>Hello World</div>}; \n Vue.createSSRApp(example).mount('#app', true);\n </script>\n </body>\n </html>\n `);\n })();\n}\n\napp.get('/', renderVueApp);\n\nconst port = process.env.PORT || 8080;\napp.listen(port, () =>\n console.log(`Server started at localhost:${port}. Press ctrl+c to quit.`)\n);\n```\n\n```text\ncreateSSRApp\n```\n\n```text\nrenderToString\n```\n\n```text\n@vue/server-renderer\n```\n\n```text\nssrContext._registeredComponents\n```\n\n========================================\n\nComments:\n- Any sample for complex case? For example: import 3rd party component libraries\n- No specific example at hand. Did you take a look at the git repo? I havn't played this with any component lib, but I suppose you just plug it in the regular way. I built a regular app with antd vue 3 and I see no obstacles that would prevent this from working in a ssr setup. Hope that helps\n- @UliKrause What if I need typescript?\n- At the moment there is no need to install `@vue/server-renderer` separately, just load it from Vue itself like `require(\"vue/server-renderer\")`\n- @Rustery that one even needs to use `import` nowadays.","metadata":{"transformedAt":"2026-08-18T18:33:07.841Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":97,"estimatedTokens":760}}124{"id":"stack-48285476","source":"stackoverflow","questionId":48285476,"title":"Using nuxt, how do I put the route name in the page title?","tags":["javascript","vue.js","vue-router","nuxt.js"],"text":"Title: Using nuxt, how do I put the route name in the page title?\nTags: javascript, vue.js, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to set the page title to a different value for each page.\n\nIn regular Vue.js, I have done the following:\n\n```\nimport router from './router'\nimport { store } from './store/store';\n\nrouter.beforeEach((to, from, next) => {\n store.mutations.setRoute(to);\n document.title = store.getters.pageTitle;\n next();\n}\n```\n\nHow would I get that effect in nuxt?\n\nThat is, on both initial page load and when changing pages, I want the browser tab's title to change. For instance, from \"My App - About\" to \"My App - Profile\".\n\n========================================\n\nTop Answer:\nI found a way to do this, but I don't know if it is the \"right\" way. I use the `mounted()` function in `default.vue` for the initial page load and the `transition` property in `nuxt.config.js` for each page change. So, in `default.vue`:\n\n```\n...mapGetters(['appTitle']),\n...mapMutations(['setRoute']),\nmounted() {\n this.setRoute(this.$route.name);\n document.title = this.appTitle();\n}\n```\n\nAnd in `nuxt.config.js`:\n\n```\ntransition: {\n name: 'page',\n mode: 'out-in',\n beforeEnter (el) {\n this.$store.commit(\"setRoute\", this.$route.name);\n document.title = this.$store.getters.appTitle;\n }\n},\n```\n\n========================================\n\nCode:\n```text\nimport router from './router'\nimport { store } from './store/store';\n\nrouter.beforeEach((to, from, next) => {\n store.mutations.setRoute(to);\n document.title = store.getters.pageTitle;\n next();\n}\n```\n\n```text\nhead() {\n return {\n title: \"About page\"\n };\n }\n```\n\n```text\npages\n```\n\n```text\n...mapGetters(['appTitle']),\n...mapMutations(['setRoute']),\nmounted() {\n this.setRoute(this.$route.name);\n document.title = this.appTitle();\n}\n```\n\n```text\ntransition: {\n name: 'page',\n mode: 'out-in',\n beforeEnter (el) {\n this.$store.commit(\"setRoute\", this.$route.name);\n document.title = this.$store.getters.appTitle;\n }\n},\n```\n\n```text\nmounted()\n```\n\n```text\ndefault.vue\n```\n\n```text\ntransition\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ndefault.vue\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n<script setup>\ndocument.title = useRoute().name;\n\n... logic ...\n</script>\n```\n\n```text\nsetup() {\n document.title = useRoute().query;\n},\n```\n\n```text\ndocument.title\n```\n\n```text\n<script setup>\n```\n\n========================================\n\nComments:\n- That works, mostly -- I can put the static page name in, but that doesn't handle all cases. I'd like to use the vuex store to compute the page name because it will contain an asterisk in some conditions. But combining that with the mounted() { document.title = } works perfectly. Thanks!\n- head() { return { title: this.$route.name } },\n- @CharlesBrandt that suggestion worked perfectly. thank you\n- What about nuxt3)\n- @modex98 haven't used Nuxt 3 yet but from docs it seems you have to use `useRoute` composable inside `setup` script/method.See the docs v3.nuxtjs.org/api/composables/use-route\n- did you look at my answer?\n- This answer works well for me as I have a large app and manage all of my routes & meta programmatically in one js file; it makes sense to also manage titles there as well. I'd rather not have to deal with `title` across numerous page components all over the place.\n- Also: Using `document.title` seems to be legit, as vue-creator Evan You himself does so in these title snippets.\n- How about server-side? `document.title` is only available on client-side.","metadata":{"transformedAt":"2026-08-18T18:33:07.841Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":155,"estimatedTokens":885}}125{"id":"stack-54040683","source":"stackoverflow","questionId":54040683,"title":"NUXT: Module not found: Error: Can't resolve 'fs'","tags":["node.js","vue.js","webpack","nuxt.js"],"text":"Title: NUXT: Module not found: Error: Can't resolve 'fs'\nTags: node.js, vue.js, webpack, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm starting out with vue and nuxt, I have a project using vuetify and I'm trying to modify the carousel component to dynamically load images from the static folder. So far I've come up with:\n\n```\n\n \n \n \n \n\n \n function getImagePaths() {\n var glob = require(\"glob\");\n var options = {\n cwd: \"./static\"\n };\n var fileNames = glob.sync(\"*\", options);\n var items = [];\n fileNames.forEach(fileName =>\n items.push({\n 'src': '/'+fileName\n })\n );\n return items;\n }\n export default {\n data() {\n return {items :getImagePaths()};\n }\n };\n\n \n```\n\nWhen I test this I see:\n\n```\nERROR in ./node_modules/fs.realpath/index.js\nModule not found: Error: Can't resolve 'fs' in '....\\node_modules\\fs.realpath'\nERROR in ./node_modules/fs.realpath/old.js\nModule not found: Error: Can't resolve 'fs' in ....\\node_modules\\fs.realpath'\nERROR in ./node_modules/glob/glob.js\nModule not found: Error: Can't resolve 'fs' in '....\\node_modules\\glob'\nERROR in ./node_modules/glob/sync.js\nModule not found: Error: Can't resolve 'fs' in '.....\\node_modules\\glob'\n```\n\ngoogling this I see a bunch of references like https://github.com/webpack-contrib/css-loader/issues/447.\n\nThese suggest that you have to midify the webpack config file with something like:\n\n```\nnode: {\n fs: 'empty'\n}\n```\n\nI know very little about webpack. I found https://nuxtjs.org/faq/extend-webpack/ , but am not sure how to modify the webpack config file in this case.\n\nHow do I do this?\n\n========================================\n\nTop Answer:\nI know this is an old question, but it may be helpful for someone to disable fs in their browser.\n\nLike this:\n\nnuxt.config.js\n\n```\nbuild: {\n extend (config, { isDev, isClient }) {\n\n config.node= {\n fs: 'empty'\n }\n\n // ....\n }\n },\n```\n\n========================================\n\nCode:\n```text\n<template>\n <v-carousel>\n <v-carousel-item v-for=\"(item,i) in items\" :key=\"i\" :src=\"item.src\"></v-carousel-item>\n </v-carousel>\n </template>\n\n\n <script>\n function getImagePaths() {\n var glob = require(\"glob\");\n var options = {\n cwd: \"./static\"\n };\n var fileNames = glob.sync(\"*\", options);\n var items = [];\n fileNames.forEach(fileName =>\n items.push({\n 'src': '/'+fileName\n })\n );\n return items;\n }\n export default {\n data() {\n return {items :getImagePaths()};\n }\n };\n\n </script>\n```\n\n```text\nERROR in ./node_modules/fs.realpath/index.js\nModule not found: Error: Can't resolve 'fs' in '....\\node_modules\\fs.realpath'\nERROR in ./node_modules/fs.realpath/old.js\nModule not found: Error: Can't resolve 'fs' in ....\\node_modules\\fs.realpath'\nERROR in ./node_modules/glob/glob.js\nModule not found: Error: Can't resolve 'fs' in '....\\node_modules\\glob'\nERROR in ./node_modules/glob/sync.js\nModule not found: Error: Can't resolve 'fs' in '.....\\node_modules\\glob'\n```\n\n```text\nnode: {\n fs: 'empty'\n}\n```\n\n```text\nconst express = require('express')\n\n// Create express instance\nconst app = express()\n\n// Require API routes\nconst carousel = require('./routes/carousel')\n\n// Import API Routes\napp.use(carousel)\n\n// Export the server middleware\nmodule.exports = {\n path: '/api',\n handler: app\n}\n```\n\n```text\nconst { Router } = require('express')\nconst glob = require('glob')\n\nconst router = Router()\n\nrouter.get('/carousel/images', async function (req, res) {\n const options = {\n cwd: './static'\n }\n const filenames = glob.sync('*', options)\n\n let items = [];\n filenames.forEach(filename =>\n items.push({\n 'src': '/'+filename\n })\n );\n\n return res.json({ data: items })\n})\n\nmodule.exports = router\n```\n\n```text\nmodule.exports = {\n build: {\n ...\n },\n serverMiddleware: [\n '~/api/index.js'\n ]\n}\n```\n\n```text\n<script>\nexport default {\n async asyncData ({ $axios }) {\n const images = (await $axios.$get('/api/carousel/images')).data\n\n return { images }\n }\n}\n</script>\n```\n\n```text\nindex.js\n```\n\n```text\napi/index.js\n```\n\n```text\ncarousel.js\n```\n\n```text\napi/routes/carousel.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nbuild: {\n extend (config, { isDev, isClient }) {\n\n config.node= {\n fs: 'empty'\n }\n\n // ....\n }\n },\n```\n\n```text\nbuild: { extend (config, { isDev, isClient }) {\n config.node = {\n fs: 'empty'\n }\n\n // ....\n}},\n```\n\n```text\nnuxt-config.js\n```\n\n========================================\n\nComments:\n- you cant use fs module on client\n- Ok, What would you suggest.\n- make an api endpoint that would return image urls for the images and make api call to get it in asyncData\n- Does this require the axios module?\n- not necessary, but yes\n- Would you be able to give me an example?\n- Thank you very much for the detailed exemplary code. Based on this code and the express-template, I managed to load image from specific directory in a dynamic page based on the route name. However, I found that such custom API won't work for static generated site using `nuxt generate`. If I understand correctly, this is because there simply won't be any server we can call our API from. I am wondering is there any workaround for this? Is it possible to use custom API like shown here for static site?","metadata":{"transformedAt":"2026-08-18T18:33:07.841Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":263,"estimatedTokens":1326}}126{"id":"stack-60692255","source":"stackoverflow","questionId":60692255,"title":"Nuxt open link into modal","tags":["javascript","vue.js","vue-router","nuxt.js"],"text":"Title: Nuxt open link into modal\nTags: javascript, vue.js, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a Nuxt application that has a list of products and clicking on one of them open a dedicated page of the product. It is working fine.\n\nStructure is:\n\n```\n/pages/featured // directory of products\n/pages/product/:id/:slug // Dedicated product page\n```\n\nNow I wish to add a new feature:\n\n- I wish to keep the dedicated page of the product if clicked from a page that is not the directory of the products or if people land directly on it;\n\n- I wish to open an almost full-screen dialog of the product on top of the directory if, obviously, clicked from the directory;\n\n- Keep the routing change on dialogs.\n\nA nice example of what I wish to achieve is the photo directory of Youpic.\n\nA list of \"products\", visible entirely in a dialog with its internal navigation.\n\nI'm looking at the various nuxt-routing and vue-router documentations to try developing it but I'm still far away from the solution.\n\nThis small portion of the code I see here looks pretty similar at what I need but I don't understand how should I correctly implement it and how to create my nuxt custom routing:\n\n```\nexport default {\n router: {\n extendRoutes (routes, resolve) {\n routes.push({\n path: '/users/:id',\n components: {\n default: resolve(__dirname, 'pages/users'), // or routes[index].component\n modal: resolve(__dirname, 'components/modal.vue')\n },\n chunkNames: {\n modal: 'components/modal'\n }\n })\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nI recently implemented this feature after facing nearly the same situation you are in. At least in my case, I was really overthinking it. \n\nAll that I did was take the single resource page (/pages/product/:id/:slug in your case) and have it be a modal by default. I am using vuetify and v-dialog is a modal. The nuxt project hierarchy didn't change. Your equivalent would be the slug.vue page. \n\n```\n\n \n \n \n \n close\n \n {{member.alias}}\n \n \n Notes\n Edit\n Payments\n\n \n \n \n \n \n \n\nimport { mapGetters } from \"vuex\";\nexport default {\nwatchQuery: [\"id\"],\ntransition(to, from) {\n if (!from) {\n return \"slide-left\";\n }\n return +to.query.id < +from.query.id ? \"slide-right\" : \"slide-left\";\n},\ndata() {\n return {\n id: this.$route.params.id,\n drawer: true\n };\n},\nfetch({ store, params }) {\n store.commit(\"members/active\", params.id);\n},\ncomputed: {\n member: {\n get() {\n return this.$store.getters[\"members/active\"];\n },\n set(member) {\n this.$store.commit(\"members/update\", {\n id: member.id,\n member: member\n });\n }\n }\n},\nmethods: {\n async close() {\n await this.$nuxt.$router.go(-1);\n this.drawer = false;\n }\n}\n};\n```\n\n========================================\n\nCode:\n```text\n/pages/featured // directory of products\n/pages/product/:id/:slug // Dedicated product page\n```\n\n```text\nexport default {\n router: {\n extendRoutes (routes, resolve) {\n routes.push({\n path: '/users/:id',\n components: {\n default: resolve(__dirname, 'pages/users'), // or routes[index].component\n modal: resolve(__dirname, 'components/modal.vue')\n },\n chunkNames: {\n modal: 'components/modal'\n }\n })\n }\n }\n}\n```\n\n```text\nbeforeRouteLeave(to, from, next) {\n if (to.name === \"product-id\") {\n this.displayProductModal(to);\n } else {\n next();\n }\n},\n```\n\n```text\ndisplayProductModal(route) {\n this.activeModal = route.params.id\n window.history.pushState({}, null, route.path)\n},\nhideProductModal() {\n this.activeModal = null\n window.history.pushState({}, null, this.$route.path)\n}\n```\n\n```text\nbeforeRouteLeave()\n```\n\n```text\nvue-router\n```\n\n```text\nwindow.history\n```\n\n```text\n<template>\n<v-dialog v-model=\"drawer\" fullscreen hide-overlay transition=\"dialog-bottom-transition\">\n <v-card height=\"100vh\">\n <div class=\"flex\">\n <v-toolbar dark color=\"primary darken-2\">\n <v-btn icon dark @click=\"close\">\n <v-icon>close</v-icon>\n </v-btn>\n <v-toolbar-title>{{member.alias}}</v-toolbar-title>\n <v-spacer></v-spacer>\n <v-toolbar-items>\n <v-btn text nuxt :to=\"`/members/${member.id}/notes`\">Notes</v-btn>\n <v-btn text nuxt :to=\"`/members/${member.id}/edit`\">Edit</v-btn>\n <v-btn text nuxt :to=\"`/members/${member.id}/payments`\">Payments</v-btn>\n\n </v-toolbar-items>\n </v-toolbar>\n <v-row no-gutters>\n </v-row>\n </div>\n </v-card>\n</v-dialog>\n</template>\n\n<script>\nimport { mapGetters } from \"vuex\";\nexport default {\nwatchQuery: [\"id\"],\ntransition(to, from) {\n if (!from) {\n return \"slide-left\";\n }\n return +to.query.id < +from.query.id ? \"slide-right\" : \"slide-left\";\n},\ndata() {\n return {\n id: this.$route.params.id,\n drawer: true\n };\n},\nfetch({ store, params }) {\n store.commit(\"members/active\", params.id);\n},\ncomputed: {\n member: {\n get() {\n return this.$store.getters[\"members/active\"];\n },\n set(member) {\n this.$store.commit(\"members/update\", {\n id: member.id,\n member: member\n });\n }\n }\n},\nmethods: {\n async close() {\n await this.$nuxt.$router.go(-1);\n this.drawer = false;\n }\n}\n};\n```\n\n```text\nhttps://www.example.com/featured (directory of products)\n```\n\n```text\nhttps://www.example.com/product/:id/:slug (Details page)\n```\n\n```text\nhttps://www.example.com/featured (directory of products)\n```\n\n```text\nnuxt-link\n```\n\n```text\nhttps://www.example.com/product/:id/:slug (Details page)\n```\n\n```text\nhttps://www.example.com/featured (directory of products)\n```\n\n```text\nrouter.push\n```\n\n```text\nNuxt\n```\n\n```text\npages/explore\n```\n\n```text\nrouter.push\n```\n\n```text\nURL(https://youpic.com/image/16660875/steffi-by-fs22photography)\n```\n\n```text\nNuxt code structure\n```\n\n```text\npages/image/:id/:slug\n```\n\n========================================\n\nComments:\n- What about adding an iframe to that modal and navigating through it?\n- Did you end up finding a good solution to this? I've been trying to solve the exact same problem.\n- Thanks, I will give it a try very soon and let you know!\n- Unfortunately this is not working as I do expect... the `/featured` page lose all contents, I wish to emulate exactly what Youpic did for their gallery. Thanks!\n- If this is the contents of the :slug, it should have no impact at all on the contents of featured.\n- You got the point but I would like to see some example because like that, to be honest, I don't know what should I do... I already use `nuxt-link` for each product from the featured page, but it land on that page... I need the modal to be on top of the explore page, with its URL changed. Exactly like youpic/explore. It would be nice to have an example on how I should configure these 2 pages and routing... Thanks!\n- Do you have your code online working?? Or can you add code online tools??\n- Cheers for this example and explenation,! It is working very well! Cheers!\n- Works well, one minor thing, is there any hook/event when browser back button is clicked?\n- I got the back button issue working with popstate","metadata":{"transformedAt":"2026-08-18T18:33:07.841Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":309,"estimatedTokens":1816}}127{"id":"stack-70284856","source":"stackoverflow","questionId":70284856,"title":"Nuxt - add script to head and body","tags":["nuxt.js"],"text":"Title: Nuxt - add script to head and body\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to use this script in my Nuxt app, but can't figure out how. In a basic HTML file, it works fine. This is the code:\n\n```\n\n \n outdooractive platform - API Template\n \n\n \n \n \n\n \n \n\n \n \n\n \n \n\n var conf = {\n frontendtype: \"tour\", // choose content type\n zoom: 11, // set initial zoom level\n center: [ 10.292, 47.546 ] // set initial map center\n };\n \n var fvp = oa.api.flexviewpage( conf );\n\n \n \n\n```\n\nI have tried this approach, but it returns with an error that `api doesn't exist`\n\n```\ndata() {\n return {\n conf: {\n frontendtype: 'tour',\n zoom: 11,\n center: [10.292, 47.546]\n }\n }\n },\n head() {\n return {\n script: [\n {\n src: '//www.outdooractive.com/alpportal/oa_head.js?proj=api-dev-oa&key=yourtest-outdoora-ctiveapi&lang=en'\n },\n {\n body: true,\n fvp: this.oa.api.flexviewpage(this.conf) // attempt one\n fvp: () => {this.oa.api.flexviewpage(this.conf)} // attempt two\n }\n ]\n }\n }\n```\n\nI am still fairly new so would really appreciate some help, and perhaps a description of why the `var fvp` is recognized in a plain HTML file, but not with Nuxt.\n\nThank you\n\n========================================\n\nTop Answer:\nPlease note that the `Script` component has been deprecated as of Nuxt 3.0.0-rc.14 and the suggested method is now `useHead`\nhttps://github.com/nuxt/framework/releases/tag/v3.0.0-rc.14\n\nIn Nuxt 3 you simply use the `Script` component, eg:\n\n```\n\n```\n\nor\n\n```\n\n // some JS code\n\n```\n\nNote that most things that typically go in the head portion of the document now have components. There is also the `useHead` composable. See https://nuxt.com/docs/api/composables/use-head\n\n========================================\n\nCode:\n```html\n<!DOCTYPE html>\n<html>\n <head>\n <title>outdooractive platform - API Template</title>\n <meta charset=\"utf-8\">\n\n \n <!-- load Outdooractive Javascript API -->\n <script type=\"text/javascript\" \n src=\"//www.outdooractive.com/alpportal/oa_head.js?proj=api-dev-oa&key=yourtest-outdoora-ctiveapi&lang=en\"></script>\n\n\n </head>\n <body>\n\n <!-- container used by FlexView API -->\n <div class=\"oax-top-cont\"></div>\n\n\n <!-- and some lines of javascript inside a script tag -->\n <script type=\"text/javascript\">\n\n var conf = {\n frontendtype: \"tour\", // choose content type\n zoom: 11, // set initial zoom level\n center: [ 10.292, 47.546 ] // set initial map center\n };\n \n var fvp = oa.api.flexviewpage( conf );\n\n </script>\n </body>\n</html>\n```\n\n```js\ndata() {\n return {\n conf: {\n frontendtype: 'tour',\n zoom: 11,\n center: [10.292, 47.546]\n }\n }\n },\n head() {\n return {\n script: [\n {\n src: '//www.outdooractive.com/alpportal/oa_head.js?proj=api-dev-oa&key=yourtest-outdoora-ctiveapi&lang=en'\n },\n {\n body: true,\n fvp: this.oa.api.flexviewpage(this.conf) // attempt one\n fvp: () => {this.oa.api.flexviewpage(this.conf)} // attempt two\n }\n ]\n }\n }\n```\n\n```text\napi doesn't exist\n```\n\n```text\nvar fvp\n```\n\n```html\n<!DOCTYPE html>\n<html {{ HTML_ATTRS }}>\n <head {{ HEAD_ATTRS }}>\n {{ HEAD }}\n <!-- load Outdooractive Javascript API -->\n <script type=\"text/javascript\" src=\"//www.outdooractive.com/alpportal/oa_head.js?proj=api-dev-oa&key=yourtest-outdoora-ctiveapi&lang=en\"></script>\n\n </head>\n <body {{ BODY_ATTRS }}>\n {{ APP }}\n\n <!-- container used by FlexView API -->\n <div class=\"oax-top-cont\"></div>\n\n\n <!-- and some lines of javascript inside a script tag -->\n <script type=\"text/javascript\">\n\n var conf = {\n frontendtype: \"tour\", // choose content type\n zoom: 11, // set initial zoom level\n center: [ 10.292, 47.546 ] // set initial map center\n };\n \n var fvp = oa.api.flexviewpage( conf );\n\n </script>\n </body>\n</html>\n```\n\n```js\ndata() {\n return {\n conf: {\n frontendtype: 'tour',\n zoom: 11,\n center: [10.292, 47.546]\n }\n }\n},\nhead(){\n return {\n script: [\n {\n src: '//www.outdooractive.com/alpportal/oa_head.js?proj=api-dev-oa&key=yourtest-outdoora-ctiveapi&lang=en'\n },\n {\n type:'text/javascript',\n innerHTML: JSON.stringify(this.conf)\n }\n ]\n }\n}\n```\n\n```text\nindex.html\n```\n\n```text\nconf\n```\n\n```text\nhead()\n```\n\n```text\n<Script async src=\"https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXXX-X\"></Script>\n```\n\n```text\n<Script>\n // some JS code\n</Script>\n```\n\n```text\nScript\n```\n\n```text\nuseHead\n```\n\n```text\nScript\n```\n\n```text\nuseHead\n```\n\n```js\nhead: {\n ...\n script: [\n { src: '/js/script_name.js' } // load script in your static folder\n ]\n }\n```\n\n```js\n// ScriptTag.vue\n<script setup lang=\"ts\">\n defineProps({\n type: {\n type: String,\n default: 'text/javascript',\n required: false,\n },\n async: {\n type: String,\n default: undefined,\n required: false,\n },\n defer: {\n type: String,\n default: undefined,\n required: false,\n },\n });\n</script>\n\n<template>\n <Component \n :is=\"'script'\" \n :type=\"type\" \n :async=\"async ? async : undefined\"\n :defer=\"defer ? defer : undefined\"\n >\n <slot />\n </Component>\n</template>\n```\n\n```js\n<template>\n <ScriptTag async=\"true\">\n // Code here\n </ScriptTag>\n</template>\n```\n\n========================================\n\nComments:\n- does the `conf`/`fvp` same no matter what url/page is? Or different pages have different `conf`/`fvp`?\n- The link is broken, can you update it? nuxt.com/docs/examples/composables/use-head#usehead This is an example\n- Updated useHead link\n- There's no good reason for the downvote on this answer. See the link which is another SO answer with 14+ upvotes.","metadata":{"transformedAt":"2026-08-18T18:33:07.841Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":319,"estimatedTokens":1487}}128{"id":"stack-68415572","source":"stackoverflow","questionId":68415572,"title":"How to add 301 redirects to NUXT","tags":["nuxt.js"],"text":"Title: How to add 301 redirects to NUXT\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a NUXT project which i'm trying to add 301 redirect to. I've tried a few different approaches, but nothing works. If I go to the old URL I get a 404 page.\n\nWhats the best way to add redirects to a Nuxt project?\n\nAny help would be appreciated.\n\n```\nconst redirects =\n [\n { from: 'https://www. example.com/article/new-guidelines-new-normal-new-opportunities-new-working-environments', to: 'https://www. example.com' },\n { from: 'https://www. example.com/article/vetting-candidate-why-its-a-no-brainer', to: 'https://www. example.com' },\n { from: 'https://www. example.com/job-alerts', to: 'https://www. example.com' },\n { from: 'https://www. example.com/jobs', to: 'https://www. example.com' },\n { from: 'https://www. example.com/news', to: 'https://www. example.com' },\n { from: 'https://www. example.com/login', to: 'https://www. example.com' },\n { from: 'https://www. example.com/cv-upload', to: 'https://www. example.com/#submit-cv' },\n { from: 'https://www. example.com/expertise', to: 'https://www. example.com/our-expertise' }\n ]\n \n module.exports = function (req, res, next) {\n const redirect = redirects.find(r => r.from === req.url)\n if (redirect) {\n console.log(`redirect: ${redirect.from} => ${redirect.to}`)\n res.writeHead(301, { Location: redirect.to })\n res.end()\n } else {\n next()\n }\n }\n\n// nuxt.connig.js\n\n serverMiddleware: [\n { path: \"/api/redirects\", handler: \"~/api/redirects/index.js\" },\n ],\n```\n\n========================================\n\nTop Answer:\nFor **Nuxt 3** you can use the `routeRules` setting in your `nuxt.config.ts`.\n\n**nuxt.config.ts**\n\n```\nexport default defineNuxtConfig({\n routeRules: {\n \"/from\": {\n redirect: {\n to: \"/to\",\n statusCode: 301,\n },\n },\n },\n});\n```\n\nFor more config options see https://nitro.unjs.io/config/#routes\n\n========================================\n\nCode:\n```text\nconst redirects =\n [\n { from: 'https://www. example.com/article/new-guidelines-new-normal-new-opportunities-new-working-environments', to: 'https://www. example.com' },\n { from: 'https://www. example.com/article/vetting-candidate-why-its-a-no-brainer', to: 'https://www. example.com' },\n { from: 'https://www. example.com/job-alerts', to: 'https://www. example.com' },\n { from: 'https://www. example.com/jobs', to: 'https://www. example.com' },\n { from: 'https://www. example.com/news', to: 'https://www. example.com' },\n { from: 'https://www. example.com/login', to: 'https://www. example.com' },\n { from: 'https://www. example.com/cv-upload', to: 'https://www. example.com/#submit-cv' },\n { from: 'https://www. example.com/expertise', to: 'https://www. example.com/our-expertise' }\n ]\n \n module.exports = function (req, res, next) {\n const redirect = redirects.find(r => r.from === req.url)\n if (redirect) {\n console.log(`redirect: ${redirect.from} => ${redirect.to}`)\n res.writeHead(301, { Location: redirect.to })\n res.end()\n } else {\n next()\n }\n }\n\n// nuxt.connig.js\n\n serverMiddleware: [\n { path: \"/api/redirects\", handler: \"~/api/redirects/index.js\" },\n ],\n```\n\n```js\n// nuxt.config.js\nserverMiddleware: [{ \n path: '/',\n handler: './serverMiddleware.js'\n }]\n```\n\n```js\n// serverMiddleware.js\nexport default (req, res, next) => {\n // detect urls you'd like to redirect\n // call res.redirect(CODE, NEWURL)\n\n if (req.url === '/some-page/') {\n res.writeHead(301, { Location: 'redirect-page' });\n res.end();\n } else {\n next();\n }\n}\n```\n\n```text\n// nuxt.config.js\nredirect: [\n { from: '^/myoldurl', to: '/mynewurl', statusCode: 301 }\n]\n```\n\n```js\nexport default defineNuxtConfig({\n routeRules: {\n \"/from\": {\n redirect: {\n to: \"/to\",\n statusCode: 301,\n },\n },\n },\n});\n```\n\n```text\nrouteRules\n```\n\n```text\nnuxt.config.ts\n```\n\n========================================\n\nComments:\n- So you want for example, that `/jobs` redirects you to `/`? Does it need to be on the server side?\n- Thanks Braks, but just tried this and nothing happens when hitting the URL I want to redirect.\n- I updated my response, seems that I had a wrong api for the serverMiddleware in mind. Try the updated response out and let me know if that works for you. Edit: I didn't even notice that you literally did the exact same thing already, sorry :D Been switching between questions too much. What exactly is not working with your original implementation? (by the way you have some whitespaces in your routes? ** www .example **\n- Thanks for the help Braks. In the end using Nuxt Redirect Module did the tick!\n- You will need to add a call to `next()` in serverMiddleware.js for this code to work\n- Not sure why this got downvoted – this is correct for Nuxt 3. nuxt.com/docs/guide/concepts/rendering#hybrid-rendering\n- I am redirecting from my nuxt landing pages to my dashboard pages, which is a different project. Therefore I am ussing website/settings. How can I make it so that the query in the url doesn't go away?\n- Is it also possible to redirect multiple pages? For example /from/** to test.website/**\n- Note that Hybrid Rendering is not available when using nuxt generate.","metadata":{"transformedAt":"2026-08-18T18:33:07.841Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":161,"estimatedTokens":1297}}129{"id":"stack-50551158","source":"stackoverflow","questionId":50551158,"title":"How to attach axios / axios interceptor to Nuxt globally ?","tags":["vue.js","axios","nuxt.js"],"text":"Title: How to attach axios / axios interceptor to Nuxt globally ?\nTags: vue.js, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nhow would i go about attaching axios / axios interceptor globally to nuxt (so its available everywhere), same how i18n is attached ?\n\nThe idea is that i would like to have a global axios interceptor that every single request goes through that interceptor.\n\nThanks\n\n========================================\n\nTop Answer:\nIt's hidden in the documentation - https://nuxtjs.org/docs/2.x/directory-structure/plugins\n\nSee number 3 of the first photo:\n\n```\n// plugins/axios.js\nexport default function ({ $axios, redirect }) {\n $axios.onError(error => {\n if (error.response.status == 404) {\n redirect('/sorry')\n }\n })\n}\n```\n\nthen define this in nuxt.config.js\n\n```\nmodule.exports = {\n //....\n\n plugins: [\n '~/plugins/axios',\n ],\n\n //....\n};\n```\n\n========================================\n\nCode:\n```js\nimport Vue from 'vue';\nimport axios from 'axios';\n\naxios.interceptors.request.use((config) => {\n // Do something before request is sent\n return config;\n}, function (error) {\n // Do something with request error\n return Promise.reject(error);\n});\n\nVue.use(axios);\n```\n\n```js\nmodule.exports = {\n //....\n\n plugins: [\n '~/plugins/axios',\n ],\n\n //....\n};\n```\n\n```text\nimport axios from 'axios'\nconst instance = axios.create({\n baseURL: 'http://example.org' // if you have one\n})\n\n// Put all interceptors on this instance\ninstance.interceptors.response.use(r => r)\n\nexport default instance\n```\n\n```text\nimport request from './request'\n\nawait request.get('/endpoint')\n// or use promises\nrequest.get('/endpoint').then(data => data)\n```\n\n```text\nimport request from './request'\nglobal.request = request\n// use it:\nawait request.get('example.org')\n```\n\n```text\nVue.prototype.$request = request\n// in your component:\nthis.$request.get()\n```\n\n```text\nexport default function ({ $axios, app, redirect }) {\n $axios.onRequest(config => {\n config.params = config.params || {}; // get existing parameters\n config.params['lang'] = app.i18n.locale;\n })\n\n $axios.onError(error => {\n const code = parseInt(error.response && error.response.status)\n if (code === 400) {\n redirect('/400')\n }\n })\n}\n```\n\n```text\nmodule.exports = {\n plugins: [\n '~/plugins/axios'\n ]\n};\n```\n\n```text\n// plugins/axios.js\nexport default function ({ $axios, redirect }) {\n $axios.onError(error => {\n if (error.response.status == 404) {\n redirect('/sorry')\n }\n })\n}\n```\n\n```text\nmodule.exports = {\n //....\n\n plugins: [\n '~/plugins/axios',\n ],\n\n //....\n};\n```\n\n========================================\n\nComments:\n- id still have to import request module in every single component... is there a way to attach that to a global nuxt object ?\n- @rvsted yes you can, I've updated my answer accordingly but I don't suggest doing it, as the module import is just cleaner. You can also attach it to the vue instance by adding it to its prototype if you needed to.\n- Is there any way to access state from this plugin?\n- yes, you can import the store und use it `import store from '@/store/index';` `store.getters['user/name'];` in store you have to export getters, actions, etc `export const getters = { name: (state, getters) => {...} }`\n- why plugin? why not middleware","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":161,"estimatedTokens":838}}130{"id":"stack-72139221","source":"stackoverflow","questionId":72139221,"title":"How to use template refs in Nuxt 3","tags":["vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: How to use template refs in Nuxt 3\nTags: vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nIn Nuxt2 there were template $refs that you could access in `` with `this.$refs`\n\nI would like to know what is the Nuxt3 equivalent of this is.\n\nI need this to access the innerText of an element. I am not allowed to use `querySelector` or `getElementById` etc.\n\nThis is the way we write code. I can give html elements `ref=\"fooBar\"` but I can't access it with `this.$refs.fooBar` or even `this.$refs`.\n\n```\n\nimport { ref, computed } from 'vue';\n\nconst foo = ref('bar');\n\nfunction fooBar() {\n //Do stuff\n}\n\n //Html here\n\n```\n\n========================================\n\nCode:\n```html\n<script setup lang=\"ts\">\nimport { ref, computed } from 'vue';\n\nconst foo = ref('bar');\n\nfunction fooBar() {\n //Do stuff\n}\n</script>\n\n<template>\n //Html here\n</template>\n```\n\n```text\n<script>\n```\n\n```text\nthis.$refs\n```\n\n```text\nquerySelector\n```\n\n```text\ngetElementById\n```\n\n```text\nref=\"fooBar\"\n```\n\n```text\nthis.$refs.fooBar\n```\n\n```text\nthis.$refs\n```\n\n```html\n<script>\nexport default {\n mounted() {\n console.log('input', this.$refs['my-cool-div'])\n }\n}\n</script>\n\n<template>\n <div ref=\"my-cool-div\">\n hello there\n </div>\n</template>\n```\n\n```html\n<script setup>\nimport { useTemplateRef } from 'vue'\n\nconst myEl = useTemplateRef('myCoolDiv')\n\nconst clickMe = () => console.log(myEl)\n</script>\n\n<template>\n <button @click=\"clickMe\">show me the ref</button>\n <div ref=\"myCoolDiv\">\n hello there\n </div>\n</template>\n```\n\n========================================\n\nComments:\n- In this example `const foo = ref('bar');` is instead of `data() {return {foo:'bar'}}`\n- This is not at all how my code looks like anymore i thought that this was because of Nuxt3 but maybe because we work in TypeScript? We don’t use any lifecycle hooks anymore i’ve updated the question with my code.\n- Aaaah yes that works thanks for like the 8th time you safe my life. So this way of using refs is not a nuxt3 thing but just typescript? I'm new to both.\n- @MarnixElling this is actually a Vue3 (Composition API) thing: vuejs.org/api/composition-api-lifecycle.html#onmounted If you want to type it properly, here you go: vuejs.org/guide/typescript/…\n- As of Vue 3.5 `useTemplateRef` (vuejs.org/guide/essentials/template-refs#accessing-the-refs‌​) is the way to reference a html element or component","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":115,"estimatedTokens":602}}131{"id":"stack-64409416","source":"stackoverflow","questionId":64409416,"title":"NuxtJS: Disable console.log in production env","tags":["javascript","vue.js","nuxt.js"],"text":"Title: NuxtJS: Disable console.log in production env\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am looking for a way to disable `console.log()` for production env. Something like putting the below code to `nuxt.config.js` or `index.js`:\n\n```\nif (process.env.NODE_ENV !== \"development\") {\n console.log = () => {};\n}\n```\n\nI tried it, but it doesn't work. Any help would be appreciated.\n\nMy nuxt.config.js is here\nhttps://gist.github.com/somaria/9a2b0e06497d13a35fe9eee141a15d07\n\n========================================\n\nTop Answer:\nAs an alternative, this can also be done with Plugins.\n\nUnder `Plugins` folder, we can create a file called `disableLogs.js` which can look like so:\n\n```\n// plugins/disableLogs.js\n\nexport function disableLogs() {\n console.log = () => {};\n // or you can override any other stuff you want\n}\n\nprocess.env.NODE_ENV === \"production\" ? disableLogs() : null;\n```\n\nThen we can register this plugin to be used inside `nuxt.config.js`\n\n```\n// nuxt.config.js\nplugins: [\n { src: \"~/plugins/disableLogs.js\" },\n { src: \"~/plugins/any-other-plugin.js\"\n],\n```\n\nThis will run before instantiating the root Vue.js Application.\n\nThere are other things where you can configure it to run either client or server side, etc. More info here - https://nuxtjs.org/guide/plugins#vue-plugins\n\n========================================\n\nCode:\n```js\nif (process.env.NODE_ENV !== \"development\") {\n console.log = () => {};\n}\n```\n\n```text\nconsole.log()\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nindex.js\n```\n\n```js\n// nuxt.config.js\nexport default {\n build: {\n terser: {\n // https://github.com/terser/terser#compress-options\n terserOptions: {\n compress: {\n drop_console: true\n }\n }\n }\n }\n}\n```\n\n```text\nterser\n```\n\n```text\nbuild.terser.terserOptions\n```\n\n```js\n// plugins/disableLogs.js\n\nexport function disableLogs() {\n console.log = () => {};\n // or you can override any other stuff you want\n}\n\nprocess.env.NODE_ENV === \"production\" ? disableLogs() : null;\n```\n\n```js\n// nuxt.config.js\nplugins: [\n { src: \"~/plugins/disableLogs.js\" },\n { src: \"~/plugins/any-other-plugin.js\"\n],\n```\n\n```text\nPlugins\n```\n\n```text\ndisableLogs.js\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- You could try using `NUXT_ENV_` before your variable names during the build phase. Can you also your nuxt.config.js file?","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":130,"estimatedTokens":603}}132{"id":"stack-55759151","source":"stackoverflow","questionId":55759151,"title":"How to solve Maximum call stack size exceeded Error in nuxt.js","tags":["vue.js","vuex","nuxt.js"],"text":"Title: How to solve Maximum call stack size exceeded Error in nuxt.js\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get data from firebase using axios. I'm using vuex store to handle all my data .\n\nI've this two actions to get the data and store it : \n\n```\nnuxtServerInit(vuexContext, context) {\n return axios\n .get(\"https://nuxt-blog.firebaseio.com/posts.json\")\n .then(res => {\n const postsArray = [];\n for (const key in res.data) {\n postsArray.push({ ...res.data[key], id: key });\n }\n vuexContext.commit(\"setPosts\", postsArray);\n })\n .catch(e => context.error(e));\n },\n setPosts(vuexContext, posts) {\n vuexContext.commit(\"setPosts\", posts);\n }\n```\n\nI don't know what is wrong with this code but it gives me this errors :\n\nMaximum call stack size exceeded\n\nerrors on terminal\n\n========================================\n\nCode:\n```text\nnuxtServerInit(vuexContext, context) {\n return axios\n .get(\"https://nuxt-blog.firebaseio.com/posts.json\")\n .then(res => {\n const postsArray = [];\n for (const key in res.data) {\n postsArray.push({ ...res.data[key], id: key });\n }\n vuexContext.commit(\"setPosts\", postsArray);\n })\n .catch(e => context.error(e));\n },\n setPosts(vuexContext, posts) {\n vuexContext.commit(\"setPosts\", posts);\n }\n```\n\n```text\nres.data\n```\n\n========================================\n\nComments:\n- In my case, it was fixed by using the same name for both component `name: \"Sample\"` property and ``.\n- I received this error when introducing a new component into a template. Wrapping the component with Nuxt's `` cleared the error. I'll trace the actual culprit in the future.\n- Happened again. This time, I was calling a component inside itself. It causes recursion.\n- I've minimized the object and i get this error `Client network socket disconnected before secure TLS connection was established`\n- @AymanTarig no idea, too little info and thats not a place for it. If u have new issue and your current one solved, mark it as solved and open a new question with information","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":66,"estimatedTokens":533}}133{"id":"stack-63631069","source":"stackoverflow","questionId":63631069,"title":"What are types for input events in Vue","tags":["typescript","vue.js","nuxt.js"],"text":"Title: What are types for input events in Vue\nTags: typescript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhat are correct Typescript types for input events in Vue? When I use `Event` it is missing target value or key or files properties.\n\nLet's have an example for:\n\n```\n {}\" />\n {}\" />\n```\n\nIn React we have something like *ChangeEvent* which is generic and apply element specific types. How we do it in Vue?\n\n========================================\n\nTop Answer:\nThis works for me having a common text input, whilst the accepted answer produces a linter error for me:\n\nError: Unexpected token. Did you mean `{'}'}` or `}`?\n\n```\nconst onInput = (ev: Event) => {\n const { value = '' } = ev.target as HTMLInputElement;\n // ...\n};\n```\n\n========================================\n\nCode:\n```text\n<input @input=\"(e: MISSING_TYPE) => {}\" />\n<input @keypress=\"(e: MISSING_TYPE) => {}\" />\n```\n\n```text\nEvent\n```\n\n```text\n<input @keypress=\"handleKeypress\" />\n\nhandleKeypress(e: KeyboardEvent) { }\n```\n\n```text\n<input @input=\"handleInput\" />\n\nhandleInput(e: Event) { \n const target = (<HTMLInputElement>e.target)\n\n console.log(target.value)\n}\n```\n\n```text\nconst onInput = (ev: Event) => {\n const { value = '' } = ev.target as HTMLInputElement;\n // ...\n};\n```\n\n```js\nexport type VKeyboardEvent<T extends HTMLElement> = KeyboardEvent & {\n target: T;\n};\n```\n\n```js\nconst onKeyboardArrowDown = (evt: VKeyboardEvent<HTMLDivElement>) => {\n // Do something with a properly-typed target.\n const theParentOfMyDiv = evt.target.parentElement\n}\n```\n\n========================================\n\nComments:\n- Is KeyboardEvent what you're looking for? (Event > UIEvent > KeyboardEvent)\n- Thank you, KeyboardEvent looks good for keypress. What about input and e.target.value? Can we have any documentation on the list of these specific events like KeyboardEvent or we need to extract it from codebase?\n- `target` is on the `Event` type. I think you'd need to cast to something more specific to get value, i.e. (e.target).value\n- For docs, you have KeyboardEvent, the TypeScript types should correspond to this. You can inspect them yourself in lib.dom.d.ts\n- this works for me, though I had to cast the target as: `const target = e.target as HTMLInputElement`","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":86,"estimatedTokens":561}}134{"id":"stack-70643398","source":"stackoverflow","questionId":70643398,"title":"How to pass prop from page to layout","tags":["vue.js","nuxt.js","vue-props"],"text":"Title: How to pass prop from page to layout\nTags: vue.js, nuxt.js, vue-props\nSource: Stack Overflow\n\nQuestion:\nI currently have duplicated layout that the only difference is a prop I pass to a component:\n\ndefault.vue\n\n```\n\n \n \n \n \n \n \n \n```\n\nfront.vue\n\n```\n\n \n \n \n \n \n \n \n```\n\nIs there any way to pass that `light: true` from page to layout so I can use only `default.vue` layout?\n\nI know I could emit some event on mounted but would like to prevent using lifecycle hooks for this\n\n========================================\n\nCode:\n```html\n<template>\n <div class=\"page\">\n <SkipToContent />\n <Header />\n <Nuxt />\n <Footer />\n </div>\n </template>\n```\n\n```html\n<template>\n <div class=\"page\">\n <SkipToContent />\n <Header light=\"true\" />\n <Nuxt />\n <Footer />\n </div>\n </template>\n```\n\n```text\nlight: true\n```\n\n```text\ndefault.vue\n```\n\n```html\n<!-- components/CommonLayout.vue -->\n<template>\n <div class=\"page\">\n <SkipToContent />\n <Header :light=\"light\" />\n <Nuxt />\n <Footer />\n </div>\n</template>\n\n<script>\nexport default {\n props: {\n light: Boolean,\n }\n}\n</script>\n```\n\n```html\n<!-- layouts/default.vue -->\n<template>\n <CommonLayout />\n</template>\n```\n\n```html\n<!-- layouts/front.vue -->\n<template>\n <CommonLayout light />\n</template>\n```\n\n```text\nlight\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":107,"estimatedTokens":340}}135{"id":"stack-75575272","source":"stackoverflow","questionId":75575272,"title":"Nuxt instance unavailable when trying to run useRuntimeConfig in a file within utils directory during server side rendering (SSR)","tags":["javascript","vue.js","nuxt.js","server-side-rendering","nuxt3.js"],"text":"Title: Nuxt instance unavailable when trying to run useRuntimeConfig in a file within utils directory during server side rendering (SSR)\nTags: javascript, vue.js, nuxt.js, server-side-rendering, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a website in Nuxt 3 for frontend with SSR, and Laravel in the backend. In the Nuxt 3 project, I have an ApiBridge.js file in the utils directory that I use to organize API calls, set the base URL etc. Since starting the project, I've been running this with server side rendering turned off for my convenience, but when I try to run this with SSR on (Turned on in nuxt.config.js), I get a \"Nuxt instance unavailable\" error. I'm working on this project while learning Nuxt 3 on the go, so I might be missing something obvious.\n\n```\nimport axios from \"axios\";\n\nconst runtimeConfig = useRuntimeConfig()\n\nconst api = axios.create({\n baseURL: runtimeConfig?.API_BASE_URL,\n withCredentials: true,\n});\n\nconst apiBridge = {\n login: (info) => api.post('/login', {\n ...info,\n }),\n\n register: (info) => api.post('/register', {\n ...info,\n })\n\n /* .... */\n}\n\nexport default apiBridge;\n```\n\nWhy is this happening? Is this a bad way to do this? How to fix it? Why's it working with SSR turned off? Is it because of the auto imports? Thanks in advance!\n\nLooked around the web but found nothing useful.\n\nEDIT:\nnuxt.config.js as requested by a comment\n\n```\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n modules: [\n '@nuxtjs/tailwindcss',\n [\n '@pinia/nuxt',\n {\n autoImports: [\n // automatically imports `defineStore`\n 'defineStore', // import { defineStore } from 'pinia'\n // automatically imports `defineStore` as `definePiniaStore`\n ['defineStore', 'definePiniaStore'], // import { defineStore as definePiniaStore } from 'pinia'\n ],\n },\n ],\n ],\n tailwindcss: {\n configPath: './tailwind.config.js'\n },\n build: {\n\n },\n // ssr: false, // remove later\n runtimeConfig: {\n public: {\n BASE_URL: process.env.BASE_URL,\n API_BASE_URL: process.env.API_BASE_URL,\n }\n },\n})\n```\n\n========================================\n\nTop Answer:\nYou can also resolve this by accessing the runtime configuration with:\n\n```\nuseNuxtApp().$config\n```\n\nI had the exact same error as you except I was trying to access useRuntimeConfig() in a plugin and this resolved it.\n\n========================================\n\nCode:\n```text\nimport axios from \"axios\";\n\nconst runtimeConfig = useRuntimeConfig()\n\nconst api = axios.create({\n baseURL: runtimeConfig?.API_BASE_URL,\n withCredentials: true,\n});\n\n\nconst apiBridge = {\n login: (info) => api.post('/login', {\n ...info,\n }),\n\n register: (info) => api.post('/register', {\n ...info,\n })\n\n /* .... */\n}\n\nexport default apiBridge;\n```\n\n```text\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n modules: [\n '@nuxtjs/tailwindcss',\n [\n '@pinia/nuxt',\n {\n autoImports: [\n // automatically imports `defineStore`\n 'defineStore', // import { defineStore } from 'pinia'\n // automatically imports `defineStore` as `definePiniaStore`\n ['defineStore', 'definePiniaStore'], // import { defineStore as definePiniaStore } from 'pinia'\n ],\n },\n ],\n ],\n tailwindcss: {\n configPath: './tailwind.config.js'\n },\n build: {\n\n },\n // ssr: false, // remove later\n runtimeConfig: {\n public: {\n BASE_URL: process.env.BASE_URL,\n API_BASE_URL: process.env.API_BASE_URL,\n }\n },\n})\n```\n\n```text\nimport axios from \"axios\"\n\nexport const useApiBridge = () => {\n const runtimeConfig = useRuntimeConfig()\n\n const api = axios.create({\n baseURL: runtimeConfig.API_BASE_URL,\n withCredentials: true,\n });\n\n return { \n login: (info) => api.post('/login', {\n ...info,\n }),\n\n register: (info) => api.post('/register', {\n ...info,\n })\n }\n}\n```\n\n```text\nconst apiBridge = useApiBridge()\n```\n\n```text\nuseRuntimeConfig()\n```\n\n```text\nuseRuntimeConfig()\n```\n\n```text\nasyncData()\n```\n\n```text\nfetch()\n```\n\n```text\nAPI_BASE_URL\n```\n\n```text\nApiBridge\n```\n\n```text\nnuxtServerInit()\n```\n\n```text\n.env\n```\n\n```text\nprocess.env\n```\n\n```text\nuseRuntimeConfig()\n```\n\n```text\nuseNuxtApp().$config\n```\n\n```text\nnpm audit fix\n```\n\n========================================\n\nComments:\n- Please add your `nuxt.config` file\n- useRuntimeConfig() is what they call a composable in Nuxt 3. Your answer did not help unfortunately. You can't use process.env like that in Nuxt 3 from what I'm aware. Nuxt 3 doesn't have nuxtServerInit either (I've checked the docs, didn't find it).\n- I'm using it in a clientside plugin and apparently the whole point of runtimeconfig is to avoid env variables leaking?\n- This is part of the solution for me. Now I need to find a way to run your `useApiBridge` in a middleware or a plugin. When I try to do it I get \"Nuxt instance unavailable\" error again 😩","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":227,"estimatedTokens":1274}}136{"id":"stack-63246744","source":"stackoverflow","questionId":63246744,"title":"nuxt.js hot-reload is slow","tags":["nuxt.js"],"text":"Title: nuxt.js hot-reload is slow\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to know if it is normal that nuxt takes 2 or 3 seconds to make the hot reload changes?\nFor example with Gatsby the Hot Reloads are instantaneous. I missed something?\n\nHere is my nuxt build config:\n\n```\nbuild: {\n parallel: true,\n cache: true,\n extractCSS: process.env.NODE_ENV === 'production',\n optimizeCSS: process.env.NODE_ENV === 'production',\n transpile: ['vue-intersect'],\n},\n```\n\n========================================\n\nTop Answer:\nI am happy to report that after manually importing about 300 components in approximately 40 pages for about 15 hours, the HMR (Hot Module Replacement) is slower. It has added approximately 100ms on an M1 computer and around 200-300ms on an Intel computer. Therefore, setting \"components: false\" does not make the hot reload faster.\n\n========================================\n\nCode:\n```text\nbuild: {\n parallel: true,\n cache: true,\n extractCSS: process.env.NODE_ENV === 'production',\n optimizeCSS: process.env.NODE_ENV === 'production',\n transpile: ['vue-intersect'],\n},\n```\n\n```text\n...\n// change to false, or remove this config.\ncomponents: true\n...\n```\n\n========================================\n\nComments:\n- If you disable parallel and transpile, the speed is increased? Can you provide us your modules session and buildModules and plugins too? your build have something else? Verify if you have a property called components: true. If the components is true, you will import all pages and components every reload.\n- @HenriqueVanKlaveren I have disabled parallel and transpile but it's the same speed :(\n- thanks it's that but, now I have to create all the component imports.\n- yeh, you need, but think this cenario: You have one component, and inside this component you have a lot of child component. in this case, you dont need import all the child component in the project context, you need import only the parent component. For a small projects this maybe doesn't matter, but when you have a many many child, subchild component, this is the best way to do it. Nice thats work for you. I'm happy to help you.\n- Wow thanks, my builds were taking around 20-30 seconds on each hot reload. After changing components to false it takes less than one second !","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":53,"estimatedTokens":575}}137{"id":"stack-61425153","source":"stackoverflow","questionId":61425153,"title":"Loading custom fonts in Nuxt/Tailwind Project","tags":["nuxt.js","tailwind-css"],"text":"Title: Loading custom fonts in Nuxt/Tailwind Project\nTags: nuxt.js, tailwind-css\nSource: Stack Overflow\n\nQuestion:\nHi everybody and sorry my english.\n\nI have created a nuxt.js project with Tailwind. I´d like to custom my font family, so I downloaded some font files from Google Fonts. I have been reading Tailwind docs, but i can´t understand where do i have to place the font files and how to config Tailwind for loading the files.\n\nI´d be very gratefull if somebody could help me.\n\n========================================\n\nTop Answer:\nNuxt 2.12 and Tailwind 1.4.0 (assume you're using @nuxtjs/tailwind):\n\ntailwind.css:\n\n```\n/* purgecss start ignore */\n@import 'tailwindcss/base';\n@import 'tailwindcss/components';\n/* purgecss end ignore */\n@import 'tailwindcss/utilities';\n\n/* add fonts here */\n@import '~assets/css/fonts';\n```\n\nfonts.css:\n\n```\n@font-face {\n font-family: Underground;\n font-weight: 400;\n src: url('~assets/fonts/Roboto.woff2') format('woff2'),\n url('~assets/fonts/Roboto.woff') format('woff');\n}\n```\n\nAnd in tailwind.config.js:\n\n```\nmodule.exports = {\n theme: {\n fontFamily: {\n roboto: ['Roboto']\n }\n },\n variants: {},\n plugins: []\n}\n```\n\nThen you can use this font globally, in your default.vue layout:\n\n```\n\n \n \n \n\n```\n\nBTW, static is not for assets, like fonts, it's for files, like robots.txt, sitemap.xml\n\n========================================\n\nCode:\n```css\n@include font-face( KapraNeuePro, '~/assets/fonts/KapraNeueProFamily/Kapra-Neue-Pro-Regular', 400, normal, otf);\n@include font-face( KapraNeuePro, '~/assets/fonts/KapraNeueProFamily/Kapra-Neue-Pro-Medium', 600, medium, otf);\n```\n\n```js\nmodule.exports = {\n theme: {\n fontFamily: {\n sans: [\"KapraNeuePro\"],\n serif: [\"KapraNeuePro\"],\n mono: [\"KapraNeuePro\"],\n display: [\"KapraNeuePro\"],\n body: [\"KapraNeuePro\"]\n },\n variants: {},\n plugins: []\n }\n};\n```\n\n```text\nnpm run build\n```\n\n```text\nfonts\n```\n\n```text\nassets\n```\n\n```text\n~/css/tailwind.css\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nfont-family\n```\n\n```text\n@import 'tailwindcss/base';\n@import 'tailwindcss/components';\n@import 'tailwindcss/utilities';\n\n@font-face {\n font-family: 'Roboto';\n font-weight: 700;\n src: url('/fonts/Roboto/Roboto-Bold.ttf') format('truetype');\n}\n@font-face {\n font-family: 'OpenSans';\n font-weight: 500;\n src: url('/fonts/OpenSans/OpenSans-Medium.ttf') format('truetype');\n}\n```\n\n```text\ntheme: {\n extend: {\n fontFamily: {\n heading: ['Roboto', 'sans-serif'],\n body: ['OpenSans', 'sans-serif']\n }\n }\n}\n```\n\n```css\n/* purgecss start ignore */\n@import 'tailwindcss/base';\n@import 'tailwindcss/components';\n/* purgecss end ignore */\n@import 'tailwindcss/utilities';\n\n/* add fonts here */\n@import '~assets/css/fonts';\n```\n\n```css\n@font-face {\n font-family: Underground;\n font-weight: 400;\n src: url('~assets/fonts/Roboto.woff2') format('woff2'),\n url('~assets/fonts/Roboto.woff') format('woff');\n}\n```\n\n```js\nmodule.exports = {\n theme: {\n fontFamily: {\n roboto: ['Roboto']\n }\n },\n variants: {},\n plugins: []\n}\n```\n\n```js\n<template>\n <div class=\"container mx-auto font-roboto\">\n <nuxt />\n </div>\n</template>\n```\n\n```js\ngoogleFonts: {\n families: {\n 'Architects Daughter': true,\n // or:\n // Lato: [100, 300],\n // Raleway: {\n // wght: [100, 400],\n // ital: [100]\n // },\n },\n },\n```\n\n```js\nfontFamily: {\n handwritten: ['Architects Daughter'],\n },\n```\n\n```html\n<h2 class=\"font-handwritten\">\n This is a custom font\n </h2>\n```\n\n```text\nyarn add --dev @nuxtjs/google-fonts\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ntailwind.config.js\n```\n\n========================================\n\nComments:\n- If anyone else is confused by this, nuxtjs/tailwindcss no longer generates a tailwind.css file by default: github.com/nuxt-community/tailwindcss-module/issues/253","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":224,"estimatedTokens":975}}138{"id":"stack-58465065","source":"stackoverflow","questionId":58465065,"title":"How do I change the URL of the page in Nuxt SSR mode without reloading the whole page?","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: How do I change the URL of the page in Nuxt SSR mode without reloading the whole page?\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\n- I am trying to build a Master Detail View where list and detail are shown side by side on desktop but on different pages on mobile as shown in the image below\n\n- I may have between 500 to 10000 items on the list to display\n\n- I simulated both approaches with 10000 items, feel free to change the number in server/app.js file\n\nhttps://i.sstatic.net/cL4Gv.png\n\n- When I click on an item in the list, I want the URL to change so that I click back button I go to the previous button.\n\n- The page should not reload for doing this and it should be in SSR mode\n\n**What have I tried?**\n\n**Approach 1 Dynamic Routes**\n\nInside pages folder, I put an articles folder and _id.vue file and added a nuxt-link\n\nThis setup is VERY VERY slow, takes 20 seconds for the summary to change \n\nHere is Approach 1 on CodeSandbox\n\n**Approach 2 Custom @nuxtjs/router module with push**\n\nInstead of the default router, I tried using the custom @nuxtjs/module\n\nLinks are selected much much faster in this approach and the URL is also changing\n\nHowever if I click on item 4877, it reloads the page and the scrollbar goes back to the top of the page?\n\nHow do I keep the scrollbar wherever it is or PREVENT reloading the page?\n\nHere is Approach 2 on CodeSandbox with Custom Router\n\nSimple Question\n\n- What do I do in SSR mode to change the URL as I select an item in the list without reloading the page?\n\n- Which approach is better?\n\n========================================\n\nTop Answer:\nyou can try to split page in 2 parts: \"/pages/arcticles.vue\" and \"/pages/arcticles/_id.vue\".\nThis approach similar with your first, list not reload list. \nWith speed i don't know what to do. Resulting page size is 15Mb.\n\narcticles.vue \n\n```\n\n \n \n \n \n \n Article {{ i.title }}\n \n \n \n \n \n \n\n```\n\narcticles/_id.vue\n\n```\n\n \n Article {{ $route.params.id }}\n \n\n```\n\n========================================\n\nCode:\n```js\naddHashToLocation(params) {\n history.pushState(\n {},\n null,\n this.$route.path + '#' + encodeURIComponent(params)\n )\n}\n```\n\n```js\n// main component\ncreated() {\n // event fire when pushState\n this.$nuxt.$on('pushState', params => {\n // do your logic with params\n })\n},\nbeforeDestroy() {\n this.$nuxt.$off('pushState')\n},\n...\n\n// Where there are history.pushState\nthis.$nuxt.$emit('pushState', params)\n```\n\n```text\nhistory.pushState\n```\n\n```text\naddHashToLocation('/my/new/path')\n```\n\n```text\nhistory.replaceState\n```\n\n```text\n<template>\n <div class=\"root\">\n <div class=\"left\">\n <ul>\n <li v-for=\"i in sortedArticles\" :key=\"i.feedItemId\">\n <nuxt-link :to=\"'/articles/' + i.feedItemId\">\n Article {{ i.title }}\n </nuxt-link>\n </li>\n </ul>\n </div>\n <nuxt-child class=\"right\"></nuxt-child>\n </div>\n</template>\n```\n\n```text\n<template>\n <div>\n Article {{ $route.params.id }}\n </div>\n</template>\n```\n\n========================================\n\nComments:\n- note to self looking at this after 10 years: there are 3 approaches to achieve this and each of them is covered in detail on my other post here stackoverflow.com/questions/68313593/…\n- upvoted! the only issue is that i cannot find out which id was selected anymore, $route.params.id is undefined, i guess this is what you were trying to say by vue router doesnt know url has changed, is there any way to get the id that was selected, also when moving back and forth, it doesnt scroll to the desired item\n- Yes, $route.params doesn't reflect url after pushState. So, you have to pass data logic in a different way. You can use the store if you already have business logic here, but you can also use custom router events. I will edit my answer to explain that...","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":154,"estimatedTokens":957}}139{"id":"stack-50048103","source":"stackoverflow","questionId":50048103,"title":"Place to initialize Firebase in Nuxt.js app","tags":["firebase","nuxt.js"],"text":"Title: Place to initialize Firebase in Nuxt.js app\nTags: firebase, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm writing a web app with `Nuxt.js` and `Firebase`. In which file do I need to initialize the `Firebase`? In other words, where to put this code snippet?\n\n```\nvar config = {\n apiKey: \"xxxxxxxxxx\",\n authDomain: \"xxxxxxxxx.firebaseapp.com\",\n databaseURL: \"https://xxxxxxxx.firebaseio.com\",\n projectId: \"xxxxxxxxx\",\n storageBucket: \"xxxxxxxxxxx.appspot.com\",\n messagingSenderId: \"xxxxxxxxxx\"\n};\nfirebase.initializeApp(config);\n```\n\n========================================\n\nTop Answer:\nAs written in fireship.io example:\n\nSeems like the correct approach to connecting to firebase within Nuxt 3 `/server` is creating a file in `/server/utils`.\n\n`FIRESTORE_SECRET` env variable contains the secret json given by firestore.\n\n`server/utils/firebase.ts`\n\n```\nimport { initializeApp, cert } from 'firebase-admin/app'\nimport { getFirestore } from 'firebase-admin/firestore'\n\nif (!process.env.FIRESTORE_SECRET) {\n throw new Error('Firestore secret not found in runtime config')\n}\n\nexport const app = initializeApp({\n credential: cert(JSON.parse(process.env.FIRESTORE_SECRET))\n})\n\nexport const db = getFirestore()\n```\n\nHere is an example of using the database in a server api route:\n\n```\nimport { db } from '../utils/firebase'\n\nexport default defineEventHandler(async (event) => {\n\n db.collection('users').doc('user_id').create({\n age: 16\n })\n }\n\n})\n```\n\n========================================\n\nCode:\n```text\nvar config = {\n apiKey: \"xxxxxxxxxx\",\n authDomain: \"xxxxxxxxx.firebaseapp.com\",\n databaseURL: \"https://xxxxxxxx.firebaseio.com\",\n projectId: \"xxxxxxxxx\",\n storageBucket: \"xxxxxxxxxxx.appspot.com\",\n messagingSenderId: \"xxxxxxxxxx\"\n};\nfirebase.initializeApp(config);\n```\n\n```text\nNuxt.js\n```\n\n```text\nFirebase\n```\n\n```text\nFirebase\n```\n\n```text\nimport firebase from 'firebase'\nimport 'firebase/firestore' //if use firestore\n\nif (!firebase.apps.length) {\n firebase.initializeApp({\n apiKey: \"xxx\",\n authDomain: \"xxx\",\n databaseURL: \"xxx\",\n projectId: \"xxx\",\n storageBucket: \"xxx\",\n messagingSenderId: \"xxx\"\n })\n}\n\nfirebase.firestore().settings({ timestampsInSnapshots: true })\n\nconst db = firebase.firestore()\nconst storage = firebase.storage() //if use storage\n\nexport { storage, db }\n```\n\n```text\nimport { db } from '~/plugins/firebase.js'\n\ndata() {\n return {\n users: []\n }\n},\nmounted() {\n db.collection(\"users\").get().then((querySnapshot) => {\n this.users = querySnapshot.docs.map(doc =>\n Object.assign({ id: doc.id }, doc.data())\n )\n })\n}\n```\n\n```text\nimport { initializeApp, cert } from 'firebase-admin/app'\nimport { getFirestore } from 'firebase-admin/firestore'\n\n\nif (!process.env.FIRESTORE_SECRET) {\n throw new Error('Firestore secret not found in runtime config')\n}\n\nexport const app = initializeApp({\n credential: cert(JSON.parse(process.env.FIRESTORE_SECRET))\n})\n\nexport const db = getFirestore()\n```\n\n```text\nimport { db } from '../utils/firebase'\n\nexport default defineEventHandler(async (event) => {\n\n db.collection('users').doc('user_id').create({\n age: 16\n })\n }\n\n})\n```\n\n```text\n/server\n```\n\n```text\n/server/utils\n```\n\n```text\nFIRESTORE_SECRET\n```\n\n```text\nserver/utils/firebase.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":171,"estimatedTokens":819}}140{"id":"stack-57666738","source":"stackoverflow","questionId":57666738,"title":"Vuex Classic mode for store/ is deprecated and will be removed in Nuxt 3","tags":["vue.js","vuex","nuxt.js"],"text":"Title: Vuex Classic mode for store/ is deprecated and will be removed in Nuxt 3\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have below files and could not find the reason for warning \"Classic mode for store/ is deprecated and will be removed in Nuxt 3\". Everything works fine just getting that annoying warning.\n\n***modules/data.js*** file in store of nuxt.js.\n\n```\nconst state = () => ({\n loadedPosts: []\n });\n\n const mutations = {\n setPosts(state, posts){\n state.loadedPosts = posts;\n }\n };\n\n const actions = {\n setPosts(vuexContext, posts){\n vuexContext.commit('setPosts', posts);\n }\n };\n\n const getters = {\n loadedPosts(state){\n return state.loadedPosts;\n }\n };\n\n export default {\n state,\n actions,\n getters,\n mutations\n };\n```\n\n***index.js*** file in store of nuxt.js.\n\n```\nimport Vuex from 'vuex';\nimport data from \"~/store/modules/data\";\n\nconst createStore = () => {\n return new Vuex.Store({\n modules: {\n data: {\n namespaced: true,\n ...data\n }\n }\n });\n};\n\nexport default createStore;\n```\n\n========================================\n\nTop Answer:\nIf it seems to you that everything has been done as per Nuxt docs but you still see the «Classic mode is deprecated» warning, the following may help:\n\n- Go to the directory where the built files are, i.e. `dist`\n\n- Open store.js\n\n- See the following piece of code:\n\n```\nif (typeof store === 'function') {\n return console.warn('Classic mode for store/ is deprecated and will be removed in Nuxt 3.')\n}\n```\n\n- Check what is being exported from your store/index.?s — is it a function? That's where the warning comes from. Fix it by exporting an object.\n\n========================================\n\nCode:\n```text\nconst state = () => ({\n loadedPosts: []\n });\n\n const mutations = {\n setPosts(state, posts){\n state.loadedPosts = posts;\n }\n };\n\n const actions = {\n setPosts(vuexContext, posts){\n vuexContext.commit('setPosts', posts);\n }\n };\n\n const getters = {\n loadedPosts(state){\n return state.loadedPosts;\n }\n };\n\n export default {\n state,\n actions,\n getters,\n mutations\n };\n```\n\n```text\nimport Vuex from 'vuex';\nimport data from \"~/store/modules/data\";\n\nconst createStore = () => {\n return new Vuex.Store({\n modules: {\n data: {\n namespaced: true,\n ...data\n }\n }\n });\n};\n\nexport default createStore;\n```\n\n```text\nexport const state = () => ({\n loadedPosts: []\n});\n\nexport const mutations = {\n setPosts(state, posts){\n state.loadedPosts = posts;\n }\n};\n\nexport const actions = {\n setPosts(vuexContext, posts){\n vuexContext.commit('setPosts', posts);\n }\n};\n\nexport const getters = {\n loadedPosts(state){\n return state.loadedPosts;\n }\n};\n```\n\n```text\nthis.$store.data.loadedPosts\n```\n\n```text\nthis.$store.commit('data/setPosts', [{id: '1',...}, {id: '2',...}]);\n```\n\n```text\nthis.$store.dispatch('data/setPosts', [{id: '1',...}, {id: '2',...}]);\n```\n\n```text\nthis.$store.getters['data/loadedPosts'];\n```\n\n```text\nif (typeof store === 'function') {\n return console.warn('Classic mode for store/ is deprecated and will be removed in Nuxt 3.')\n}\n```\n\n```text\ndist\n```\n\n========================================\n\nComments:\n- `...getters['data/loadedPosts']` / `...dispatch('data/setPosts')` - Mr.Stark I am not feeling well.. I mean seriouslly this is an awfull syntax.. But you're 100% right that's the new deal with nuxt, big mistake..\n- another way is to create `store/data/[actions.js, getters.js, mutations.js, state.js]`, so nuxt will use \"data\" folder as a module.\n- Just can't need create index.js","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":187,"estimatedTokens":908}}141{"id":"stack-61697598","source":"stackoverflow","questionId":61697598,"title":"[Nuxt.JS]access the $auth object in the context from plugin js","tags":["axios","nuxt.js"],"text":"Title: [Nuxt.JS]access the $auth object in the context from plugin js\nTags: axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to access the $auth object in the context from the js defined under 'plugins/', but I can't.\n\nhttps://auth.nuxtjs.org/api/auth.html#auth\n\n This module globally injects $auth instance, meaning that you can access it anywhere using this.$auth. For plugins, asyncData, fetch, nuxtServerInit and Middleware, you can access it from context.$auth\n\nIt is described above, but my code (axios-interceptor.js) cannot access $auth from context (it is undefined).\nWhat does it take to be able to access it?\n\n### plugins/axios-interceptor.js\n\n```\nexport default function (context) {\n const { $axios, route, redirect } = context\n\n $axios.interceptors.response.use(\n function (response) {\n return response\n },\n function (error) {\n const code = parseInt(error.response && error.response.status)\n const thisRoutePath = route.path\n\n if ([401, 403].includes(code)) {\n if (thisRoutePath !== '/') {\n redirect('/?login')\n }\n }\n return Promise.reject(error)\n }\n )\n}\n```\n\n### nuxt.config.js\n\n```\nexport default {\n plugins: [\n '@/plugins/axios-interceptor.js'\n ],\n\n modules: [\n '@nuxtjs/axios',\n '@nuxtjs/proxy',\n '@nuxtjs/auth'\n ],\n axios: {\n baseURL: BASE_URL\n },\n auth: {\n cookie: false,\n autoFetchUser: false,\n redirect: {\n login: '/login',\n logout: '/login',\n callback: '/callback',\n home: '/home'\n },\n strategies: {\n local: {\n endpoints: {\n login: { url: BACKEND_API_PATH_BASE + '/api/v1/login/', method: 'post', propertyName: 'token' },\n user: { url: BACKEND_API_PATH_BASE + '/api/v1/users/me', method: 'get', propertyName: false },\n logout: false\n },\n },\n }\n },\n router: {\n middleware: [\n 'auth'\n ]\n },\n```\n\nThe reason I want to access $auth in `axios-interceptor.js` is that I want to execute $auth.logout() in the `if ([401, 403].includes(code)) {` block and remove the token.\n\n========================================\n\nCode:\n```js\nexport default function (context) {\n const { $axios, route, redirect } = context\n\n $axios.interceptors.response.use(\n function (response) {\n return response\n },\n function (error) {\n const code = parseInt(error.response && error.response.status)\n const thisRoutePath = route.path\n\n if ([401, 403].includes(code)) {\n if (thisRoutePath !== '/') {\n redirect('/?login')\n }\n }\n return Promise.reject(error)\n }\n )\n}\n```\n\n```js\nexport default {\n plugins: [\n '@/plugins/axios-interceptor.js'\n ],\n\n modules: [\n '@nuxtjs/axios',\n '@nuxtjs/proxy',\n '@nuxtjs/auth'\n ],\n axios: {\n baseURL: BASE_URL\n },\n auth: {\n cookie: false,\n autoFetchUser: false,\n redirect: {\n login: '/login',\n logout: '/login',\n callback: '/callback',\n home: '/home'\n },\n strategies: {\n local: {\n endpoints: {\n login: { url: BACKEND_API_PATH_BASE + '/api/v1/login/', method: 'post', propertyName: 'token' },\n user: { url: BACKEND_API_PATH_BASE + '/api/v1/users/me', method: 'get', propertyName: false },\n logout: false\n },\n },\n }\n },\n router: {\n middleware: [\n 'auth'\n ]\n },\n```\n\n```text\naxios-interceptor.js\n```\n\n```text\nif ([401, 403].includes(code)) {\n```\n\n```js\nexport default {\n // plugins: [\n // '@/plugins/axios-interceptor.js' ########### REMOVE ###########\n // ],\n :\n (Ommit)\n :\n auth: {\n :\n (Ommit)\n :\n plugins: [\n '@/plugins/axios-interceptor.js' // ########### ADD ###########\n ]\n },\n (Ommit)\n :\n}\n```\n\n========================================\n\nComments:\n- I can see that the $auth object is not found in the context on the second line of the `axios-interceptor.js` above. I checked by looking at the contents of the context with Chrome's dev tool.\n- thanks for this! I would have never think of that. it works.\n- For some reason when I use Axios in the `auth` plugins the interceptors don't work anymore...\n- This works just fine, and the good stuff is that I don't need to set the access token to my other axios instances by myself.","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":185,"estimatedTokens":1024}}142{"id":"stack-60411436","source":"stackoverflow","questionId":60411436,"title":"NuxtJS Page is created twice","tags":["vue.js","nuxt.js","server-side-rendering"],"text":"Title: NuxtJS Page is created twice\nTags: vue.js, nuxt.js, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nI am currently facing an Issue in **NuxtJS** where a **method is called twice** and a request is therefore sent twice.\n\nThis happens in a **page** and the method which is called twice is **created**().\n\nI open the page with a **parameter** like:\n\n```\nhttp://localhost:3000/mypage?token=123123123\n```\n\nAnd in the created() Method of the page I call a store dispatch.\n\n```\ncreated() {\n if (this.token === undefined || this.token === null) {\n this.$router.push('/login')\n } else {\n console.log('called created() and sent dispatch')\n this.$store.dispatch('thirdPartyLogin', {\n token: this.token\n })\n }\n},\n```\n\nThe token is parsed via the data property:\n\n```\ndata() {\n return {\n token: this.$nuxt.$route.query.token\n }\n},\n```\n\nThe problem with this is that it is a One Time Token, which means that it is invalid after one use. So after the second call no more success of the request can take place.\n\n**Why is the page created twice or created() called twice?**\n\nhttps://i.sstatic.net/f49Up.png\n\n========================================\n\nTop Answer:\nThis is how it works:\n\nNuxt.js runs `created()` once on the server side then on the client side.\n\nThe `Nuxt SSR` shows the `console.log` message of your server and the second `console.log` is the message on the client side.\n\nYou have 2 Options:\n\nRun this on the serverside:\n\nWrap it in:\n\n```\nif(process.server){\n }\n```\n\nOr run it once on the client side:\n\n```\nif(!process.server){\n }\n```\n\n========================================\n\nCode:\n```text\nhttp://localhost:3000/mypage?token=123123123\n```\n\n```js\ncreated() {\n if (this.token === undefined || this.token === null) {\n this.$router.push('/login')\n } else {\n console.log('called created() and sent dispatch')\n this.$store.dispatch('thirdPartyLogin', {\n token: this.token\n })\n }\n},\n```\n\n```js\ndata() {\n return {\n token: this.$nuxt.$route.query.token\n }\n},\n```\n\n```text\ncreated(){\n if(process.client){\n //...your action here\n }\n}\n```\n\n```text\nprocess.client\n```\n\n```text\nif(process.server){\n }\n```\n\n```text\nif(!process.server){\n }\n```\n\n```text\ncreated()\n```\n\n```text\nNuxt SSR\n```\n\n```text\nconsole.log\n```\n\n```text\nconsole.log\n```\n\n========================================\n\nComments:\n- see this link stackoverflow.com/questions/60199338/…","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":143,"estimatedTokens":597}}143{"id":"stack-61930969","source":"stackoverflow","questionId":61930969,"title":"Detecting Server Side Rendering in Nuxt.js","tags":["javascript","vue.js","nuxt.js","server-side-rendering"],"text":"Title: Detecting Server Side Rendering in Nuxt.js\nTags: javascript, vue.js, nuxt.js, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nI have a Nuxt.js app that uses Server Side Rendering. However in one of my pages I need to detect if it's SSR for a toggle of one of the components. What are some possible ways of creating an `isSSR` flag?\n\n========================================\n\nCode:\n```text\nisSSR\n```\n\n```text\nprocess.server\n```\n\n```text\nserver\n```\n\n```text\nclient\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.842Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":25,"estimatedTokens":121}}144{"id":"stack-54027290","source":"stackoverflow","questionId":54027290,"title":"Nuxt: displaying local image from static folder","tags":["javascript","node.js","vue.js","nuxt.js"],"text":"Title: Nuxt: displaying local image from static folder\nTags: javascript, node.js, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nhttps://i.sstatic.net/AD4NT.png\n\nI'm getting started with nuxt. My static folder is in the screenshot. I've been trying to https://nuxtjs.org/guide/assets/#static\n\nI've got a vuetify carousel component that was working fine with urls as the src. Now I want to try to serve local static files. I tried:\n\n```\n\n \n \n \n\n \n\nexport default {\n data () {\n return {\n items: [\n {\n src: '/static/52lv.PNG'\n },\n {\n src: 'https://cdn.vuetifyjs.com/images/carousel/sky.jpg'\n },\n {\n src: 'https://cdn.vuetifyjs.com/images/carousel/bird.jpg'\n },\n {\n src: 'https://cdn.vuetifyjs.com/images/carousel/planet.jpg'\n }\n ]\n }\n }\n}\n\n```\n\nbut now when I run the dev server I get a blank screen for that image of the carousel . The other images with urls work fine.\n\nInspecting the blank element in the browser, I see:\n\nhttps://i.sstatic.net/0fV89.png\n\nHow can I display this image?\n\n========================================\n\nTop Answer:\nIn addition to this question, if we would have it in '~assets/images/521v.PNG' ?\n\nInstead of doing this\n\n```\nexport default { data () {\n return {\n items: [\n {\n src: '/static/52lv.PNG'\n },\n```\n\nDo this\n\n```\nsrc: `${require(`~assets/images/521v.PNG`)}`\n```\n\nand you would use it like this:\n\n```\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <v-carousel>\n <v-carousel-item v-for=\"(item,i) in items\" :key=\"i\" :src=\"item.src\"></v-carousel-item>\n </v-carousel>\n</template>\n\n\n <script>\n\nexport default {\n data () {\n return {\n items: [\n {\n src: '/static/52lv.PNG'\n },\n {\n src: 'https://cdn.vuetifyjs.com/images/carousel/sky.jpg'\n },\n {\n src: 'https://cdn.vuetifyjs.com/images/carousel/bird.jpg'\n },\n {\n src: 'https://cdn.vuetifyjs.com/images/carousel/planet.jpg'\n }\n ]\n }\n }\n}\n</script>\n```\n\n```text\nsrc: '/52lv.PNG'\n```\n\n```text\nexport default { data () {\n return {\n items: [\n {\n src: '/static/52lv.PNG'\n },\n```\n\n```text\nsrc: `${require(`~assets/images/521v.PNG`)}`\n```\n\n```text\n<img :src=\"items.src\"/>\n```\n\n========================================\n\nComments:\n- Alternative you can just `` as shown in the documentation","metadata":{"transformedAt":"2026-08-18T18:33:07.843Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":139,"estimatedTokens":585}}145{"id":"stack-74688433","source":"stackoverflow","questionId":74688433,"title":"Why loading dynamically assets fails on Nuxt v3","tags":["javascript","nuxt.js","assets","vite","nuxt3.js"],"text":"Title: Why loading dynamically assets fails on Nuxt v3\nTags: javascript, nuxt.js, assets, vite, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm experience a weird situation,\n\nI have a \"standard\" `Nuxt v3` project that comes with vite\n\n**Works**\n\n```\n\n```\n\n**Does not work**\n\n```\n\n```\n\nNote that the image path is the same so it does exist, the error I'm getting is:\n\nCannot find module '@/assets/img/image.png' Require stack\n\nThe docs don't mention anything that has to be done in order to achieve it\n\nhttps://i.sstatic.net/mAxO2.png\n\nIs there anything I should do?\n\n========================================\n\nCode:\n```html\n<img src=\"~/assets/img/image.png\">\n<img src=\"~/assets/video/video.mp4\">\n```\n\n```html\n<img :src=\"require('~/assets/img/image.png')\">\n<img :src=\"require('~/assets/video/video.mp4')\">\n```\n\n```text\nNuxt v3\n```\n\n```js\nexport const useDynamicImage = async (path) => {\n const images = import.meta.glob(\"/src/assets/images/**/*\");\n const image = (await images[path.replace(\"@\", \"/src\")]()).default;\n\n return image as string;\n};\n```\n\n```html\n<img :src=\"`_nuxt/assets/img/${imageName}`\">\n```\n\n```none\nexport const useDynamicImage = (path: string): string =>\n new URL(path, import.meta.url).toString();\n```\n\n```js\n<script>\nconst glob = import.meta.glob(\"~/assets/images/how-to-use/*\", {\n eager: true,\n});\n\nconst getImageAbsolutePath = (imageName: string): string => {\n return glob[`/assets/images/how-to-use/${imageName}`][\"default\"];\n};\n</script>\n```\n\n```none\n<script lang=\"ts\" setup>\n//@ts-ignore\nimport image1 from \"../assets/images/image1.jpg\";\n//@ts-ignore\nimport image2 from \"../assets/images/image2.jpg\";\n//@ts-ignore\nimport image3 from \"../assets/images/image3.jpg\";\n\nconst images = [image1, image2, image3];\n</script>\n```\n\n```text\nrequire\n```\n\n```text\nimport\n```\n\n```text\n/src\n```\n\n```text\n@/\n```\n\n```text\nimageName\n```\n\n========================================\n\nComments:\n- A similar question got asked this morning, here is my comment. Also, you're reading which documentation here? Looks like the one for Nuxt2 (with Webpack4). Since you're using Vite, please my comment.\n- hello @kissu The official docs nuxtjs.org/docs might be from the nuxt 2 version, do you have the link of the version 3? I don't think I understand your links so I would like to go through it\n- Here you have the docs for Nuxt3: nuxt.com\n- thanks! but it doesn't mention any of that.. nuxt.com/docs/getting-started/assets I'm trying with: this code `videoUrl.value = new URL(`/src/assets/video/hero-video-double.${props.isIOS ? 'mp4' : 'webm'}`, import.meta.url)` and that string prints out `/src/assets/video/hero-video-double.webm` but `videoUrl` is `http://localhost:3333/undefined` any thougts?\n- Please read my initial comment Everything is written down there.\n- yes, I'm trying with option 3 of that SO answer's link, but is not explaining why to use like that and is failing to me and I don't know where to get more info..\n- Use the `2022 answer: Vite 2.8.6 + Vue 3.2.31` one.\n- I'll give it a shot, although I'm trying to load a video ant that answer is trying to load `().href`","metadata":{"transformedAt":"2026-08-18T18:33:07.843Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":122,"estimatedTokens":780}}146{"id":"stack-59338642","source":"stackoverflow","questionId":59338642,"title":"duplicate namespace auth/ for the namespaced module auth","tags":["vue.js","vuex","nuxt.js"],"text":"Title: duplicate namespace auth/ for the namespaced module auth\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI've been getting this error after installing nuxtjs module. I have tried every trick in the book to fix it, but seems like nothing is working.Added more information.\n\n```\n[vuex] duplicate namespace auth/ for the namespaced module auth\n```\n\nI've been frustrated with it. \n\n```\nauth: {\n plugins: [{ src: '~/plugins/axios', ssr: true }, '~/plugins/auth.js'],\n vuex: {\n namespace: 'auth'\n },\n strategies: {\n local: {\n endpoints: {\n login: {\n url: \"login\",\n method: \"post\",\n propertyName: \"meta.token\"\n },\n user: {\n url: \"me\",\n method: \"get\",\n propertyName: false\n },\n logout: {\n url: \"logout\",\n method: \"post\"\n },\n redirect: {\n login: \"login\",\n logout: \"/\",\n home: \"/\",\n callback: \"/\"\n },\n watchLoggedIn: true,\n rewriteRedirects: true\n }\n }\n }\n },\n```\n\nPlugins\n\n```\nplugins: [\n { src: \"~/plugins/Maps.js\", ssr: false },\n { src: \"~/plugins/Typed.js\", ssr: false },\n { src: \"~/plugins/Animate.js\", ssr: false },\n { src: \"~/plugins/Counter.js\", ssr: false },\n { src: \"~plugins/Vimeo.js\", ssr: false },\n \"~plugins/mixins/user.js\",\n \"~plugins/mixins/validation.js\",\n ],\n```\n\nauth.js ({\n busy: false,\n loggedIn: false,\n strategy: \"local\",\n user: false\n});\n```\n\nFollowing is the code, i currently have. If you need to see any other file, feel free to let me know.\n\nhttps://www.youtube.com/watch?v=FojAfwueTLc\n\n========================================\n\nTop Answer:\nYou probably have a file inside your store folder called \"auth.js\" and you did not explicitly set vuex.namespace option in your nuxt.config.js file.\n\nFrom the documentation: \n\n every .js file inside the store directory is transformed as a namespaced module (index being the root module).\n\nSo that means, \"auth\" becomes a namespace automatically.\n\nThe issue is \"auth\" is also the default Vuex store namespace for keeping state because \"vuex.namespace\" option in your nuxt.config.js file is \"auth\" by default if none is set explicitly. That is where the duplicate comes.\n\nTo solve this, change your store/auth.js to something different like store/authentication.js or change your vuex.namespace option in your nuxt.config.js file to something other than \"auth\" or else it will be used as default.\n\n========================================\n\nCode:\n```text\n[vuex] duplicate namespace auth/ for the namespaced module auth\n```\n\n```text\nauth: {\n plugins: [{ src: '~/plugins/axios', ssr: true }, '~/plugins/auth.js'],\n vuex: {\n namespace: 'auth'\n },\n strategies: {\n local: {\n endpoints: {\n login: {\n url: \"login\",\n method: \"post\",\n propertyName: \"meta.token\"\n },\n user: {\n url: \"me\",\n method: \"get\",\n propertyName: false\n },\n logout: {\n url: \"logout\",\n method: \"post\"\n },\n redirect: {\n login: \"login\",\n logout: \"/\",\n home: \"/\",\n callback: \"/\"\n },\n watchLoggedIn: true,\n rewriteRedirects: true\n }\n }\n }\n },\n```\n\n```text\nplugins: [\n { src: \"~/plugins/Maps.js\", ssr: false },\n { src: \"~/plugins/Typed.js\", ssr: false },\n { src: \"~/plugins/Animate.js\", ssr: false },\n { src: \"~/plugins/Counter.js\", ssr: false },\n { src: \"~plugins/Vimeo.js\", ssr: false },\n \"~plugins/mixins/user.js\",\n \"~plugins/mixins/validation.js\",\n ],\n```\n\n```text\nexport const getters = {\n authenticated(state) {\n return state.loggedIn;\n },\n user(state) {\n return state.user;\n }\n};\n\nexport const state = () => ({\n busy: false,\n loggedIn: false,\n strategy: \"local\",\n user: false\n});\n```\n\n```text\nexport const getters = {\n authenticated(state) {\n return state.auth.loggedIn\n },\n\n user(state) {\n return state.auth.user\n }\n }\n```\n\n```text\nimport Vue from 'vue'\nimport {mapGetters} from 'vuex'\n\n const User = {\n install(Vue, options) {\n Vue.mixin({\n computed: {\n ...mapGetters({\n user: 'user',\n authenticated: 'authenticated'\n })\n }\n })\n }\n };\n\n Vue.use(User);\n```\n\n```text\nexport const getters = {\nauthenticated(state, getters, rootState) {\n return rootState.auth.loggedIn;\n},\n\nuser(state, getters, rootState) {\n return rootState.auth.user;\n}\n};\n```\n\n```text\nimport Vue from \"vue\";\nimport { mapGetters } from \"vuex\";\n\nconst User = {\n install(Vue, options) {\n Vue.mixin({\n computed: {\n ...mapGetters(\"Auth\", {\n user: \"user\",\n authenticated: \"authenticated\"\n })\n }\n});\n}\n};\nVue.use(User);\n```\n\n```text\nauth.js\n```\n\n```text\n\"Panos\"\n```\n\n```text\nAuth.js\n```\n\n```text\nauth.js\n```\n\n```text\nrootState\n```\n\n========================================\n\nComments:\n- It would be helpful if you could some relevant code.\n- Nope. I've tried every possible solution you have suggested. I am trying to override the @nuxtjs/auth module. It's not working.","metadata":{"transformedAt":"2026-08-18T18:33:07.843Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":253,"estimatedTokens":1275}}147{"id":"stack-67012728","source":"stackoverflow","questionId":67012728,"title":"Use nuxt/content to display markdown fetched from a database","tags":["vue.js","nuxt.js","nuxt-content"],"text":"Title: Use nuxt/content to display markdown fetched from a database\nTags: vue.js, nuxt.js, nuxt-content\nSource: Stack Overflow\n\nQuestion:\nI'm using nuxt / content in my app and it's working fine. In another part of the app, I'd like to fetch some markdown from a database and display it.\n\n```\nlet mytext = \"Some *markdown* fetched from a db here.\"\n\n```\n\nThis does not work because I'm missing a parsing step; when you do `$content(\"a_page_title_here\").fetch()` it parses the fetched text and presents it to the component as structured json.\n\nHow do I use `$content` to parse text, so it can be passed to the component for display?\n\nI'll bet there is a way to do it, but the documentation does not include a reference section that describes everything you can do with `$content`.\n\nIf there is an easy way to use the underlying Remark component, I can do that.\n\n========================================\n\nTop Answer:\nThanks to tony19's answer, I was able to create simple component which renders passed string with Markdown content dynamically. Maybe it will be useful for somebody, too!\n\n```\n\nimport markdownParser from \"@nuxt/content/transformers/markdown\"\n\nconst props = defineProps({\n markdownString: {\n type: String,\n required: true,\n }\n});\n\nconst record = ref(\"\");\n\nwatchEffect(async () => {\n await markdownParser.parse(\"custom.md\", props.markdownString).then((md) => record.value = md);\n});\n\n \n\n```\n\nComponent usage example:\n\n```\n\n```\n\nMarkdown will be re-rendered each time `description` changes.\n\n========================================\n\nCode:\n```text\nlet mytext = \"Some *markdown* fetched from a db here.\"\n\n<nuxt-content :document=\"mytext\" />\n```\n\n```text\n$content(\"a_page_title_here\").fetch()\n```\n\n```text\n$content\n```\n\n```text\n$content\n```\n\n```js\n// ~/utils/parseMarkdown.js\nimport markdownParser from '@nuxt/content/transformers/markdown'\n\n// first arg to parse() is for id, which is unused\nexport const parseMarkdown = md => markdownParser.parse('custom.md', md)\n```\n\n```html\n<script setup>\nimport { parseMarkdown } from '~/utils/parseMarkdown'\n\nconst result = ref(null)\nconst loadMarkdown = async () => {\n const data = await $fetch('https://example.com/page.md')\n result.value = await parseMarkdown(data)\n}\nloadMarkdown()\n</script>\n\n<template>\n <ContentRendererMarkdown :value=\"result\" v-if=\"result\" />\n</template>\n```\n\n```js\n// ~/utils/parseMarkdown.js\nimport Markdown from '@nuxt/content/parsers/markdown'\nimport { getDefaults, processMarkdownOptions } from '@nuxt/content/lib/utils'\n\nexport async function parseMarkdown(md) {\n const options = getDefaults()\n processMarkdownOptions(options)\n return new Markdown(options.markdown).toJSON(md) // toJSON() is async\n}\n```\n\n```html\n<script>\nimport { parseMarkdown } from '~/utils/parseMarkdown'\n\nexport default {\n async asyncData({ $axios }) {\n const resp = await $axios.get('https://example.com/page.md')\n const page = await parseMarkdown(resp.data)\n return { page }\n }\n}\n</script>\n\n<template>\n <nuxt-content :document=\"page\" />\n</template>\n```\n\n```text\nnuxt@3\n```\n\n```text\n@nuxt/content@2\n```\n\n```text\n@nuxt/content\n```\n\n```text\n@nuxt/content\n```\n\n```text\nContentRendererMarkdown\n```\n\n```text\nnuxt@2\n```\n\n```text\n@nuxt/content@1\n```\n\n```text\nMarkdown\n```\n\n```text\n@nuxt/content\n```\n\n```text\ntoJSON()\n```\n\n```text\ngray-matter\n```\n\n```text\n<nuxt-content>.document\n```\n\n```text\nMarkdown\n```\n\n```text\nrehype\n```\n\n```text\ngetDefaults()\n```\n\n```text\nprocessMarkdownOptions()\n```\n\n```js\nconst mytext = await this.$content('a_page_title_here').fetch()\n```\n\n```text\n<script setup>\nimport markdownParser from \"@nuxt/content/transformers/markdown\"\n\nconst props = defineProps({\n markdownString: {\n type: String,\n required: true,\n }\n});\n\nconst record = ref(\"\");\n\nwatchEffect(async () => {\n await markdownParser.parse(\"custom.md\", props.markdownString).then((md) => record.value = md);\n});\n</script>\n\n<template>\n <ContentRendererMarkdown :value=\"record\" v-if=\"record\" />\n</template>\n```\n\n```text\n<MarkdownStringRenderer :markdownString=\"description\" />\n```\n\n```text\ndescription\n```\n\n```text\nnpm install marked\nnpm install @types/marked # For TypeScript projects\n```\n\n```text\n<script setup lang=\"ts\">\nimport { marked } from 'marked';\n\nconst parsedDescription = computed(() => {\n return marked.parse(description);\n});\n</script>\n```\n\n```none\nimport markdownParser from '@nuxt/content/transformers/markdown'\n```\n\n```js\n<script setup lang=\"ts\">\nconst md = `\n::alert\nHello MDC\n::\n`\n</script>\n\n<template>\n <MDC :value=\"md\" tag=\"article\" />\n</template>\n```\n\n```text\n@nuxt/content\n```\n\n```text\n^3.0.1\n```\n\n```text\nmarkdownParser\n```\n\n```text\nMDC\n```\n\n========================================\n\nComments:\n- No, because $content looks for the text in a file on disk, and is not processing text from an external source.\n- `[plugin:vite:import-analysis] Missing \"./parsers/markdown\" specifier in \"@nuxt/content\" package`. It must have been changed. I wish we could get the same output as Nuxt offers for file-based Markdown for consistency.\n- @Lukas Interesting. `@next/content/parsers/markdown` is from `nuxt@2` and `@nuxt/content@1`. Do you have the right versions installed? If so, you're probably right that they removed it. I haven't had a chance to check this yet.\n- I'm sorry, I must have been tired and I missed the versions. I'm on Nuxt 3 and content 2... my bad.\n- `markdownParser.parse('custom.md', md)` returns a JSON object from a markdown string. Is there way to do the opposite.. from JSON back to a markdown string? I ask because I store the json in a database, but want to convert it to markdown so the user can edit it and then save it again as JSON once they are finished.","metadata":{"transformedAt":"2026-08-18T18:33:07.843Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":286,"estimatedTokens":1421}}148{"id":"stack-52357328","source":"stackoverflow","questionId":52357328,"title":"How to pass multiple parameters in Nuxt?","tags":["javascript","vue.js","nuxt.js"],"text":"Title: How to pass multiple parameters in Nuxt?\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn Nuxt.js if I have in `pages/posts/_id.vue` this code:\n\n```\n \n \n Post id: {{$route.params.id }} \n \n\n```\n\nWhen I type in the URL: `http://localhost:3000/posts/123`, it displays **Post id: 123**.\n\nSo I learned how to pass one parameter through the URL.\n\nBut I want to pass also the category to which the post belongs to and display a message like this one: **Post id: 123. Category: News**. \n\n- How can I structure the posts folder and get the result I want?\n\n- And how to access the URL in this case? Something like `http://localhost:3000/posts/123`/News` ?\n\n========================================\n\nCode:\n```text\n<template> \n <div> \n Post id: {{$route.params.id }} \n </div> \n</template>\n```\n\n```text\npages/posts/_id.vue\n```\n\n```text\nhttp://localhost:3000/posts/123\n```\n\n```text\nhttp://localhost:3000/posts/123\n```\n\n```text\nposts/\n--| _category/\n-----| _id.vue\n```\n\n```text\nhttp://localhost:3000/posts/news/123\n```\n\n```text\n{{ $route.params.category }}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.843Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":61,"estimatedTokens":422}}149{"id":"stack-66637556","source":"stackoverflow","questionId":66637556,"title":"How to use Vue Testing Library with Nuxt.js?","tags":["vue.js","nuxt.js","testing-library","vue-testing-library"],"text":"Title: How to use Vue Testing Library with Nuxt.js?\nTags: vue.js, nuxt.js, testing-library, vue-testing-library\nSource: Stack Overflow\n\nQuestion:\nI want to use Vue Testing Library in my `Nuxt.js` app. But straight after installing the package, launching a test triggers this error:\n\n'vue-cli-service' is not recognized as an internal or external\ncommand, operable program or batch file.\n\nThis is presumably because `Nuxt.js` does not use `vue-cli-service`.\n\nDespite that, is there a simple way to use `Vue Testing Library` with `Nuxt.js`?\n\n========================================\n\nCode:\n```text\nNuxt.js\n```\n\n```text\nNuxt.js\n```\n\n```text\nvue-cli-service\n```\n\n```text\nVue Testing Library\n```\n\n```text\nNuxt.js\n```\n\n```js\n{\n \"scripts\": {\n \"test:unit\": \"vue-cli-service test:unit\" ❌ not for Nuxt projects\n }\n}\n```\n\n```text\nnpx create-nuxt-app nuxt-testing-library-demo\n```\n\n```text\n$ npx create-nuxt-app nuxt-testing-library-demo\n\ncreate-nuxt-app v3.5.2\n✨ Generating Nuxt.js project in nuxt-testing-library-demo\n[...]\n? Testing framework: Jest\n```\n\n```text\nnpm install -D @testing-library/vue@5\n```\n\n```text\nnpm run test\n```\n\n```text\nnpm install -D @testing-library/vue@5 \\\n vue-jest@^3 \\\n jest@^26 \\\n babel-core@7.0.0-bridge.0 \\\n babel-jest@^26\n\nnpm install -D ts-jest@^26 # if using TypeScript\n```\n\n```js\n// <rootDir>/package.json\n{\n \"scripts\": {\n \"test\": \"jest\"\n }\n}\n```\n\n```js\n// <rootDir>/jest.config.js\nmodule.exports = {\n moduleNameMapper: {\n '^@/(.*)$': '<rootDir>/$1',\n '^~/(.*)$': '<rootDir>/$1',\n '^vue$': 'vue/dist/vue.common.js'\n },\n moduleFileExtensions: [\n 'ts', // if using TypeScript\n 'js',\n 'vue',\n 'json'\n ],\n transform: {\n \"^.+\\\\.ts$\": \"ts-jest\", // if using TypeScript\n '^.+\\\\.js$': 'babel-jest',\n '.*\\\\.(vue)$': 'vue-jest'\n },\n collectCoverage: true,\n collectCoverageFrom: [\n '<rootDir>/components/**/*.vue',\n '<rootDir>/pages/**/*.vue'\n ]\n}\n```\n\n```js\n// <rootDir>/.babelrc\n{\n \"env\": {\n \"test\": {\n \"presets\": [\n [\n \"@babel/preset-env\",\n {\n \"targets\": {\n \"node\": \"current\"\n }\n }\n ]\n ]\n }\n }\n}\n```\n\n```html\n<!-- <rootDir>/components/Counter.vue -->\n<template>\n <div>\n <p>Times clicked: {{ count }}</p>\n <button @click=\"increment\">increment</button>\n </div>\n</template>\n\n<script>\n export default {\n data: () => ({\n count: 0,\n }),\n methods: {\n increment() {\n this.count++\n },\n },\n }\n</script>\n```\n\n```js\n// <rootDir>/test/Counter.spec.js\nimport {render, screen, fireEvent} from '@testing-library/vue'\nimport Counter from '@/components/Counter.vue'\n\ntest('increments value on click', async () => {\n render(Counter)\n expect(screen.queryByText('Times clicked: 0')).toBeTruthy()\n\n const button = screen.getByText('increment')\n await fireEvent.click(button)\n await fireEvent.click(button)\n expect(screen.queryByText('Times clicked: 2')).toBeTruthy()\n})\n```\n\n```text\nnpm run test\n```\n\n```text\nvue-cli-service\n```\n\n```text\ncreate-nuxt-app\n```\n\n```text\nTesting framework\n```\n\n```text\ntest\n```\n\n```text\njest\n```\n\n```text\n@nuxt/create-nuxt-app\n```\n\n```text\n@testing-library/vue@5\n```\n\n```text\ntest\n```\n\n```text\ntestMatch\n```\n\n```text\ntestRegex\n```\n\n```text\njest.config.js\n```\n\n```text\ntest\n```\n\n========================================\n\nComments:\n- I don't know how to check this. But in my `package.json` I have `\"nuxt\": \"^2.14.12\"`","metadata":{"transformedAt":"2026-08-18T18:33:07.843Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":29,"totalLines":227,"estimatedTokens":874}}150{"id":"stack-70971967","source":"stackoverflow","questionId":70971967,"title":"Can't install node-sass@6 for node v16","tags":["node.js","webpack","sass","nuxt.js","node-sass"],"text":"Title: Can't install node-sass@6 for node v16\nTags: node.js, webpack, sass, nuxt.js, node-sass\nSource: Stack Overflow\n\nQuestion:\nThis is my package.json after uninstalling `sass` `node-sass` and `sass-loader` because I changed my node version from 14 to 16,\n\n```\n{\n \"name\": \"our-awesome-project\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"static\": \"NUXTJS_DEPLOY_TARGET=static NUXTJS_SSR=true nuxt generate\",\n \"build-and-start\": \"NUXTJS_DEPLOY_TARGET=server NUXTJS_SSR=false nuxt build && NUXTJS_DEPLOY_TARGET=server NUXTJS_SSR=false nuxt start\"\n },\n \"husky\": {\n \"hooks\": {\n \"pre-commit\": \"cross-env PRE_COMMIT=true lint-staged -r\"\n }\n },\n \"dependencies\": {\n \"core-js\": \"^3.19.3\",\n \"nuxt\": \"^2.15.8\",\n \"nuxt-i18n\": \"^6.28.1\",\n \"nuxt-purgecss\": \"^1.0.0\",\n \"vue\": \"^2.6.14\",\n \"vue-server-renderer\": \"^2.6.14\",\n \"vue-template-compiler\": \"^2.6.14\",\n \"webpack\": \"^4.46\"\n },\n \"devDependencies\": {\n \"@nuxtjs/eslint-config\": \"^8.0.0\",\n \"@nuxtjs/google-fonts\": \"^1.3.0\",\n \"@nuxtjs/storybook\": \"^4.2.0\",\n \"@nuxtjs/style-resources\": \"^1.2.1\",\n \"@vue/cli-plugin-babel\": \"^4.5.15\",\n \"babel-eslint\": \"^10.1.0\",\n \"eslint\": \"^8.7.0\",\n \"husky\": \"^7.0.4\",\n \"nuxt-svg-loader\": \"^1.2.0\",\n \"postcss\": \"^8.4.5\"\n }\n}\n```\n\nAccording to this I should install node-sass version 6.0\nhttps://i.sstatic.net/oPd2r.png\n\nBut I'm trying:\n`npm install --save-dev sass@1.49.0 node-sass@6.0.1 sass-loader@10.2.1`\n\nAlso, read here to add `--unsafe-perm` so I tried:\n`npm install --save-dev --unsafe-perm sass@1.49.0 node-sass@6.0.1 sass-loader@10.2.1`\n\nBut it keeps failing, being the first error **always** this one:\n\n```\nnpm ERR! code 1\nnpm ERR! path /Users/toniweb/Proyectos/our-awesome-project/node_modules/node-sass\nnpm ERR! command failed\nnpm ERR! command sh -c node scripts/build.js\nnpm ERR! Building: /Users/user/.nvm/versions/node/v16.13.1/bin/node /Users/toniweb/Proyectos/our-awesome-project/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=\n```\n\nI tried removing node_modules package-lock.json and the same result\n\nOf course, this is driving me nuts.. please tell me that anyone has an idea to try out\n\n========================================\n\nTop Answer:\nWe have a Nuxt 2.15.8 app running on Node 16, in which a couple of months ago we switched from node-sass to sass, as the former is deprecated.\n\nI recall at the time it took some figuring out, but in the end we just needed to install some postcss parsers to get the Nuxt app fully working with sass & sass-loader.\n\nTaking as the baseline the package.json in your post, try:\n\n```\nnpm install --save-dev \\\n sass@1.49.4 \\\n sass-loader@10.2.1 \\\n postcss-html@1.3.0 \\\n postcss-scss@4.0.3\n```\n\n========================================\n\nCode:\n```text\n{\n \"name\": \"our-awesome-project\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"static\": \"NUXTJS_DEPLOY_TARGET=static NUXTJS_SSR=true nuxt generate\",\n \"build-and-start\": \"NUXTJS_DEPLOY_TARGET=server NUXTJS_SSR=false nuxt build && NUXTJS_DEPLOY_TARGET=server NUXTJS_SSR=false nuxt start\"\n },\n \"husky\": {\n \"hooks\": {\n \"pre-commit\": \"cross-env PRE_COMMIT=true lint-staged -r\"\n }\n },\n \"dependencies\": {\n \"core-js\": \"^3.19.3\",\n \"nuxt\": \"^2.15.8\",\n \"nuxt-i18n\": \"^6.28.1\",\n \"nuxt-purgecss\": \"^1.0.0\",\n \"vue\": \"^2.6.14\",\n \"vue-server-renderer\": \"^2.6.14\",\n \"vue-template-compiler\": \"^2.6.14\",\n \"webpack\": \"^4.46\"\n },\n \"devDependencies\": {\n \"@nuxtjs/eslint-config\": \"^8.0.0\",\n \"@nuxtjs/google-fonts\": \"^1.3.0\",\n \"@nuxtjs/storybook\": \"^4.2.0\",\n \"@nuxtjs/style-resources\": \"^1.2.1\",\n \"@vue/cli-plugin-babel\": \"^4.5.15\",\n \"babel-eslint\": \"^10.1.0\",\n \"eslint\": \"^8.7.0\",\n \"husky\": \"^7.0.4\",\n \"nuxt-svg-loader\": \"^1.2.0\",\n \"postcss\": \"^8.4.5\"\n }\n}\n```\n\n```text\nnpm ERR! code 1\nnpm ERR! path /Users/toniweb/Proyectos/our-awesome-project/node_modules/node-sass\nnpm ERR! command failed\nnpm ERR! command sh -c node scripts/build.js\nnpm ERR! Building: /Users/user/.nvm/versions/node/v16.13.1/bin/node /Users/toniweb/Proyectos/our-awesome-project/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=\n```\n\n```text\nsass\n```\n\n```text\nnode-sass\n```\n\n```text\nsass-loader\n```\n\n```text\nnpm install --save-dev sass@1.49.0 node-sass@6.0.1 sass-loader@10.2.1\n```\n\n```text\n--unsafe-perm\n```\n\n```text\nnpm install --save-dev --unsafe-perm sass@1.49.0 node-sass@6.0.1 sass-loader@10.2.1\n```\n\n```text\nnpm uninstall node-sass\nnpm install --save-dev sass\n```\n\n```text\nARM64\n```\n\n```text\nnode-sass\n```\n\n```text\nsass\n```\n\n```text\nnode-sass\n```\n\n```text\nsass\n```\n\n```sh\nnpm install --save-dev \\\n sass@1.49.4 \\\n sass-loader@10.2.1 \\\n postcss-html@1.3.0 \\\n postcss-scss@4.0.3\n```\n\n```text\nxcode-select --install\n```\n\n```text\nnpm i -g pnpm \n# then \npnpm i\n```\n\n```text\nnpm i --force\n```\n\n========================================\n\nComments:\n- Are you running a M1 mac? ARM64 isn't supported by any version of node-sass right now. It blocked pending GitHub Actions adding support to be able to build and test\n- Yes, apple's M1 . So there is no workaround for now?\n- @ToniMichelCaubet is the initial issue for you that it fails to install the packages? I recommend getting a more updated version of 'sass-loader'. Also, 'node-sass' is deprecated and you should only need 'sass' if you are setting up your own webpack (according to webpack documentation). I hope this helps. webpack.js.org/loaders/sass-loader/#getting-started\n- @Ken thanks a lot for this info. Didn't know node-sass was the way down.. but I forgot to mention that our project is a nuxt app (even that is visible in the package.json) and still can't get it to work w/o node-sass.. i'll research a bit more\n- the \"new\" error is `Error: Compiling RuleSet failed: Properties options are unknown`\n- What about if node sass is a sub dependency of some packages ?","metadata":{"transformedAt":"2026-08-18T18:33:07.843Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":224,"estimatedTokens":1528}}151{"id":"stack-74283819","source":"stackoverflow","questionId":74283819,"title":"Error while creating nuxt3 project. Failed to download template from registry","tags":["javascript","vue.js","frontend","nuxt.js","nuxt3.js"],"text":"Title: Error while creating nuxt3 project. Failed to download template from registry\nTags: javascript, vue.js, frontend, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nWhen I use this command to create a new Nuxt 3 project:\n\n```\nnpx nuxi init nuxt-app\n```\n\nIt outputs this error:\n\n```\nERROR (node:1752) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time 09:53:25\n(Use `node --trace-warnings ...` to show where the warning was created)\n\n ERROR Failed to download template from registry: fetch failed 09:53:25\n\n at /C:/Users/myname/AppData/Local/npm-cache/_npx/a95e0f536cf9a537/node_modules/nuxi/dist/chunks/init.mjs:13269:11\n at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n at async downloadTemplate (/C:/Users/myname/AppData/Local/npm-cache/_npx/a95e0f536cf9a537/node_modules/nuxi/dist/chunks/init.mjs:13268:20)\n at async Object.invoke (/C:/Users/myname/AppData/Local/npm-cache/_npx/a95e0f536cf9a537/node_modules/nuxi/dist/chunks/init.mjs:13336:15)\n at async _main (/C:/Users/myname/AppData/Local/npm-cache/_npx/a95e0f536cf9a537/node_modules/nuxi/dist/cli.mjs:50:20)\n```\n\nMy environments:\n\n- Operating System: Windows 11\n\n- node version : 18.12.0\n\n- npm version: 8.12.1\n\nAt first I suspected that this was due to my network. But I didn't get an error when I tried to install other npm packages.\n\n========================================\n\nTop Answer:\nI also encountered the same error (windows 10). Mine was just plain.\n\n```\nERROR Error: Failed to download template from registry: fetch failed\n```\n\nYes, it was something related to network or ip being blocked. I managed to solve it though. Here's what I did.\n\nFirst go to `C:\\Windows\\System32\\drivers\\etc`\n\nIn this folder look for the 'hosts' file. Open it with notepad as admin. Now in the end of the file (along with other ip addresses) add this line.\n\n```\n// Some other ip address\n185.199.108.133 raw.githubusercontent.com\n```\n\nThis should fix the issue.\n\n========================================\n\nCode:\n```text\nnpx nuxi init nuxt-app\n```\n\n```text\nERROR (node:1752) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time 09:53:25\n(Use `node --trace-warnings ...` to show where the warning was created)\n\n\n ERROR Failed to download template from registry: fetch failed 09:53:25\n\n at /C:/Users/myname/AppData/Local/npm-cache/_npx/a95e0f536cf9a537/node_modules/nuxi/dist/chunks/init.mjs:13269:11\n at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n at async downloadTemplate (/C:/Users/myname/AppData/Local/npm-cache/_npx/a95e0f536cf9a537/node_modules/nuxi/dist/chunks/init.mjs:13268:20)\n at async Object.invoke (/C:/Users/myname/AppData/Local/npm-cache/_npx/a95e0f536cf9a537/node_modules/nuxi/dist/chunks/init.mjs:13336:15)\n at async _main (/C:/Users/myname/AppData/Local/npm-cache/_npx/a95e0f536cf9a537/node_modules/nuxi/dist/cli.mjs:50:20)\n```\n\n```text\nraw.githubusercontent.com\n```\n\n```text\nraw.githubusercontent.com\n```\n\n```text\nERROR Error: Failed to download template from registry: fetch failed\n```\n\n```text\n// Some other ip address\n185.199.108.133 raw.githubusercontent.com\n```\n\n```text\nC:\\Windows\\System32\\drivers\\etc\n```\n\n```text\n185.199.108.133 raw.githubusercontent.com\n```\n\n========================================\n\nComments:\n- It should be an issue to the Nuxt github repository, You could look there for a similar problems. Try this `npx nuxi@latest nuxt3-app` not sure if node@18 already is supported in npx\n- See my answer here\n- Very strange fix, that one should not be needed and is probably not a long term solution IMO. Otherwise, it's mainly a network security bypass and you sysadmin is probably angry now. Still, GG for finding that one out.\n- Basically this answer: stackoverflow.com/a/76121013/8816585\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:07.843Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":112,"estimatedTokens":1057}}152{"id":"stack-60226470","source":"stackoverflow","questionId":60226470,"title":"Vue / Router: How do I correctly fetch data before rendering page content?","tags":["javascript","vue.js","vue-router","nuxt.js"],"text":"Title: Vue / Router: How do I correctly fetch data before rendering page content?\nTags: javascript, vue.js, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt with Vue Router and Axios. I see Vue Router has this fantastic feature called Navigation Guards. \n\nUnfortunately, in the example below, my `beforeRouteEnter()` function is called but seems to exit and switch pages before my manual `next()` method is called in `fetchPageData(next)`. \n\nWhat is the correct pattern here?\n\n```\nexport default {\n beforeRouteEnter (to, from, next) {\n next(vm => {\n vm.fetchPageData(next);\n });\n },\n methods: {\n async fetchPageData(next) {\n const result = await this.$axios.$get('/api/v2/inventory/3906?apiKey=f54761e0-673e-4baf-86c1-0b85a6c8c118');\n this.$store.commit('property/setProperty', result[0]);\n next();\n }\n }\n}\n```\n\nI assume that my first call to `next(vm => {})` is running asynchronously, allowing execution to continue, resulting in a page change before I (most likely incorrectly) try to callback next().\n\n========================================\n\nTop Answer:\n**What is happening there, is that you already calling `next` and that's**\n **why the route enters immediately.**\n\nWhere you are calling next ?\n\n```\nbeforeRouteEnter (to, from, next) {\n next(vm => { // And the above code will execute `vm.fetchPageData` when the component is already rendered.\n\nSo even if you don't call `next` on the `fetchPageData` the route will enter.\n\nBy assuming that you want to enter the view after certain data is fetched by BE you can use `beforeEnter` on the router config:\n\n```\nconst router = new VueRouter({\n routes: [\n {\n path: '/foo',\n component: Foo,\n beforeEnter: (to, from, next) => {\n axios.get('api/...')\n .then(response => {\n store.commit('mutation', response)\n next()\n })\n .catch(e => {\n alert('Something went wrong')\n next(false)\n })\n }\n }\n ]\n})\n```\n\nAnother solution would be to allow the route to enter but show a loader while data is being fetched: Checkout this answer\n\n========================================\n\nCode:\n```text\nexport default {\n beforeRouteEnter (to, from, next) {\n next(vm => {\n vm.fetchPageData(next);\n });\n },\n methods: {\n async fetchPageData(next) {\n const result = await this.$axios.$get('/api/v2/inventory/3906?apiKey=f54761e0-673e-4baf-86c1-0b85a6c8c118');\n this.$store.commit('property/setProperty', result[0]);\n next();\n }\n }\n}\n```\n\n```text\nbeforeRouteEnter()\n```\n\n```text\nnext()\n```\n\n```text\nfetchPageData(next)\n```\n\n```text\nnext(vm => {})\n```\n\n```js\nexport default {\n async fetch({store, $axios}) {\n const result = await $axios.$get('/api/v2/inventory/3906');\n store.commit('property/setProperty', result[0]);\n }\n}\n```\n\n```text\nnext()\n```\n\n```text\nnext()\n```\n\n```text\nnext()\n```\n\n```text\nnext()\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\ndata\n```\n\n```text\nasyncData\n```\n\n```text\nbeforeRouteEnter (to, from, next) {\n next(vm => { // <= HERE you execute next\n vm.fetchPageData(next);\n });\n},\n```\n\n```text\nconst router = new VueRouter({\n routes: [\n {\n path: '/foo',\n component: Foo,\n beforeEnter: (to, from, next) => {\n axios.get('api/...')\n .then(response => {\n store.commit('mutation', response)\n next()\n })\n .catch(e => {\n alert('Something went wrong')\n next(false)\n })\n }\n }\n ]\n})\n```\n\n```text\nnext\n```\n\n```text\nvm.fetchPageData\n```\n\n```text\nnext\n```\n\n```text\nfetchPageData\n```\n\n```text\nbeforeEnter\n```\n\n========================================\n\nComments:\n- Sadly the asyncData isn't working for me as I need to put the data in a store and I can't seem to access the store from within it. Can you please post an example of how to use next() with \"extracting fetch logic from the component itself\" as you mentioned.\n- Added more Nuxt specific options of how to do async data. If you are using a store, use `fetch` instead of `asyncData`....\n- Can you please suggest a way that I could achieve my goal (first load data, then switch pages) from within the component (from readability perspective - as opposed to in the router configuration)? I'm not sure how to access the vm (to get access to $axios) without using next function, which is then called too early.\n- As far as I can see you are using an axios instance. So you can import this instance and use the axios in the router config. In that case you will not need to use `this` (Vue instance)\n- If you still can't find a solution, ping me on rolanddoda2014@gmail.com and I will make a simple demo for you","metadata":{"transformedAt":"2026-08-18T18:33:07.843Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":205,"estimatedTokens":1161}}153{"id":"stack-54083703","source":"stackoverflow","questionId":54083703,"title":"nuxt.js - preload .woff fonts loaded as @font-face","tags":["javascript","vue.js","webpack","fonts","nuxt.js"],"text":"Title: nuxt.js - preload .woff fonts loaded as @font-face\nTags: javascript, vue.js, webpack, fonts, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nTrying to improve my google score and google is telling me to use preload on the two custom fonts i'm using to save a whopping 4.5 seconds? currently the fonts are stored in assets/fonts and then being loaded as @font-face in typography.scss file when is then loaded in the nuxt.config.js file inside css: [ '@/assets/scss/typography.scss', ]\n\n========================================\n\nCode:\n```text\n//nuxt.config.js\n\nmodule.exports = {\n mode: ' your mode ',\n\n ...\n\n render: {\n bundleRenderer: {\n shouldPreload: (file, type) => {\n return ['script', 'style', 'font'].includes(type)\n }\n }\n\n },\n ...\n\n}\n```\n\n```text\n/static/fonts/yourfonts.woff2\n```\n\n========================================\n\nComments:\n- No worries, glad to help.\n- I don't know why, but for me this does nothing. I followed this issue: github.com/nuxt/nuxt.js/issues/1508 but for me the only thing that had an effect was putting it in my head.link with `{ rel: 'preload', as: 'font', type: 'font/woff2', href: '/fonts/myfont.woff2', crossorigin: true }`\n- Does module.exports sit outside export default{} or inside it?\n- doesn't worked for me , looking at this github.com/manniL/lichter.io/blob/…\n- Use this option to customize vue SSR bundle renderer. This option is skipped if ssr: false. nuxtjs.org/docs/2.x/configuration-glossary/configuration-ren‌​der","metadata":{"transformedAt":"2026-08-18T18:33:07.843Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":43,"estimatedTokens":381}}154{"id":"stack-72882000","source":"stackoverflow","questionId":72882000,"title":"How do I make my Nuxt app (v3) serve .mjs.br (brotli) files instead of the regular .mjs files? (Text compression)","tags":["nuxt.js","nuxt3.js"],"text":"Title: How do I make my Nuxt app (v3) serve .mjs.br (brotli) files instead of the regular .mjs files? (Text compression)\nTags: nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI deployed a simple Nuxt (version 3) app over Google Cloud Run and tested the performance using Lighthouse. The score was pretty horrible but one of the most impactful improvements it offered was to enable text compression (gzip or brotli).\n\nI was able to make the server output `.mjs.br` files implementing `vite-plugin-compression` in the nuxt config:\n\n```\nimport viteCompression from \"vite-plugin-compression\";\n\nexport default defineNuxtConfig({\n vite: {\n plugins: [viteCompression({ algorithm: \"brotliCompress\" })],\n },\n...\n```\n\nDespite `.mjs.br` files being generated, `.mjs` files were still being served by default.\n\nHow can I make Nuxt serve the brotli-compressed files instead? Or is this not possible yet?\n\n========================================\n\nTop Answer:\nThis one works great on me: nuxt-compression\n\ninstall:\n\n```\nnpm i -D @averjs/nuxt-compression\n```\n\nnuxt.config.ts\n\n```\nexport default defineNuxtConfig({\n buildModules: ['@averjs/nuxt-compression'],\n});\n```\n\njust works! default compression is brotli.\n\n========================================\n\nCode:\n```text\nimport viteCompression from \"vite-plugin-compression\";\n\nexport default defineNuxtConfig({\n vite: {\n plugins: [viteCompression({ algorithm: \"brotliCompress\" })],\n },\n...\n```\n\n```text\n.mjs.br\n```\n\n```text\nvite-plugin-compression\n```\n\n```text\n.mjs.br\n```\n\n```text\n.mjs\n```\n\n```text\nimport { defineNuxtConfig } from 'nuxt'\n\nexport default defineNuxtConfig({\n nitro: {\n compressPublicAssets: true,\n },\n})\n```\n\n```text\nnpm i -D @averjs/nuxt-compression\n```\n\n```text\nexport default defineNuxtConfig({\n buildModules: ['@averjs/nuxt-compression'],\n});\n```\n\n```text\nexport default {\n ssr: true,\n nitro: {\n compressPublicAssets: true,\n minify: true\n },\n minify: true,\n collapseBooleanAttributes: true,\n decodeEntities: true,\n minifyCSS: true,\n minifyJS: true,\n processConditionalComments: true,\n removeEmptyAttributes: true,\n removeRedundantAttributes: true,\n trimCustomFragments: true,\n useShortDoctype: true,\n}\n```\n\n========================================\n\nComments:\n- Did you manage to figure it out?\n- @Mathijs No, I reverted back to Nuxt 2 where the files seem to be compressed by default (gzip).\n- where did you find these options? i did not find them in nuxt docs","metadata":{"transformedAt":"2026-08-18T18:33:07.843Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":119,"estimatedTokens":621}}155{"id":"stack-59292573","source":"stackoverflow","questionId":59292573,"title":"How do I disable nuxt default error redirection","tags":["vue.js","nuxt.js"],"text":"Title: How do I disable nuxt default error redirection\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSet up a nuxt project with Vuetify. One of the pages uses a `client-only` (`no-ssr`) component. During development, in case of an error in this component, I get redirected to the default error page, which prevents me from inspecting the variables and components using Vue devtools. \n\nI feel like it should be really simple but I couldn't find a way to disable this auto redirecting behavior. So I guess my question is how do you disable nuxt default error redirection?\n\n========================================\n\nTop Answer:\nI found a hack with a nuxt plugin :\n\n./plugins/errors.js\n\n```\nexport default function({ app }) {\n app.nuxt.error = () => {}\n}\n```\n\n./nuxt.config.js\n\n```\nmodule.exports = {\n ...\n plugins: [\n \"~/plugins/errors.js\",\n ],\n}\n```\n\n========================================\n\nCode:\n```text\nclient-only\n```\n\n```text\nno-ssr\n```\n\n```js\nrender (h) {\n\n // HACK TO SKIP ERROR\n this.nuxt.err = false\n\n // if there is no error\n if (!this.nuxt.err) {\n // Directly return nuxt child\n return h('NuxtChild', {\n key: this.routerViewKey,\n props: this.$props\n })\n }\n\n // ...\n }\n```\n\n```text\n<nuxt-error>\n```\n\n```text\n./node_modules/@nuxt/vue-app/template/components/nuxt.js\n```\n\n```text\nrender(h)\n```\n\n```text\nexport default function({ app }) {\n app.nuxt.error = () => {}\n}\n```\n\n```text\nmodule.exports = {\n ...\n plugins: [\n \"~/plugins/errors.js\",\n ],\n}\n```\n\n```text\nVue.config.errorHandler = (error) => {\n ErrorService.onError(error);\n return true\n}\n```\n\n```text\nconst defaultErrorHandler = Vue.config.errorHandler\n Vue.config.errorHandler = async (err, vm, info, ...rest) => {\n // Call other handler if exist\n let handled = null\n if (typeof defaultErrorHandler === 'function') {\n handled = defaultErrorHandler(err, vm, info, ...rest)\n }\n if (handled === true) {\n return handled\n }\n\n ...some code to define layout\n```\n\n========================================\n\nComments:\n- damirscorner.com/blog/posts/20200904-ErrorHandlingInNuxtjs.h‌​tml\n- I dont know how to disable redirection for error layout, although I guess that many people dont want to disable it in production environment and they need this only for development purposes, I would suggest in the if condition to add this process.env.NODE_ENV !== 'production' in order to disable redirection only in dev env\n- Can't believe this is not customizable...\n- Note this still uses the error layout, I can't find a way to disable that","metadata":{"transformedAt":"2026-08-18T18:33:07.843Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":119,"estimatedTokens":649}}156{"id":"stack-63689739","source":"stackoverflow","questionId":63689739,"title":"Is it possible for Nuxt JS plugins to only run once?","tags":["vue.js","vuejs2","vuex","nuxt.js"],"text":"Title: Is it possible for Nuxt JS plugins to only run once?\nTags: vue.js, vuejs2, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have several VueX actions (that run on the server only) and are dispatched from `nuxtServerInit`. They make HTTP requests to external services, which is slowing down the TTFB.\n\nI would like to implement a cache plugin that can store and retrieve values from Redis. The aim is to avoid making the HTTP requests in actions on every request.\n\nI started out by adding a line to the nuxt.js config file.\n\n`{ src: '~/plugins/cache', ssr: true, mode: 'server' },`\n\nI then created the following in `resources/plugins/cache.js`\n\n```\nimport redis from 'redis';\n\nexport default ({ app }, inject) => {\n console.log('Creating redis client');\n inject('cache', redis.createClient({\n //options removed for brevity\n }));\n}\n```\n\nI run the app and can see 'Creating redis client' is printed to the console on every page refresh. Is it possible to create a plugin that is instantiated when the server is started and the same instance is used for every request? Or if that is not possible, what is the best way to implement the cache?\n\n========================================\n\nCode:\n```text\nimport redis from 'redis';\n\nexport default ({ app }, inject) => {\n console.log('Creating redis client');\n inject('cache', redis.createClient({\n //options removed for brevity\n }));\n}\n```\n\n```text\nnuxtServerInit\n```\n\n```text\n{ src: '~/plugins/cache', ssr: true, mode: 'server' },\n```\n\n```text\nresources/plugins/cache.js\n```\n\n```js\nexport default function (_moduleOptions) {\n // any data you want to share between all requests\n const data = {\n message: `Hello from cache - ${new Date().toLocalTimeString()}`\n };\n\n this.nuxt.hook(\"vue-renderer:ssr:prepareContext\", (ssrContext) => {\n ssrContext.$cache = data;\n });\n}\n```\n\n```js\nexport const state = () => ({\n cache: {}\n});\n\nexport const mutations = {\n setcache(state, payload) {\n state.cache = payload;\n }\n};\n\nexport const actions = {\n nuxtServerInit({ commit }, context) {\n commit(\"setcache\", context.ssrContext.$cache);\n }\n};\n```\n\n```text\nmodules/cacheModule.js\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nstore/index.js\n```\n\n```text\ncacheAdapterEnhancer\n```\n\n```text\nnuxtServerInit\n```\n\n========================================\n\nComments:\n- why do you want to dispatch those actions on the server side?","metadata":{"transformedAt":"2026-08-18T18:33:07.843Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":109,"estimatedTokens":595}}157{"id":"stack-64793572","source":"stackoverflow","questionId":64793572,"title":"Axios fails CORS but fetch works fine","tags":["javascript","rest","vue.js","cors","nuxt.js"],"text":"Title: Axios fails CORS but fetch works fine\nTags: javascript, rest, vue.js, cors, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI've looked through all the other questions regarding CORS errors with no luck. I'm making a simple POST request in a NuxtJS client application. If I use axios, I get CORS errors, but if I use fetch, it works just fine. I would like to use axios, but I can't sort this out. The server has the correct \"Access-Control-Allow-Origin\" headers set (neither option below works when that header is removed). Anyone know why this would work for fetch but not axios?\n\n**FAILS**\n\n```\nawait this.$axios({\n url,\n method: 'POST',\n data\n })\n```\n\n**WORKS**\n\n```\nawait fetch(url, {\n method: 'POST',\n body: JSON.stringify(data)\n })\n```\n\n**Error message:**\nAccess to XMLHttpRequest at {URL} from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.\n\nIn the network tab of Chrome, the request headers show as follows:\n\nAxios request headers\n\nfetch request headers\n\n========================================\n\nCode:\n```text\nawait this.$axios({\n url,\n method: 'POST',\n data\n })\n```\n\n```text\nawait fetch(url, {\n method: 'POST',\n body: JSON.stringify(data)\n })\n```\n\n```text\nHTTP/1.1 204 No Content\nConnection: keep-alive\nAccess-Control-Allow-Origin: https://foo.bar.org\nAccess-Control-Allow-Methods: POST, OPTIONS\nAccess-Control-Allow-Headers: Content-Type\nAccess-Control-Max-Age: 86400\n```\n\n```text\nContent-Type\n```\n\n```text\nContent-Type: application/json\n```\n\n```text\naxios\n```\n\n```text\nContent-Type\n```\n\n```text\nfetch\n```\n\n```text\nContent-Type\n```\n\n```text\nfetch\n```\n\n```text\nfetch\n```\n\n```text\ntext/plain\n```\n\n```text\napplication/json\n```\n\n========================================\n\nComments:\n- What is `data`? A string? An object? A FormData object? A Blob object?\n- Have you looked at the request headers from `fetch` and `axios`? Are they equal?\n- Sorry, I incorrectly copied the fetch request initially. \"data\" is a javascript object. Axios takes an object, but for fetch, I stringified it.\n- If my fetch code is wrong, why is that one working while the axios call is failing?\n- Because the fetch code is lying about what it is sending but the server is processing it as JSON despite the claim it is plain text.\n- Ah, I see. And CORS is being enforced for axios because it's automatically setting the correct \"Content-Type: application/json\" header. So if I correctly set the header in my fetch request, it should fail just like the axios call. Am I understanding correctly?\n- Just tested it. Yeah, the fetch failed when I set the Content-Type header. Now I just need to fix the CORS issues for both of them haha.\n- Legend, I missed this somehow... great explanation!","metadata":{"transformedAt":"2026-08-18T18:33:07.844Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":113,"estimatedTokens":715}}158{"id":"stack-58541191","source":"stackoverflow","questionId":58541191,"title":"Should I build server-side of application inside nuxt.js server directory?","tags":["node.js","vue.js","project","nuxt.js"],"text":"Title: Should I build server-side of application inside nuxt.js server directory?\nTags: node.js, vue.js, project, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to build full-stack application with **Nuxt.js**. I am wondering where I should create my server-side inside **Nuxt.js** or maybe I should create separated project only for server stuff.\n\nI am trying to set up my project but I do not know how I should do it. The application which I am building will have own front-end, back-end and also database (I will use **MongoDB**) but actually I do not know how I should start. I was reading a lot about SSR and **Nuxt.js** seems really good if am planing to use **Vue.js** on fronted. While creating nuxt app I can choose to use Express and then I can see server directory inside my directory structure does it mean that i should build all back-end inside this directory or maybe it is only for small stuff?\nI have also another question what if I want to use `Nest.js` on back-end can i just use `npm i -g @nestjs/cli` and then `nest new project-name` inside my server directory ? I was looking also for this answer but almost all results in google for this type are about (comparison between **Nuxt.js**, **Next.js** and **Nest.js**).\n\nIt will be my first bigger full-stack project and I want to do it right but I am a really beginner in this so I am looking for answer from more experienced programmers.\n\n========================================\n\nCode:\n```text\nNest.js\n```\n\n```text\nnpm i -g @nestjs/cli\n```\n\n```text\nnest new project-name\n```\n\n```text\ncreate-nuxt-app\n```\n\n```text\nserver\n```\n\n```text\nindex.js\n```\n\n========================================\n\nComments:\n- btw these sort of questions really are better suited for the software engineering SE\n- Has there been any more thought about this type of Solution. A \"Monolith\" app on nuxt.js with async server/client logic and then server only business logic (Auth, etc) as well as database access\n- I think the same about API and having indpendent fronted and backedn, but there is one isue, what about SSR, can I have without **Nuxt.js** ? Or maybe it is good idea to use **Nux.js** to build SPA application (in documentation we can read that it is also solving SEO problems)? And what do you mean by this `\"not good to group folder structure if you plan to split nuxt and server in different servers\"`","metadata":{"transformedAt":"2026-08-18T18:33:07.844Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":45,"estimatedTokens":591}}159{"id":"stack-67822238","source":"stackoverflow","questionId":67822238,"title":"how to import a json file using vite dynamicly","tags":["nuxt.js","vue-i18n","vite"],"text":"Title: how to import a json file using vite dynamicly\nTags: nuxt.js, vue-i18n, vite\nSource: Stack Overflow\n\nQuestion:\nI am using vue-i18n in a Nuxtjs project, and I want to import my locale files with vite dynamicly.\n\nwhen I am using webpack, those code run well\n\n**plugins/i18n.js**\n\n```\nimport Vue from 'vue';\nimport VueI18n from 'vue-i18n';\nimport config from '@/config';\n\nVue.use(VueI18n);\n\nlet messages = Object;\n\nconfig.locale.available.forEach(locale => {\n messages[locale] = require(`~/locales/${locale}.json`);\n});\n\nexport default ({ app, store }) => {\n app.i18n = new VueI18n({\n locale: store.state.locale.locale,\n messages: messages\n });\n}\n```\n\nI got that there is no `require()` in vitejs, also the glob-import feature of vitejs\n\n- So I tried like this below first:\n\n```\nlet messages = Object,\n languages = import.meta.glob('../locales/*.json'); // => languages = {} (languages only get {} value)\n\nconfig.locale.available.forEach(locale => {\n messages[locale] = languages[`../locales/${locale}.json`];\n});\n```\n\nBut the `languages` only got `{}` value.\n\n- Then I tried to use `import()`\n\n```\nlet messages = Object,\n translate = lang => () => import(`@/locales/${lang}.json`).then(i => i.default || i);\n\nconfig.locale.available.forEach(locale => {\n messages[locale] = translate(locale);\n});\n```\n\nno errors in both terminal and console, but no locale file has been loaded correctly.\n\nonly if I `import()` one by one, the issue will disappear:\n\n```\nimport en from '@/locales/en.json';\nimport fr from '@/locales/fr.json';\nimport ja from '@/locales/ja.json';\n\nlet messages = Object;\n\nmessages['en'] = en;\nmessages['fr'] = fr;\nmessages['ja'] = ja;\n```\n\n### **CodeSandbox**\n\nBut, how to import it dynamicly?\n\nI googled it, but helped little. Greate thank for anyone help!\n\n========================================\n\nTop Answer:\nBased on @Lucas Dawson's answer\n\nfor those who have to run their code on both vite and webpack\n\n**plugins/i18n.js**\n\n```\nimport Vue from 'vue';\nimport VueI18n from 'vue-i18n';\n\nVue.use(VueI18n);\n\n/***\nmake sure your public config has `VITE_` prefix or it can't be seen in the client side\nhttps://vitejs.dev/guide/env-and-mode.html#env-files\n***/\nlet messages = Object,\n locales = process.env.VITE_AVAILABLE_LOCALES.split(',');\n\n// check is using vite or webpack\nif (typeof __webpack_require__ !== 'function') {\n // for vite\n\n /***\n glob and globEager are both work for this\n https://vitejs.dev/guide/features.html#glob-import\n\n the differences is\n `glob` will return a dynamic import function (lazy load)\n `globEager` will return the data of the file from the path directly\n\n if you use `glob`, don't forget `JSON.parse(JSON.stringify(**Your data**))`\n if you have trouble with this, use `globEager` may save your day\n ***/\n\n let modules = import.meta.globEager('/lang/*.json');\n locales.forEach(locale => {\n messages[locale] = modules[`/lang/${locale}.json`];\n });\n}\nelse {\n // for webpack (storybook)\n locales.forEach(locale => {\n messages[locale] = require(`~/lang/${locale}.json`);\n });\n}\n\nexport default ({ app, store }) => {\n app.i18n = new VueI18n({\n locale: store.getters['locale/locale'],\n messages\n });\n}\n```\n\nThanks again for @Lucas Dawson's answer!\n\n========================================\n\nCode:\n```js\nimport Vue from 'vue';\nimport VueI18n from 'vue-i18n';\nimport config from '@/config';\n\nVue.use(VueI18n);\n\nlet messages = Object;\n\nconfig.locale.available.forEach(locale => {\n messages[locale] = require(`~/locales/${locale}.json`);\n});\n\nexport default ({ app, store }) => {\n app.i18n = new VueI18n({\n locale: store.state.locale.locale,\n messages: messages\n });\n}\n```\n\n```js\nlet messages = Object,\n languages = import.meta.glob('../locales/*.json'); // => languages = {} (languages only get {} value)\n\nconfig.locale.available.forEach(locale => {\n messages[locale] = languages[`../locales/${locale}.json`];\n});\n```\n\n```js\nlet messages = Object,\n translate = lang => () => import(`@/locales/${lang}.json`).then(i => i.default || i);\n\nconfig.locale.available.forEach(locale => {\n messages[locale] = translate(locale);\n});\n```\n\n```js\nimport en from '@/locales/en.json';\nimport fr from '@/locales/fr.json';\nimport ja from '@/locales/ja.json';\n\nlet messages = Object;\n\nmessages['en'] = en;\nmessages['fr'] = fr;\nmessages['ja'] = ja;\n```\n\n```text\nrequire()\n```\n\n```text\nlanguages\n```\n\n```text\n{}\n```\n\n```text\nimport()\n```\n\n```text\nimport()\n```\n\n```js\n//Importing your data \nconst data = import.meta.glob('../locales/*.json')\n\n//Ref helps with promises I think. I'm sure there are more elegant ways.\nconst imp = ref([{}])\n\n// From https://github.com/vitejs/vite/issues/77\n// by LiuQixuan commented on Jun 20\n\nfor (const path in data) {\n data[path]().then((mod) => { \n imp.value.push(mod)\n })\n}\n```\n\n```js\nJSON.parse(JSON.stringify(**Your data**))\n```\n\n```html\n<div v-for=\"(module,i) in imp\" :key=\"i\">\n <div v-for=\"(data,j) in module\" :key=\"j\">\n\n //at this point you can read it fully with {{ data }}\n\n <div v-for=\"(jsonText, k) in JSON.parse(JSON.stringify(data))\" :key=k\">\n {{ jsonText.text }}\n <div v-for=\"insideJson in jsonText\" :key=\"insideJson\">\n {{ insideJson.yourtext }}\n </div>\n </div>\n </div>\n </div>\n```\n\n```js\nnew URL(*, import.meta.url)\n```\n\n```js\nfor (const path in modules) {\n modules[path]().then(() => {\n //*************\n const imgURL = new URL(path, import.meta.url)\n //*************\n gallery.value.push(imgURL)\n })\n }\n //Then reference that gallery.value in your :src\n```\n\n```text\nimp.values\n```\n\n```js\nimport Vue from 'vue';\nimport VueI18n from 'vue-i18n';\n\nVue.use(VueI18n);\n\n/***\nmake sure your public config has `VITE_` prefix or it can't be seen in the client side\nhttps://vitejs.dev/guide/env-and-mode.html#env-files\n***/\nlet messages = Object,\n locales = process.env.VITE_AVAILABLE_LOCALES.split(',');\n\n// check is using vite or webpack\nif (typeof __webpack_require__ !== 'function') {\n // for vite\n\n /***\n glob and globEager are both work for this\n https://vitejs.dev/guide/features.html#glob-import\n\n the differences is\n `glob` will return a dynamic import function (lazy load)\n `globEager` will return the data of the file from the path directly\n\n if you use `glob`, don't forget `JSON.parse(JSON.stringify(**Your data**))`\n if you have trouble with this, use `globEager` may save your day\n ***/\n\n let modules = import.meta.globEager('/lang/*.json');\n locales.forEach(locale => {\n messages[locale] = modules[`/lang/${locale}.json`];\n });\n}\nelse {\n // for webpack (storybook)\n locales.forEach(locale => {\n messages[locale] = require(`~/lang/${locale}.json`);\n });\n}\n\nexport default ({ app, store }) => {\n app.i18n = new VueI18n({\n locale: store.getters['locale/locale'],\n messages\n });\n}\n```\n\n```js\nconst requireLocale = async fileName => {\n try {\n const files = import.meta.globEager(\"./i18n/*.json\")\n const texts = files[`./i18n/${fileName}.json`]\n return texts?.default || {}\n }\n catch (e) {\n console.warn(`The file \"./i18n/${fileName}.json\" could not be loaded.`)\n return {}\n }\n}\n```\n\n```text\nimport.meta.glob\n```\n\n========================================\n\nComments:\n- One thing that bugged me, is that my IDE (vscode) didn't look \"healthy\" after importing the data with this syntax `const data = import.meta.glob('../locales/*.json')`: it worked but the linting displayed it as if there was a closing parenthesis missing. I solved it by using a backslash such as `const data = import.meta.glob('../locales/\\*.json')`","metadata":{"transformedAt":"2026-08-18T18:33:07.844Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":342,"estimatedTokens":1927}}160{"id":"stack-59880855","source":"stackoverflow","questionId":59880855,"title":"how to add gtm dataLayer to nuxt.js component?","tags":["vue.js","google-tag-manager","nuxt.js"],"text":"Title: how to add gtm dataLayer to nuxt.js component?\nTags: vue.js, google-tag-manager, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a problem adding to dayaLayer. For gtm I use this plugin, but I don’t understand how to add dataLayer for it through the component.\nMy nuxt.config fo plugin\n\n```\nmodules: [\n ['@nuxtjs/google-tag-manager', {\n id: 'GTM-xxxxxxxxxx',\n pageViewEventName: 'nuxtRoute',\n pageTracking: true,\n layer: 'dataLayer'\n }]\n ]\n```\n\nMy component\n\n```\nhead() {\n return {\n title: this.seo.title_meta,\n meta: [\n // hid is used as unique identifier. Do not use `vmid` for it as it will not work\n { hid: 'google-site-verification', name: 'google-site-verification', content: 'test' },\n { hid: 'description', name: 'description', content: this.seo.description_meta }\n ],\n __dangerouslyDisableSanitizers: ['script'],\n script: [\n {\n innerHTML: JSON.stringify({\n '@context': 'http://schema.org',\n '@type': 'Organization',\n name: 'test',\n url: 'https://test.co',\n sameAs: this.linkMeta,\n description: `${this.seo.description_meta}`\n }),\n type: 'application/ld+json'\n },\n {\n innerHTML: `\n window.dataLayer = window.dataLayer || [];\n window.dataLayer = [{ 'pageType': 'Main'}]\n `\n }\n ]\n };\n },\n```\n\nI tried to add a script with dataLayer to the head but nothing came of it. My Google Tag Assistant plugin does not find dataLayer. Thanks for any help!\n\n========================================\n\nCode:\n```text\nmodules: [\n ['@nuxtjs/google-tag-manager', {\n id: 'GTM-xxxxxxxxxx',\n pageViewEventName: 'nuxtRoute',\n pageTracking: true,\n layer: 'dataLayer'\n }]\n ]\n```\n\n```text\nhead() {\n return {\n title: this.seo.title_meta,\n meta: [\n // hid is used as unique identifier. Do not use `vmid` for it as it will not work\n { hid: 'google-site-verification', name: 'google-site-verification', content: 'test' },\n { hid: 'description', name: 'description', content: this.seo.description_meta }\n ],\n __dangerouslyDisableSanitizers: ['script'],\n script: [\n {\n innerHTML: JSON.stringify({\n '@context': 'http://schema.org',\n '@type': 'Organization',\n name: 'test',\n url: 'https://test.co',\n sameAs: this.linkMeta,\n description: `${this.seo.description_meta}`\n }),\n type: 'application/ld+json'\n },\n {\n innerHTML: `\n window.dataLayer = window.dataLayer || [];\n window.dataLayer = [{ 'pageType': 'Main'}]\n `\n }\n ]\n };\n },\n```\n\n```text\nscript: [\n {\n hid: 'gtm',\n innerHTML: `window.dataLayer = window.dataLayer || [];`,\n type: 'text/javascript'\n }\n]\n```\n\n```text\nmounted: {\n window.dataLayer.push({variable: value, someOtherVar: anotherValue})\n}\n```\n\n```text\nhead\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.844Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":122,"estimatedTokens":704}}161{"id":"stack-58142572","source":"stackoverflow","questionId":58142572,"title":"How do you emit an event from a nuxt plugin?","tags":["nuxt.js"],"text":"Title: How do you emit an event from a nuxt plugin?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am creating a plugin that will emit basic nuxt events triggered by sockets. The nuxt event will then be recieved and open a snackbar. When inside a component it is easy to send and receive events by using `$nuxt`\n\n```\nthis.$nuxt.$on('open-snackbar', this.handler)\n```\n\n```\nthis.$nuxt.$emit('open-snackbar', options)\n```\n\nHowever how I'm trying to do this in a plugin so its not tied to any one page, but exists throughout the app. I can't seem to figure out how to emit it from said plugin:\n\n```\nexport default (context) => {\n console.log(context)\n console.log(context.$emit)\n console.log(context.emit)\n console.log(context.$nuxt)\n console.log(context.app.emit)\n console.log(context.app.$nuxt)\n}\n```\n\n`context.app` seems like it would be the correct object but it doesn't seem to work. Any ideas?\n\n========================================\n\nTop Answer:\nI figured another way to do it, by creating a manual event bus using Vue itself and using combined inject\n\nIn my case, I had a global axios interceptor to check the responses for a status code of `401`, meaning that the user's session has expired and then display a notification to them.\n\n```\n// my-plugin.js\nimport Vue from 'vue'\n\nexport default function ({ $axios, app }, inject){\n\n inject('eventHub', new Vue()); // this is the same as Vue.prototype.$eventHub = new Vue()\n\n // checking for status \n $axios.onError((error) => {\n const code = parseInt(error.response && error.response.status)\n if (code === 401) {\n app.$auth.logout() // logout if errors have happened\n app.$eventHub.$emit('session-expired')\n }\n })\n}\n```\n\nThe event bus is now accessible both in context and in any Vue instance\n\n```\n// login.vue\n\nexport default{\n data(){\n // data\n },\n created(){\n this.$eventHub.$once('session-expired', ()=> {\n this.showAlert()\n })\n },\n methods: {\n showAlert(){\n // display notifcations\n }\n }\n}\n```\n\n========================================\n\nCode:\n```js\nthis.$nuxt.$on('open-snackbar', this.handler)\n```\n\n```js\nthis.$nuxt.$emit('open-snackbar', options)\n```\n\n```js\nexport default (context) => {\n console.log(context)\n console.log(context.$emit)\n console.log(context.emit)\n console.log(context.$nuxt)\n console.log(context.app.emit)\n console.log(context.app.$nuxt)\n}\n```\n\n```text\n$nuxt\n```\n\n```text\ncontext.app\n```\n\n```js\nexport default function (context) {\n $nuxt.$emit('event-to-emit')\n}\n```\n\n```text\nwindow.$nuxt.$emit\n```\n\n```js\nimport Vue from 'vue'\n\nexport const bus = new Vue()\n\nexport default (_context, inject) => {\n\n // Client only\n if (process.client) {\n // Event bus for plugins\n inject('bus', bus)\n }\n}\n```\n\n```js\n/**\n * Socket that pops open a snackbar\n */\nexport default ({ app: { $bus, $sockets } }) => {\n\n // Incoming message\n $sockets.on('message', payload => {\n\n // When we are on the messages page with the user\n if (window.location.pathname === `/messages/${payload.message.sender.username}`) {\n $bus.$emit('message-conversation', payload)\n }\n // Elsewhere, or messages with a different user\n else {\n $bus.$emit('open-snackbar', {\n body: payload.message.body,\n link: `/messages/${payload.message.sender.username}`,\n user: payload.message.sender\n })\n }\n })\n\n // Incoming notification\n $sockets.on('notification', payload => {\n $bus.$emit('open-snackbar', {\n body: payload.notification.text,\n link: payload.notification.link || '/notifications',\n user: payload.notification.source\n })\n })\n}\n```\n\n```js\n// my-plugin.js\nimport Vue from 'vue'\n\nexport default function ({ $axios, app }, inject){\n\n inject('eventHub', new Vue()); // this is the same as Vue.prototype.$eventHub = new Vue()\n\n // checking for status \n $axios.onError((error) => {\n const code = parseInt(error.response && error.response.status)\n if (code === 401) {\n app.$auth.logout() // logout if errors have happened\n app.$eventHub.$emit('session-expired')\n }\n })\n}\n```\n\n```js\n// login.vue\n\nexport default{\n data(){\n // data\n },\n created(){\n this.$eventHub.$once('session-expired', ()=> {\n this.showAlert()\n })\n },\n methods: {\n showAlert(){\n // display notifcations\n }\n }\n}\n```\n\n```text\n401\n```\n\n========================================\n\nComments:\n- looking at the answer above, they happen to have the same solution.\n- I have `..., target: 'static', ssr: false` in my `nuxt.config.js` In my case I hardcoded `window.$nuxt.$emit('...')` in my plugin, and it worked","metadata":{"transformedAt":"2026-08-18T18:33:07.844Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":215,"estimatedTokens":1170}}162{"id":"stack-73409247","source":"stackoverflow","questionId":73409247,"title":"Nuxt3 - how to use vite-plugin-wasm","tags":["node.js","nuxt.js","webassembly","nuxt3.js"],"text":"Title: Nuxt3 - how to use vite-plugin-wasm\nTags: node.js, nuxt.js, webassembly, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a Nuxt3 application where I need to import and use a 3rd party node package which internally is using webassembly.\n\nIn my case, the package I need is https://github.com/higumachan/lindera-js\n\n### Where do I import the package?\n\nIn one of my components, right at the beginning of the `` tag.\nAnd afterwards I'm using it in one of the methods.\n(Note: I removed unnecessary code below)\n\n```\n\n...\n\nimport * as lindera from \"lindera-js\";\n\n...\n\n methods: {\n doTranspile() {\n const tokenized= lindera.tokenize(this.input);\n console.log(tokenized);\n },\n },\n\n...\n\n```\n\n### What is the Problem?\n\nAfter dev server compiles everything and I reload the page in the browser, I get the following error:\n\n```\n[vite] Internal server error: \"ESM integration proposal for Wasm\" is not supported currently.\nUse vite-plugin-wasm or other community plugins to handle this.\nAlternatively, you can use .wasm?init or .wasm?url.\nSee https://vitejs.dev/guide/features.html#webassembly for more details.\n```\n\n### The Question\n\nHow can I use the package without problems in Nuxt3? Do I have to use `vite-plugin-wasm` and if so, how and where to use/import it?\nOr is there any other way to use a package which is using webassembly?\n\nI found some similar questions on SO, but not sure if they can be used like this in Nuxt3 as I'm fairly new to Nuxt in general.\n\n- How to use embedded Webassembly in Vite?\n\n- How to include an WASM npm module in svelte with vite?\n\n========================================\n\nCode:\n```text\n<template>\n...\n</template>\n\n<script>\nimport * as lindera from \"lindera-js\";\n\n...\n\n methods: {\n doTranspile() {\n const tokenized= lindera.tokenize(this.input);\n console.log(tokenized);\n },\n },\n\n...\n\n</script>\n```\n\n```text\n[vite] Internal server error: \"ESM integration proposal for Wasm\" is not supported currently.\nUse vite-plugin-wasm or other community plugins to handle this.\nAlternatively, you can use .wasm?init or .wasm?url.\nSee https://vitejs.dev/guide/features.html#webassembly for more details.\n```\n\n```text\n<script>\n```\n\n```text\nvite-plugin-wasm\n```\n\n```text\nnpm i -D vite-plugin-wasm\n```\n\n```text\nimport wasm from 'vite-plugin-wasm';\n\nexport default defineNuxtConfig({\n vite: {\n plugins: [wasm()],\n },\n});\n```\n\n```text\nvite-plugin-wasm\n```\n\n```text\nnuxt.config.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.844Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":117,"estimatedTokens":609}}163{"id":"stack-53946183","source":"stackoverflow","questionId":53946183,"title":"VueJS: Google Maps loads before data is ready - how to make it wait? (Nuxt)","tags":["javascript","google-maps","vue.js","nuxt.js","vue2-google-maps"],"text":"Title: VueJS: Google Maps loads before data is ready - how to make it wait? (Nuxt)\nTags: javascript, google-maps, vue.js, nuxt.js, vue2-google-maps\nSource: Stack Overflow\n\nQuestion:\nThis is my first VueJS project and I've got **vue2-google-maps** up and running but I've come across an issue when I attempt to connect the map markers to my site's JSON feed (using the Wordpress REST API), the *Lat* and *Lng* values are returning **undefined** or **NaN**.\n\nOn further investigation (thanks to @QuỳnhNguyễn below) it seems like the Google Maps instance is being run before the data is ready. I have tried watching for the feed to be loaded before initialising the map, but it doesn't seem to work.\n\nThe marker locations are pulled in from the WordPress REST API using JSON and exist in an array (locations). The array is present and populated in Vue Dev Tools (51 records), but when checking on **mounted**, the array is empty. The data is pulled in at the **created** stage, so I don't know why it wouldn't be ready by the mounted stage.\n\nThe code in question is as below...\n\n**Template:**\n\n```\n\n \n \n \n \n \n\n```\n\n**Script**\n\n```\n\n const axios = require('axios');\n const feedURL = \"API_REF\";\n\n export default {\n props: {\n centerRef: {\n type: Object,\n default: function() {\n return { lat: -20.646378400026226, lng: 116.80669825605469 }\n }\n },\n zoomVal: {\n type: Number,\n default: function() {\n return 11\n }\n }\n },\n data: function() {\n return {\n feedLoaded: false,\n zoom: this.zoomVal,\n center: this.centerRef,\n options: {\n mapTypeControl: false,\n streetViewControl: false,\n },\n mapTypeId: 'styledMapType',\n mapIconDestination: '/images/map-pin_destination.png',\n mapIconActivity: '/images/map-pin_activity.png',\n mapIconAccommodation: '/images/map-pin_accommodation.png',\n mapIconEvent: '/images/map-pin_event.png',\n mapIconBusiness: '/images/map-pin_business.png',\n locations: [],\n markers: []\n }\n },\n created: function() {\n this.getData();\n },\n mounted: function() {\n this.$nextTick(() => {\n this.$refs.karrathaMap.$mapPromise.then((map) => {\n var styledMapType = new google.maps.StyledMapType(\n [...MAP_STYLE SETTINGS...]\n )\n map.mapTypes.set('styled_map', styledMapType);\n map.setMapTypeId('styled_map');\n\n })\n\n });\n },\n watch: {\n feedLoaded: function() {\n if (this.feedLoaded == true) {\n console.log(JSON.stringify(this.locations))\n }\n }\n },\n methods: {\n getData() {\n const url = feedURL;\n axios\n .get(url)\n .then((response) => {this.locations = response.data;})\n .then(this.feedLoaded = true)\n .catch( error => { console.log(error); }\n );\n }\n }\n }\n\n```\n\n========================================\n\nTop Answer:\nIt appears to be related with data format. According to `vue-devtools` from provided screenshot your data is returned from WordPress REST API in the following format:\n\n```\n[\n {\n \"acf\": {\n \"place_latitude\": \"-22.695754\",\n \"place_longitude\": \"118.269081\",\n \"place_short-description\": \"Karijini National Park\"\n },\n \"id\": 12,\n \"parent\": 10,\n \"title\": {\n \"rendered\": \"Karijini National Park\"\n }\n },\n ... \n]\n```\n\nHaving how `locations` array is getting initialized (`getData` method), position property could be passed like this: \n\n```\n\n```\n\nHere is a demo\n\n========================================\n\nCode:\n```text\n<template>\n <gmap-map v-if=\"feedLoaded\" ref=\"map\" :center=\"center\" :zoom=\"zoom\" :map-type-id=\"mapTypeId\" :options=\"options\">\n <gmap-marker \n :key=\"index\" v-for=\"(m, index) in locations\" \n :position=\"{ lat: parseFloat(m.place_latitude), lng: parseFloat(m.place_longitude) }\" \n @click=\"toggleInfoWindow(m,index)\" \n :icon=\"mapIconDestination\">\n </gmap-marker>\n <gmap-info-window></gmap-info-window>\n </gmap-map>\n</template>\n```\n\n```text\n<script>\n const axios = require('axios');\n const feedURL = \"API_REF\";\n\n export default {\n props: {\n centerRef: {\n type: Object,\n default: function() {\n return { lat: -20.646378400026226, lng: 116.80669825605469 }\n }\n },\n zoomVal: {\n type: Number,\n default: function() {\n return 11\n }\n }\n },\n data: function() {\n return {\n feedLoaded: false,\n zoom: this.zoomVal,\n center: this.centerRef,\n options: {\n mapTypeControl: false,\n streetViewControl: false,\n },\n mapTypeId: 'styledMapType',\n mapIconDestination: '/images/map-pin_destination.png',\n mapIconActivity: '/images/map-pin_activity.png',\n mapIconAccommodation: '/images/map-pin_accommodation.png',\n mapIconEvent: '/images/map-pin_event.png',\n mapIconBusiness: '/images/map-pin_business.png',\n locations: [],\n markers: []\n }\n },\n created: function() {\n this.getData();\n },\n mounted: function() {\n this.$nextTick(() => {\n this.$refs.karrathaMap.$mapPromise.then((map) => {\n var styledMapType = new google.maps.StyledMapType(\n [...MAP_STYLE SETTINGS...]\n )\n map.mapTypes.set('styled_map', styledMapType);\n map.setMapTypeId('styled_map');\n\n })\n\n });\n },\n watch: {\n feedLoaded: function() {\n if (this.feedLoaded == true) {\n console.log(JSON.stringify(this.locations))\n }\n }\n },\n methods: {\n getData() {\n const url = feedURL;\n axios\n .get(url)\n .then((response) => {this.locations = response.data;})\n .then(this.feedLoaded = true)\n .catch( error => { console.log(error); }\n );\n }\n }\n }\n</script>\n```\n\n```text\nwatch: {\n feedLoaded: function() {\n if (this.feedLoaded == true) {\n\n var LocationList = this.locations;\n\n for (var i = 0; i < LocationList.length; i++) {\n var includeOnMap = LocationList[i].acf['place_include-on-map'];\n\n if (includeOnMap === true) {\n var placeName = LocationList[i].title.rendered;\n var placeDescription = LocationList[i].acf['place_short-description'];\n var placeLatitude = LocationList[i].acf['place_latitude'];\n var placeLongitude = LocationList[i].acf['place_longitude'];\n var placeIcon = this.mapIconDestination;\n\n this.markers.push({ name: placeName, lat: placeLatitude, lng: placeLongitude, icon: placeIcon });\n }\n\n }\n }\n }\n}\n```\n\n```text\n<gmap-map ref=\"karrathaMap\" :center=\"center\" :zoom=\"zoom\" :map-type-id=\"mapTypeId\" :options=\"options\">\n <gmap-marker v-if=\"feedLoaded == true\" :key=\"index\" v-for=\"(m, index) in markers\" :position=\"{ lat: parseFloat(m.lat), lng: parseFloat(m.lng) }\" @click=\"toggleInfoWindow(m,index)\" :icon=\"m.icon\"></gmap-marker>\n <gmap-info-window></gmap-info-window>\n</gmap-map>\n```\n\n```text\n<template>\n <div id=\"map\" v-if=\"loaded\">\n <gmap-map ref=\"map\" :center=\"center\" :zoom=\"zoom\" :map-type-id=\"mapTypeId\" :options=\"options\">\n <gmap-marker\n :key=\"index\" v-for=\"(m, index) in locations\"\n :position=\"{ lat: parseFloat(m.place_latitude), lng: parseFloat(m.place_longitude) }\"\n @click=\"toggleInfoWindow(m,index)\"\n :icon=\"mapIconDestination\">\n </gmap-marker>\n <gmap-info-window></gmap-info-window>\n </gmap-map>\n </div>\n</template>\n\n\n<script>\n export default {\n data() {\n return {\n loaded: false\n }\n },\n beforeMount: function () {\n const url = feedURL;\n axios\n .get(url)\n .then((response) => {\n this.locations = response.data;\n //activate element after api call response recieved\n this.loaded = true\n })\n .catch(error => {\n console.log(error);\n }\n );\n }\n }\n\n</script>\n```\n\n```text\n[\n {\n \"acf\": {\n \"place_latitude\": \"-22.695754\",\n \"place_longitude\": \"118.269081\",\n \"place_short-description\": \"Karijini National Park\"\n },\n \"id\": 12,\n \"parent\": 10,\n \"title\": {\n \"rendered\": \"Karijini National Park\"\n }\n },\n ... \n]\n```\n\n```text\n<gmap-marker\n :key=\"index\"\n v-for=\"(m, index) in locations\"\n :position=\"{ lat: parseFloat(m.acf.place_latitude), lng: parseFloat(m.acf.place_longitude) }\"\n></gmap-marker>\n```\n\n```text\nvue-devtools\n```\n\n```text\nlocations\n```\n\n```text\ngetData\n```\n\n========================================\n\nComments:\n- Please try this: `:position=\"google && new google.maps.LatLng(parseFloat(m.place_latitude), parseFloat(m.place_longitude))\"`\n- If it's not work please try to hardcode `lat, lng` via a number\n- @QuỳnhNguyễn Won't that create a new instance of the map for each marker? Also, it works with hard-coded values.\n- No it's only check `google` is available for create new marker.\n- @QuỳnhNguyễn I've tried your code and it comes back with position: undefined. I cannot use hard-coded values as the data comes from the WordPress REST API (JSON feed).\n- That's mean `m.place_latitude` undefined. Can you please show your `console.log(locations)`?\n- @QuỳnhNguyễn Some additional info - I now get \"Property or method \"google\" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: vuejs.org/v2/guide/….\" in the console. I can't access \"locations\" in the console as it's a Vue app. My Vue dev tools show the array exists and is populated.\n- @QuỳnhNguyễn Here is the content of the array: locations:Array[51] 0:Object 1:Object acf:Object place_include-on-map:true place_latitude:\"-22.695754\" place_longitude:\"118.269081\" place_short-description:\"An outback playground of natural wonders\" id:12 parent:10 title:Object rendered:\"Karijini National Park\"\n- Please show your `console.log(JSON.stringify(locations))`\n- I'm pretty sure problem come from your data format.\n- Let us continue this discussion in chat.\n- I already have something like that setup, as you can see in the code (sorry the `v-if` on the component was missing in my example, I will put it back) - I still get `NaN` reutrned for the `LatLng`, and no markers.\n- @AlxTheRed Try to add `mounted() {setTimeout(() => this.loaded = true, 2000)}` and remove it from then. If you do this, please tell me if `LatLng` is still a `NaN`.\n- @ulou I increased the timeout to 5 seconds, and I now get the locations returned in the console.log, but the value is still `NaN`. I think my reference to the values is wrong, but nothing I try works... `[{\"id\":12,\"title\":{\"rendered\":\"Karijini National Park\"},\"parent\":10,\"acf\":{\"place_include-on-map\":true,\"place‌​_short-description\":‌​\"An outback playground of natural wonders\",\"place_latitude\":\"-22.695754\",\"place_longitude\":\"11‌​8.269081\"}}...]`\n- The undefined error was due to some of the entries in the JSON feed not having the necessary feeds. I have explained it in my answer below. Thank you both for your help!\n- This is what the console.log for locations returns: `Locations returned: [{\"id\":10,\"title\":{\"rendered\":\"Explore\"},\"parent\":0},{\"id\":1‌​2,\"title\":{\"rendered‌​\":\"Karijini National Park\"},\"parent\":10,\"acf\":{\"place_include-on-map\":true,\"place‌​_short-description\":‌​\"An outback playground of natural wonders\",\"place_latitude\":\"-22.695754\",\"place_longitude\":\"11‌​8.269081\"}},{\"id\":14‌​,\"title\":{\"rendered\"‌​:\"Karratha\"},\"parent‌​\":10,\"acf\":{\"place_i‌​nclude-on-map\":true,‌​\"place_short-descrip‌​tion\":\"A bustling city in the Pilbara\",\"place_latitude\":\"-20.735350\",\"place_longitude\":\"11‌​6.845802\"}}..]`\n- The undefined error was due to some of the entries in the JSON feed not having the necessary feeds. I have explained it in my answer below. Thanks for your help!\n- im getting an error on this \"This 'v-if' should be moved to the wrapper element\" cannot set v-if with v-for in the same element. any solution to that?","metadata":{"transformedAt":"2026-08-18T18:33:07.844Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":363,"estimatedTokens":3129}}164{"id":"stack-58917958","source":"stackoverflow","questionId":58917958,"title":"@nuxtjs/auth Why refresh page always redirect to login","tags":["vue.js","nuxt.js"],"text":"Title: @nuxtjs/auth Why refresh page always redirect to login\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI can't refresh page or open new tab of secure page after refresh or new tab will redirect me to login \nagain\n\n**Version**\n\n```\nNuxt.js v2.9.1\n@nuxtjs/module: 4.8.4\n```\n\n**secure page**\n\n```\nmiddleware: ['auth'],\n```\n\n*middleware of auth-module*\n\n**login page**\n\n```\nmiddleware: ['guest'],\n```\n\n**middleware/guest.js**\n\n```\nexport default async function({ store, redirect }) {\n // console.log(store.state.auth)\n if (store.state.auth.loggedIn) {\n return redirect('/')\n }\n}\n```\n\n*console.log(store.state.auth) = { user: null, loggedIn: false, strategy: 'local' }*\n\n**nuxt.config.js**\n\n```\nauth: {\n strategies: {\n local: {\n endpoints: {\n // register: { url: 'member', method: 'post', propertyName: 'data.accessToken' },\n login: { url: 'api/authen-admin', method: 'post', propertyName: 'custom' },\n user: { url: 'api/admin', method: 'get', propertyName: 'custom' },\n logout: false\n },\n tokenRequired: 'Authorization',\n tokenType: false\n }\n },\n watchLoggedIn: true,\n localStorage: {\n prefix: 'auth.'\n },\n cookie: {\n prefix: 'auth.', // Default token prefix used in building a key for token storage in the browser's localStorage.\n options: {\n path: '/', // Path where the cookie is visible. Default is '/'.\n expires: 5 // Can be used to specify cookie lifetime in Number of days or specific Date. Default is session only.\n // domain: '', // Domain (and by extension subdomain/s) where the cookie is visible. Default is domain and all subdomains.\n // secure - false, // Sets whether the cookie requires a secure protocol (https). Default is false, should be set to true if possible.\n }\n },\n redirect: {\n login: '/login',\n logout: '/login',\n home: '/'\n },\n resetOnError: true\n}\n```\n\nI try to use **vuex-persist** to persist local storage but doesn't work and when login not redirect to home path still stay login path\n\n========================================\n\nTop Answer:\nExtending Fauzan Edris answer.\n\nI was using Auth Nuxt, following fixed my issue.\n\n```\nexport const actions = {\n async nuxtServerInit({\n commit\n }, {\n req\n }) {\n let auth = null\n if (req.headers.cookie) {\n // cookie found\n try {\n // check data user login with cookie\n const {\n data\n } = await this.$axios.post('/user/profile')\n // server return the data is cookie valid loggedIn is true\n auth = data.data // set the data auth\n } catch (err) {\n // No valid cookie found\n auth = null\n }\n }\n\n // How we can set the user for AuthNuxt\n // Source: https://auth.nuxtjs.org/api/auth\n this.$auth.setUser(auth)\n },\n}\n```\n\n========================================\n\nCode:\n```text\nNuxt.js v2.9.1\n@nuxtjs/module: 4.8.4\n```\n\n```text\nmiddleware: ['auth'],\n```\n\n```text\nmiddleware: ['guest'],\n```\n\n```text\nexport default async function({ store, redirect }) {\n // console.log(store.state.auth)\n if (store.state.auth.loggedIn) {\n return redirect('/')\n }\n}\n```\n\n```text\nauth: {\n strategies: {\n local: {\n endpoints: {\n // register: { url: 'member', method: 'post', propertyName: 'data.accessToken' },\n login: { url: 'api/authen-admin', method: 'post', propertyName: 'custom' },\n user: { url: 'api/admin', method: 'get', propertyName: 'custom' },\n logout: false\n },\n tokenRequired: 'Authorization',\n tokenType: false\n }\n },\n watchLoggedIn: true,\n localStorage: {\n prefix: 'auth.'\n },\n cookie: {\n prefix: 'auth.', // Default token prefix used in building a key for token storage in the browser's localStorage.\n options: {\n path: '/', // Path where the cookie is visible. Default is '/'.\n expires: 5 // Can be used to specify cookie lifetime in Number of days or specific Date. Default is session only.\n // domain: '', // Domain (and by extension subdomain/s) where the cookie is visible. Default is domain and all subdomains.\n // secure - false, // Sets whether the cookie requires a secure protocol (https). Default is false, should be set to true if possible.\n }\n },\n redirect: {\n login: '/login',\n logout: '/login',\n home: '/'\n },\n resetOnError: true\n}\n```\n\n```text\nexport const actions = {\n async nuxtServerInit ({ commit }, { req }) {\n let auth = null\n if (req.headers.cookie) {\n // cookie found\n try {\n // check data user login with cookie\n const { data } = await this.$axios.post('/api/auths/me')\n // server return the data is cookie valid loggedIn is true\n auth = data // set the data auth\n } catch (err) {\n // No valid cookie found\n auth = null\n }\n }\n commit('SET_AUTH', auth) // set state auth\n },\n}\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nstore/index.js\n```\n\n```text\nlet user = await this.$auth.requestWith(\n 'local', null, { url: 'api/admin', method: 'get', propertyName: 'custom' } );\nconsole.log(user);\n```\n\n```text\npropertyName\n```\n\n```text\n'custom'\n```\n\n```text\nfetchUser\n```\n\n```text\nexport const actions = {\n async nuxtServerInit({\n commit\n }, {\n req\n }) {\n let auth = null\n if (req.headers.cookie) {\n // cookie found\n try {\n // check data user login with cookie\n const {\n data\n } = await this.$axios.post('/user/profile')\n // server return the data is cookie valid loggedIn is true\n auth = data.data // set the data auth\n } catch (err) {\n // No valid cookie found\n auth = null\n }\n }\n\n // How we can set the user for AuthNuxt\n // Source: https://auth.nuxtjs.org/api/auth\n this.$auth.setUser(auth)\n },\n}\n```\n\n```text\n[404] /api/admin\n```\n\n```text\nauth: {\n strategies: {\n local: {\n endpoints: {\n user: { url: `${BASE_URL}/api/admin`, ... },\n ...\n}\n```\n\n```text\nself signed certificate\n\n at TLSSocket.onConnectSecure (_tls_wrap.js:1502:34)\n at TLSSocket.emit (events.js:314:20)\n at TLSSocket._finishInit (_tls_wrap.js:937:8)\n at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:711:12)\n```\n\n```text\n// plugins/axios.js\n\nimport https from 'https';\n\nexport default function ({ $axios, redirect }) {\n\n // I want to ignore SSL errors on TEST ONLY (and dev too), because I will use a self-signed certificate there\n if (process.env.APP_ENVIRONMENT !== 'production') {\n $axios.defaults.httpsAgent = new https.Agent({ rejectUnauthorized: false });\n }\n\n// other stuff ...\n\n}\n```\n\n```text\n// nuxt.config.js\n\n// ...\n\nauth: {\n redirect: {\n // ...\n },\n strategies: {\n // ...\n },\n plugins: [\n {\n src: '~/plugins/axios',\n ssr: true\n }\n ]\n },\n\n// ...\n```\n\n========================================\n\nComments:\n- Hey! this is Jeffrey from @VueScreencasts. Thanks for making this and adding the code. \"I try to use vuex-persist to persist local storage but doesn't work\" - Two thoughts: 1. I didn't have to use an extra library to make localstorage or cookies persist. Could vuex-persist be interfering? 2. What do you mean by \"doesn't work\"? Is it not storing cookies at all? Or is it storing cookies but not sending them to the server? Or is it sending them to the server, but the authentication is wrong?\n- @JeffreyBiles 1. I don't use extra library to make localstrorage or cookies same like you. 2. \"doesn't work\" it mean when i use vuex-persist @nuxtjs/auth not redirect when login success but uninstall vuex-persist then @nuxtjs/auth redirect when login success\n- \"Vuex-persist\" is the extra library, and since it works when you uninstall vuex-persist, I think we have our answer. If you need to use vuex-persist for other things, then you should ask someone who's used that library before, since the bug seems to be in vuex-persist rather than Nuxt Auth.\n- Sorry to make you confuse, When i use only Nuxt Auth it don't work it can't refresh page then i try to use \"Vuex-persist\" to persist localstorage or cookie then state not empty but bug with nuxt auth when login success nuxt auth can't redirect to secure page","metadata":{"transformedAt":"2026-08-18T18:33:07.844Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":327,"estimatedTokens":2057}}165{"id":"stack-62115781","source":"stackoverflow","questionId":62115781,"title":"Laravel Sanctum : blocked by CORS policy with Nuxt Auth module","tags":["cors","nuxt.js","laravel-7","laravel-valet","laravel-sanctum"],"text":"Title: Laravel Sanctum : blocked by CORS policy with Nuxt Auth module\nTags: cors, nuxt.js, laravel-7, laravel-valet, laravel-sanctum\nSource: Stack Overflow\n\nQuestion:\nI have a **Laravel** website served by Valet on `backend.test` and a **Nuxt** SPA on `nuxt.backend.test:3005`. When I try to authenticate to Sanctum with Nuxt Auth module, I get the CORS error below:\n\n Access to XMLHttpRequest at 'http://backend.test/login' from origin\n 'http://nuxt.backend.test:3005' has been blocked by CORS policy: No\n 'Access-Control-Allow-Origin' header is present on the requested\n resource.\n\nHow can I fix it ?\n\n**Laravel configuration**\n\n`config/cors.php`:\n\n```\n ['*'],\n 'allowed_methods' => ['*'],\n 'allowed_origins' => ['*'],\n 'allowed_origins_patterns' => [],\n 'allowed_headers' => ['*'],\n 'exposed_headers' => [],\n 'max_age' => 0,\n 'supports_credentials' => true,\n];\n```\n\n`routes/api.php`:\n\n```\nRoute::middleware('auth:sanctum')->get('/user', function (Request $request) {\n return $request->user();\n});\n```\n\n`app/Http/Kernel.php`:\n\n```\nprotected $middlewareGroups = [\n ...\n 'api' => [\n EnsureFrontendRequestsAreStateful::class,\n 'throttle:60,1',\n \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\n ],\n ];\n```\n\n`.env`:\n\n```\nSANCTUM_STATEFUL_DOMAINS=\"backend.test\"\nSESSION_DOMAIN=\".backend.test\"\n```\n\n**Nuxt configuration**\n`nuxt.config.js`:\n\n```\nexport default {\n server: {\n port: '3005',\n host: 'nuxt.backend.test'\n },\n ...\n modules: [\n '@nuxtjs/axios',\n '@nuxtjs/auth-next'\n ],\n axios: {\n proxy: true\n },\n proxy: {\n '/nuxt': {\n target: 'nuxt.backend.test',\n pathRewrite: { '^/nuxt': '/' }\n }\n },\n auth: {\n redirect: {\n callback: '/auth/callback'\n },\n strategies: {\n laravelSanctum: {\n provider: 'laravel/sanctum',\n url: 'http://backend.test'\n }\n }\n },\n ...\n}\n```\n\n`pages/index.php`:\n\n```\n\n \n \n {{ $auth.user }}\n \n Sign in\n \n\nexport default {\n methods: {\n signIn() {\n this.$auth.loginWith('laravelSanctum', {\n data: {\n email: 'me@home.com',\n password: '1qaz@WSX'\n }\n })\n }\n }\n}\n\n```\n\n========================================\n\nCode:\n```text\n<?php\n\nreturn [\n 'paths' => ['*'],\n 'allowed_methods' => ['*'],\n 'allowed_origins' => ['*'],\n 'allowed_origins_patterns' => [],\n 'allowed_headers' => ['*'],\n 'exposed_headers' => [],\n 'max_age' => 0,\n 'supports_credentials' => true,\n];\n```\n\n```text\nRoute::middleware('auth:sanctum')->get('/user', function (Request $request) {\n return $request->user();\n});\n```\n\n```text\nprotected $middlewareGroups = [\n ...\n 'api' => [\n EnsureFrontendRequestsAreStateful::class,\n 'throttle:60,1',\n \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\n ],\n ];\n```\n\n```text\nSANCTUM_STATEFUL_DOMAINS=\"backend.test\"\nSESSION_DOMAIN=\".backend.test\"\n```\n\n```text\nexport default {\n server: {\n port: '3005',\n host: 'nuxt.backend.test'\n },\n ...\n modules: [\n '@nuxtjs/axios',\n '@nuxtjs/auth-next'\n ],\n axios: {\n proxy: true\n },\n proxy: {\n '/nuxt': {\n target: 'nuxt.backend.test',\n pathRewrite: { '^/nuxt': '/' }\n }\n },\n auth: {\n redirect: {\n callback: '/auth/callback'\n },\n strategies: {\n laravelSanctum: {\n provider: 'laravel/sanctum',\n url: 'http://backend.test'\n }\n }\n },\n ...\n}\n```\n\n```text\n<template>\n <div>\n <div>\n <pre>{{ $auth.user }}</pre>\n </div>\n <button @click=\"signIn()\">Sign in</button>\n </div>\n</template>\n\n<script>\nexport default {\n methods: {\n signIn() {\n this.$auth.loginWith('laravelSanctum', {\n data: {\n email: 'me@home.com',\n password: '1qaz@WSX'\n }\n })\n }\n }\n}\n</script>\n```\n\n```text\nbackend.test\n```\n\n```text\nnuxt.backend.test:3005\n```\n\n```text\nconfig/cors.php\n```\n\n```text\nroutes/api.php\n```\n\n```text\napp/Http/Kernel.php\n```\n\n```text\n.env\n```\n\n```text\nnuxt.config.js\n```\n\n```text\npages/index.php\n```\n\n```text\n127.0.0.1 nuxt.backend.test\n```\n\n```text\nnpm remove @nuxtjs/auth\nnpm install @nuxtjs/auth-next @nuxtjs/axios\n```\n\n```text\nmodules: [\n '@nuxtjs/axios',\n '@nuxtjs/auth-next'\n ],\n```\n\n```text\n{\n axios: {\n proxy: true\n },\n proxy: {\n '/laravel': {\n target: 'http://backend.test',\n pathRewrite: { '^/laravel': '/' }\n }\n },\n auth: {\n strategies: {\n laravelSanctum: {\n provider: 'laravel/sanctum',\n url: '/laravel'\n }\n }\n }\n}\n```\n\n```text\n/etc/hosts\n```\n\n```text\n@nuxt/auth\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nbackend.test\n```\n\n```text\nnuxt.backend.test\n```\n\n```text\nlocalhost\n```\n\n```text\nhost\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nphp artisan serve\n```\n\n========================================\n\nComments:\n- I'm trying to make Nuxt work with Laravel's Sanctum but i have encountered few issues. I want know if you have a full working example or a code base I can use?\n- @xperator Unfortunately not. I'm now using Laravel Passport which better fits my needs.\n- Ah I see.. For me I spent like 3 days to get the basic login page to work. Right now the problem is when I enable `auth` middleware, the app keeps redirecting to the `/login` page even though the `this.$auth.loggedIn` is `true` and the `api/user/` from laravel side returns the right user information\n- I'm wondering if Laravel Passport is more or less of the same experience..? I just want a very simple classic user/pass login authentication, no fancy tokens or social network auth is needed","metadata":{"transformedAt":"2026-08-18T18:33:07.845Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":27,"totalLines":336,"estimatedTokens":1355}}166{"id":"stack-73060041","source":"stackoverflow","questionId":73060041,"title":"Nuxt 3 - onServerPrefetch Lifecycle injection APIs","tags":["node.js","vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: Nuxt 3 - onServerPrefetch Lifecycle injection APIs\nTags: node.js, vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\n[Vue warn]: onServerPrefetch is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.\n\nComposable\n\n```\nconst isLoggerdIn = () => {\n return expire.value //return true or false\n }\n```\n\nMiddleware\n\n```\nexport default defineNuxtRouteMiddleware( (to) => {\n const { isLoggerdIn } = useAuth() // composable\n\n if (isLoggerdIn() && to.name == 'login'){\n return navigateTo(\"/home\")\n }\n\n if (!isLoggerdIn() && to.name !== 'login'){\n return navigateTo(\"/login\")\n }\n\n})\n```\n\nOn pages home and login\n\n```\ndefinePageMeta({\n middleware: 'auth'\n})\n```\n\n========================================\n\nCode:\n```text\nconst isLoggerdIn = () => {\n return expire.value //return true or false\n }\n```\n\n```text\nexport default defineNuxtRouteMiddleware( (to) => {\n const { isLoggerdIn } = useAuth() // composable\n\n if (isLoggerdIn() && to.name == 'login'){\n return navigateTo(\"/home\")\n }\n\n if (!isLoggerdIn() && to.name !== 'login'){\n return navigateTo(\"/login\")\n }\n\n})\n```\n\n```text\ndefinePageMeta({\n middleware: 'auth'\n})\n```\n\n```js\n👇\nimport { callWithNuxt } from 'nuxt/app'\n\nexport default defineNuxtRouteMiddleware( (to) => {\n const { isLoggerdIn } = useAuth() // composable\n 👇\n const nuxtInstance = useNuxtApp()\n\n if (isLoggerdIn() && to.name == 'login'){\n 👇\n return callWithNuxt(nuxtInstance, () => navigateTo(\"/home\"))\n }\n\n if (!isLoggerdIn() && to.name !== 'login'){\n 👇\n return callWithNuxt(nuxtInstance, () => navigateTo(\"/login\"))\n }\n\n})\n```\n\n```text\nisLoggerdIn\n```\n\n```text\nuseAsyncData\n```\n\n```text\nuseFetch\n```\n\n```text\nnavigateTo\n```\n\n```text\nnuxt instance not available\n```\n\n```text\ncallWithNuxt\n```\n\n```text\nnavigateTo\n```\n\n========================================\n\nComments:\n- I think the issue is in `useAuth` could you add to the question the content of this util ?","metadata":{"transformedAt":"2026-08-18T18:33:07.845Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":124,"estimatedTokens":532}}167{"id":"stack-70615613","source":"stackoverflow","questionId":70615613,"title":"Apollo Client \"Named export 'remove' not found\"","tags":["javascript","vue.js","nuxt.js","apollo-client","nuxt3.js"],"text":"Title: Apollo Client \"Named export 'remove' not found\"\nTags: javascript, vue.js, nuxt.js, apollo-client, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm attempting to create an `apollo client` plugin for a `Nuxt 3` application. It's currently throwing an error regarding a package called `ts-invariant`:\n\n```\nfile:///Users/[my name]/Repositories/[project]/node_modules/@apollo/client/utilities/globals/fix-graphql.js:1\nimport { remove } from \"ts-invariant/process/index.js\";\n ^^^^^^\nSyntaxError: Named export 'remove' not found. The requested module 'ts-invariant/process/index.js' is a CommonJS module, which may not support all module.exports as named exports.\nCommonJS modules can always be imported via the default export, for example using:\n\nimport pkg from 'ts-invariant/process/index.js';\nconst { remove } = pkg;\n\n at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)\n at async ModuleJob.run (node:internal/modules/esm/module_job:181:5)\n at async Promise.all (index 0)\n at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n at async __instantiateModule__ (file:///Users/[my name]/Repositories/[project]/.nuxt/dist/server/server.mjs:4550:3)\n[vite dev] Error loading external \"/Users/[my name]/Repositories/[project]/node_modules/@apollo/client/core/index.js\".\n at file://./.nuxt/dist/server/server.mjs:3170:289 \n at async __instantiateModule__ (file://./.nuxt/dist/server/server.mjs:4550:3)\n```\n\n**I feel like I know enough about this error to know it has something to do with how Nuxt 3 deals with ESM, but I can't be for certain.**\n\nHere's the nuxt plugin: \n\n`plugins/apollo-client.js`\n\n```\nimport { defineNuxtPlugin } from \"#app\"\nimport { ApolloClient, InMemoryCache } from \"@apollo/client/core\"\nimport { DefaultApolloClient } from \"@vue/apollo-composable\"\n\nexport default defineNuxtPlugin((nuxtApp) => {\n const config = useRuntimeConfig()\n const apolloClient = new ApolloClient({\n uri: config.PUBLIC_API_ENDPOINT,\n cache: new InMemoryCache(),\n })\n nuxtApp.vueApp.provide(DefaultApolloClient, apolloClient)\n})\n```\n\nIn a normal scenario, I might use the nuxt-apollo community module, but it is currently afk regarding a `nuxt 3` port, so a plugin it is.\n\nHere's some documentation I relied on for my plugin:\n\nhttps://v4.apollo.vuejs.org/guide-composable/setup.html#vue-3\n\nhttps://v3.nuxtjs.org/docs/directory-structure/plugins\n\n========================================\n\nTop Answer:\nI think I've pinpointed the underlying issue. Apollo Client (3.5.10 at the time of writing early 2022) is using `\"module\":\"index.js\"` to declare the path of the ESM exports.\nHowever it seems that Webpack 5 based bundlers do not support this. Using `exports` in the package.json fixes it for good for me.\n\nYou should upvote this feature request.\n\nAnd here is my palliative until then, using a small script to alter the package.json.\n\n========================================\n\nCode:\n```sh\nfile:///Users/[my name]/Repositories/[project]/node_modules/@apollo/client/utilities/globals/fix-graphql.js:1\nimport { remove } from \"ts-invariant/process/index.js\";\n ^^^^^^\nSyntaxError: Named export 'remove' not found. The requested module 'ts-invariant/process/index.js' is a CommonJS module, which may not support all module.exports as named exports.\nCommonJS modules can always be imported via the default export, for example using:\n\nimport pkg from 'ts-invariant/process/index.js';\nconst { remove } = pkg;\n\n at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)\n at async ModuleJob.run (node:internal/modules/esm/module_job:181:5)\n at async Promise.all (index 0)\n at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n at async __instantiateModule__ (file:///Users/[my name]/Repositories/[project]/.nuxt/dist/server/server.mjs:4550:3)\n[vite dev] Error loading external \"/Users/[my name]/Repositories/[project]/node_modules/@apollo/client/core/index.js\".\n at file://./.nuxt/dist/server/server.mjs:3170:289 \n at async __instantiateModule__ (file://./.nuxt/dist/server/server.mjs:4550:3)\n```\n\n```js\nimport { defineNuxtPlugin } from \"#app\"\nimport { ApolloClient, InMemoryCache } from \"@apollo/client/core\"\nimport { DefaultApolloClient } from \"@vue/apollo-composable\"\n\nexport default defineNuxtPlugin((nuxtApp) => {\n const config = useRuntimeConfig()\n const apolloClient = new ApolloClient({\n uri: config.PUBLIC_API_ENDPOINT,\n cache: new InMemoryCache(),\n })\n nuxtApp.vueApp.provide(DefaultApolloClient, apolloClient)\n})\n```\n\n```text\napollo client\n```\n\n```text\nNuxt 3\n```\n\n```text\nts-invariant\n```\n\n```text\nplugins/apollo-client.js\n```\n\n```text\nnuxt 3\n```\n\n```js\n// nuxt.config.js\n // ...\n build: {\n postcss: {\n postcssOptions: require('./postcss.config.js')\n },\n transpile: [\n '@apollo/client',\n 'ts-invariant/process',\n ],\n },\n // ...\n```\n\n```text\n@apollo/client\n```\n\n```text\nts-invariant/process\n```\n\n```text\n\"module\":\"index.js\"\n```\n\n```text\nexports\n```\n\n```text\n{\n test: /\\.m?js$/,\n resolve: {\n fullySpecified: false,\n },\n include: [\n 'graphql',\n ].map((name) => new RegExp(`node_modules/${name}`)),\n },\n```\n\n```text\ninclude\n```\n\n========================================\n\nComments:\n- I've made some progress by manually altering the package.json: github.com/apollographql/apollo-feature-requests/issues/… The lack of exports (in the latest version 3.5.10 I've tested) in @apollo/client and ts-invariant might cause this for Weback 5 based builds\n- I'm currently using Vite instead of Webpack, but thanks for contributing!\n- And Vite handles this out of the box?\n- No it doesn't sadly","metadata":{"transformedAt":"2026-08-18T18:33:07.845Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":178,"estimatedTokens":1408}}168{"id":"stack-57403003","source":"stackoverflow","questionId":57403003,"title":"Errors while building Nuxt.js programmatically from Express server","tags":["node.js","express","vue.js","nuxt.js"],"text":"Title: Errors while building Nuxt.js programmatically from Express server\nTags: node.js, express, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to run Nuxt programmatically from my Express server, but I am getting some errors after the application is built and I open my browser console:\n\nhttps://i.sstatic.net/MZxHk.png\n\nhttps://i.sstatic.net/sfDIF.png\n\nMy nuxt.config.ts looks like:\n\n```\nimport NuxtConfiguration from '@nuxt/config';\n\n/**\n * Nuxt.js admin console app config.\n */\nexport const config: NuxtConfiguration = {\n /**\n * Directory paths options. Remove `rootDir` and `modulesDir` properties if you want to run/build admin console Nuxt app.\n */\n rootDir: 'src/admin-console',\n modulesDir: ['../../node_modules'],\n mode: 'universal',\n /*\n ** Headers of the page.\n */\n head: {\n title: process.env.npm_package_name || '',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: process.env.npm_package_description || '' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n /*\n ** Customize the progress-bar color.\n */\n loading: { color: '#fff' },\n /*\n ** Global CSS.\n */\n css: [\n ],\n /*\n ** Plugins to load before mounting the App.\n */\n plugins: [\n ],\n /*\n ** Nuxt.js modules.\n */\n modules: [\n // Doc: https://bootstrap-vue.js.org/docs/\n 'bootstrap-vue/nuxt',\n // Doc: https://axios.nuxtjs.org/usage\n '@nuxtjs/axios',\n ],\n /*\n ** Axios module configuration.\n ** See https://axios.nuxtjs.org/options\n */\n axios: {\n },\n};\n\nexport default config;\n```\n\nAnd I start Nuxt build as Express middleware:\n\n```\nimport { Application } from 'express';\nimport { Nuxt, Builder } from 'nuxt';\nimport config from '../admin-console/nuxt.config';\n\n/**\n * Builds admin console Nuxt app.\n * @param app Express application instance.\n */\nexport async function buildAdminConsoleNuxtApp(app: Application) {\n const nuxt = new Nuxt(config);\n try {\n await new Builder(nuxt).build();\n } catch (error) {\n throw new Error(error);\n }\n\n app.use('/admin', nuxt.render);\n}\n```\n\nand register it like:\n\n```\nawait buildAdminConsoleNuxtApp(this.app);\n```\n\nIn all of the examples I found, this was the only way of building Nuxt, so I don't know what I am doing wrong. The built application doesn't detect click events etc. and doesn't function as it should.\n\n========================================\n\nCode:\n```text\nimport NuxtConfiguration from '@nuxt/config';\n\n/**\n * Nuxt.js admin console app config.\n */\nexport const config: NuxtConfiguration = {\n /**\n * Directory paths options. Remove `rootDir` and `modulesDir` properties if you want to run/build admin console Nuxt app.\n */\n rootDir: 'src/admin-console',\n modulesDir: ['../../node_modules'],\n mode: 'universal',\n /*\n ** Headers of the page.\n */\n head: {\n title: process.env.npm_package_name || '',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: process.env.npm_package_description || '' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n /*\n ** Customize the progress-bar color.\n */\n loading: { color: '#fff' },\n /*\n ** Global CSS.\n */\n css: [\n ],\n /*\n ** Plugins to load before mounting the App.\n */\n plugins: [\n ],\n /*\n ** Nuxt.js modules.\n */\n modules: [\n // Doc: https://bootstrap-vue.js.org/docs/\n 'bootstrap-vue/nuxt',\n // Doc: https://axios.nuxtjs.org/usage\n '@nuxtjs/axios',\n ],\n /*\n ** Axios module configuration.\n ** See https://axios.nuxtjs.org/options\n */\n axios: {\n },\n};\n\nexport default config;\n```\n\n```text\nimport { Application } from 'express';\nimport { Nuxt, Builder } from 'nuxt';\nimport config from '../admin-console/nuxt.config';\n\n/**\n * Builds admin console Nuxt app.\n * @param app Express application instance.\n */\nexport async function buildAdminConsoleNuxtApp(app: Application) {\n const nuxt = new Nuxt(config);\n try {\n await new Builder(nuxt).build();\n } catch (error) {\n throw new Error(error);\n }\n\n app.use('/admin', nuxt.render);\n}\n```\n\n```text\nawait buildAdminConsoleNuxtApp(this.app);\n```\n\n```text\nimport { Application } from 'express';\nimport { Nuxt, Builder, Generator } from 'nuxt';\nimport config from '../admin-console/nuxt.config';\nimport { EnvType } from '../config/types';\n\n/**\n * Builds admin console Nuxt.js/Vue.js application.\n * @param app Express application instance.\n */ \nexport async function buildAdminConsoleNuxtApp(app: Application) {\n config.dev = process.env.NODE_ENV === EnvType.PRODUCTION;\n const nuxt = new Nuxt(config);\n try {\n const builder = await new Builder(nuxt);\n await new Generator(nuxt, builder).generate({ build: true, init: true });\n } catch (error) {\n throw new Error(error);\n }\n\n app.use('/', nuxt.render);\n}\n```\n\n```text\nconfig.dev\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.845Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":221,"estimatedTokens":1233}}169{"id":"stack-53821555","source":"stackoverflow","questionId":53821555,"title":"How to refresh the data obtained by Async Data() in NuxtJs?","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: How to refresh the data obtained by Async Data() in NuxtJs?\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn NuxtJs app i got data() on server side by AsyncData() method.\n\nFor example, I need to delete one entry and refresh the page without restarting the browser. \n\nIn pure Vue, I would write an ajax method to update the data from the server after removal. Usually this method is the same as for the initial load and it is located in \"mounted\". But NuxtJs can't I access a method async Data() again. Or can I?\n\n```\nasync asyncData({$axios, params}) {\n const {data} = await $axios.$get(`/topics/${params.id}`)\n\n return {\n topic: data\n }\n },\n\n -------------------------\n\n async deletePost(id) {\n await this.$axios.$delete(`/topics/${this.topic.id}/posts/${id}`)\n // bad idea - hard reset\n window.location.reload(true)\n //how refresh by asyncData()?\n },\n```\n\n========================================\n\nTop Answer:\nThis is easily done using the `$nuxt` helper, in any component:\n\n```\nawait this.$nuxt.refresh()\n```\n\nSee https://nuxtjs.org/docs/internals-glossary/$nuxt/#refreshing-page-data\n\n========================================\n\nCode:\n```text\nasync asyncData({$axios, params}) {\n const {data} = await $axios.$get(`/topics/${params.id}`)\n\n return {\n topic: data\n }\n },\n\n -------------------------\n\n async deletePost(id) {\n await this.$axios.$delete(`/topics/${this.topic.id}/posts/${id}`)\n // bad idea - hard reset\n window.location.reload(true)\n //how refresh by asyncData()?\n },\n```\n\n```text\ndata() {\n return {\n topic: [],\n }\n}\n```\n\n```text\nasync deletePost(id) {\n await this.$axios.$delete(`/topics/${this.topic.id}/posts/${id}`)\n this.topic... //change it to reflect what was deleted.\n},\n```\n\n```text\nawait this.$axios.$delete(`/topics/${this.topic.id}/posts/${id}`)\n let {data} = await $axios.$get(`/topics/${this.topic.id}`)\n return this.topic = data\n},\n```\n\n```js\nawait this.$nuxt.refresh()\n```\n\n```text\n$nuxt\n```\n\n```text\n// register page component\n\n async fetch({ store }) {\n\n await store.dispatch('places/countries/getCountriesAction');\n\n },\n\n\nstore folder \nplaces/countries.js\n\nexport const actions = {\n\n async getCountriesAction({ state,commit }) {\n\n return this.$axios('countries').then((e)=>{\n\n commit('InitializeData',e.data.data)\n\n });\n\n\n }\n}\n```\n\n========================================\n\nComments:\n- /help/formatting, meta.stackexchange.com/a/131011/997587","metadata":{"transformedAt":"2026-08-18T18:33:07.845Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":125,"estimatedTokens":632}}170{"id":"stack-50700680","source":"stackoverflow","questionId":50700680,"title":"nuxt start requires node_modules to be present in order to run","tags":["node.js","docker","webpack","node-modules","nuxt.js"],"text":"Title: nuxt start requires node_modules to be present in order to run\nTags: node.js, docker, webpack, node-modules, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a `nuxt-community/starter-template` project with minimal additions. My `package.json` looks like this\n\n```\n{\n // ...\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"docker-image\": \"nuxt build && docker build -t unijobs-www-temp .\",\n \"start\": \"nuxt start\",\n \"generate\": \"NODE_ENV=production nuxt generate\",\n \"lint\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"precommit\": \"npm run lint\"\n },\n \"dependencies\": {\n \"@fortawesome/fontawesome\": \"^1.1.8\",\n \"@fortawesome/fontawesome-free-brands\": \"^5.0.13\",\n \"@fortawesome/fontawesome-free-regular\": \"^5.0.13\",\n \"@fortawesome/fontawesome-free-solid\": \"^5.0.13\",\n \"@fortawesome/vue-fontawesome\": \"0.0.22\",\n \"nuxt\": \"^1.0.0\",\n \"nuxt-fontawesome\": \"^0.2.0\",\n \"node-sass\": \"^4.9.0\",\n \"sass-loader\": \"^7.0.2\"\n },\n \"devDependencies\": {\n \"babel-eslint\": \"^8.2.1\",\n \"eslint\": \"^4.15.0\",\n \"eslint-friendly-formatter\": \"^3.0.0\",\n \"eslint-loader\": \"^1.7.1\",\n \"eslint-plugin-vue\": \"^4.0.0\"\n }\n}\n```\n\nLocal development looks fine, local `build` and `start` seem to work fine. However, it all goes south when I build the Docker image.\n**PLEASE NOTE** this is not an issue with Docker, the same is true if I run equivalent steps on my own machine, in a new directory.\n\n```\nFROM node:stretch\n\nENV NODE_ENV=production\nENV HOST=0.0.0.0\nEXPOSE 3000\n\nRUN npm -g i nuxt\nRUN mkdir -p /app\nADD .nuxt /app/.nuxt\nADD static /app/static\nWORKDIR /app\n\nCMD [\"nuxt\", \"start\"]\n```\n\nThis is what I find in the logs:\n\n```\n2018-06-05T12:27:19.910Z nuxt:render Rendering url /\n{ Error: Cannot find module 'core-js/library/fn/promise' from '/app'\n at Function.module.exports [as sync] (/usr/local/lib/node_modules/nuxt/node_modules/resolve/lib/sync.js:42:15)\n at r (/usr/local/lib/node_modules/nuxt/node_modules/vue-server-renderer/build.js:8332:44)\n at Object. (server-bundle.js:1429:18)\n at __webpack_require__ (server-bundle.js:27:30)\n at Object.module.exports.module.exports (server-bundle.js:105:31)\n at __webpack_require__ (server-bundle.js:27:30)\n at Object. (server-bundle.js:1218:138)\n at __webpack_require__ (server-bundle.js:27:30)\n at server-bundle.js:92:18\n at Object. (server-bundle.js:95:10)\n at evaluateModule (/usr/local/lib/node_modules/nuxt/node_modules/vue-server-renderer/build.js:8338:21)\n at /usr/local/lib/node_modules/nuxt/node_modules/vue-server-renderer/build.js:8396:18\n at new Promise ()\n at /usr/local/lib/node_modules/nuxt/node_modules/vue-server-renderer/build.js:8388:14\n at Object.renderToString (/usr/local/lib/node_modules/nuxt/node_modules/vue-server-renderer/build.js:8564:9)\n at Renderer.renderRoute (/usr/local/lib/node_modules/nuxt/lib/core/renderer.js:344:41)\n code: 'MODULE_NOT_FOUND',\n statusCode: 500,\n name: 'NuxtServerError' }\n```\n\nHowever, it all goes away as soon as I plug `node_modules` in, next to the `.nuxt` and `static` directories. It seems some of the modules are not bundled. My `nuxt.config.js` file is like\n\n```\nmodule.exports = {\n head: {\n // Skipping noise...\n },\n modules: [\n [ 'nuxt-fontawesome', {\n component: 'fa',\n imports: [\n { set: '@fortawesome/fontawesome-free-brands' },\n ]\n }],\n ],\n loading: { color: '#3B8070' },\n build: {\n extend (config, { isDev, isClient }) {\n if (isDev && isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n\n// *** NOTE: In practice, I'm only using FA brands here, not the others ***\n\n config.resolve.alias['@fortawesome/fontawesome-free-brands$'] = '@fortawesome/fontawesome-free-brands/shakable.es.js' \n }\n }\n }\n}\n```\n\nAm I doing something wrong?\n\n========================================\n\nCode:\n```text\n{\n // ...\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"docker-image\": \"nuxt build && docker build -t unijobs-www-temp .\",\n \"start\": \"nuxt start\",\n \"generate\": \"NODE_ENV=production nuxt generate\",\n \"lint\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"precommit\": \"npm run lint\"\n },\n \"dependencies\": {\n \"@fortawesome/fontawesome\": \"^1.1.8\",\n \"@fortawesome/fontawesome-free-brands\": \"^5.0.13\",\n \"@fortawesome/fontawesome-free-regular\": \"^5.0.13\",\n \"@fortawesome/fontawesome-free-solid\": \"^5.0.13\",\n \"@fortawesome/vue-fontawesome\": \"0.0.22\",\n \"nuxt\": \"^1.0.0\",\n \"nuxt-fontawesome\": \"^0.2.0\",\n \"node-sass\": \"^4.9.0\",\n \"sass-loader\": \"^7.0.2\"\n },\n \"devDependencies\": {\n \"babel-eslint\": \"^8.2.1\",\n \"eslint\": \"^4.15.0\",\n \"eslint-friendly-formatter\": \"^3.0.0\",\n \"eslint-loader\": \"^1.7.1\",\n \"eslint-plugin-vue\": \"^4.0.0\"\n }\n}\n```\n\n```text\nFROM node:stretch\n\nENV NODE_ENV=production\nENV HOST=0.0.0.0\nEXPOSE 3000\n\nRUN npm -g i nuxt\nRUN mkdir -p /app\nADD .nuxt /app/.nuxt\nADD static /app/static\nWORKDIR /app\n\nCMD [\"nuxt\", \"start\"]\n```\n\n```text\n2018-06-05T12:27:19.910Z nuxt:render Rendering url /\n{ Error: Cannot find module 'core-js/library/fn/promise' from '/app'\n at Function.module.exports [as sync] (/usr/local/lib/node_modules/nuxt/node_modules/resolve/lib/sync.js:42:15)\n at r (/usr/local/lib/node_modules/nuxt/node_modules/vue-server-renderer/build.js:8332:44)\n at Object.<anonymous> (server-bundle.js:1429:18)\n at __webpack_require__ (server-bundle.js:27:30)\n at Object.module.exports.module.exports (server-bundle.js:105:31)\n at __webpack_require__ (server-bundle.js:27:30)\n at Object.<anonymous> (server-bundle.js:1218:138)\n at __webpack_require__ (server-bundle.js:27:30)\n at server-bundle.js:92:18\n at Object.<anonymous> (server-bundle.js:95:10)\n at evaluateModule (/usr/local/lib/node_modules/nuxt/node_modules/vue-server-renderer/build.js:8338:21)\n at /usr/local/lib/node_modules/nuxt/node_modules/vue-server-renderer/build.js:8396:18\n at new Promise (<anonymous>)\n at /usr/local/lib/node_modules/nuxt/node_modules/vue-server-renderer/build.js:8388:14\n at Object.renderToString (/usr/local/lib/node_modules/nuxt/node_modules/vue-server-renderer/build.js:8564:9)\n at Renderer.renderRoute (/usr/local/lib/node_modules/nuxt/lib/core/renderer.js:344:41)\n code: 'MODULE_NOT_FOUND',\n statusCode: 500,\n name: 'NuxtServerError' }\n```\n\n```text\nmodule.exports = {\n head: {\n // Skipping noise...\n },\n modules: [\n [ 'nuxt-fontawesome', {\n component: 'fa',\n imports: [\n { set: '@fortawesome/fontawesome-free-brands' },\n ]\n }],\n ],\n loading: { color: '#3B8070' },\n build: {\n extend (config, { isDev, isClient }) {\n if (isDev && isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n\n// *** NOTE: In practice, I'm only using FA brands here, not the others ***\n\n config.resolve.alias['@fortawesome/fontawesome-free-brands$'] = '@fortawesome/fontawesome-free-brands/shakable.es.js' \n }\n }\n }\n}\n```\n\n```text\nnuxt-community/starter-template\n```\n\n```text\npackage.json\n```\n\n```text\nbuild\n```\n\n```text\nstart\n```\n\n```text\nnode_modules\n```\n\n```text\n.nuxt\n```\n\n```text\nstatic\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n.nuxt\n```\n\n```text\nnuxt build --standalone\n```\n\n========================================\n\nComments:\n- isnt that supposed to work as an \"express\" server?\n- Can you check the node version (`node -v`) from your docker image `node:stretch`. Nuxt needs node >= 8.4\n- That was fine, it has >= 8.4. The actual problem was me not understanding how deployment with npm works. The Dockerfile I pasted above is somewhat wrong: instead of installing nuxt global I should have done a `npm install` to install the runtime modules, and copied the `.nuxt` directory after building it from outside the container. In short: I was building inside the container and I didn't need to.\n- That is an interesting option…\n- could this be the accepted answer? Hopefully this feature will be documented soon github.com/nuxt/nuxtjs.org/issues/499","metadata":{"transformedAt":"2026-08-18T18:33:07.845Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":279,"estimatedTokens":2006}}171{"id":"stack-60382088","source":"stackoverflow","questionId":60382088,"title":"Jest does not collect coverage from vue files (nuxt)","tags":["javascript","vue.js","jestjs","nuxt.js"],"text":"Title: Jest does not collect coverage from vue files (nuxt)\nTags: javascript, vue.js, jestjs, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhen I run `jest --coverage` jest only collects coverage from JavaScript files, but not my vue files. The folder structure is correct. `jest.config.js` is in the root folder, just like `/components` and `/lib`. For me, there is no logical explanation why coverage is collected from JavaScript files but not from vue files.\n\nhttps://i.sstatic.net/Ab3D7.png\n\nHere is my `jest.config.js`\n\n```\nmodule.exports = {\n verbose: true,\n setupFilesAfterEnv: ['/test-framework-scripts.js'],\n moduleFileExtensions: [\n 'js',\n 'jsx',\n 'json',\n 'vue',\n 'node',\n ],\n moduleNameMapper: {\n '^@/(.*)$': '/$1',\n },\n moduleDirectories: [\n 'node_modules',\n 'bower_components',\n 'shared',\n 'test/tmp',\n ],\n transform: {\n '^.+\\\\.vue$': 'vue-jest',\n '.+\\\\.(css|styl|less|sass|scss|png|jpe?g|ttf|woff|woff2)$': 'jest-transform-stub',\n '^.+\\\\.js$': 'babel-jest',\n '^.+\\\\.svg$': '/jest-svg-transform.js',\n '\\\\.(gql|graphql)$': 'jest-transform-graphql',\n },\n transformIgnorePatterns: [\n '/node_modules/(!gsap)',\n ],\n snapshotSerializers: [\n 'jest-serializer-vue',\n ],\n testMatch: [\n '/test/**/*.spec.(js|jsx|ts|tsx)',\n ],\n testPathIgnorePatterns: [\n '/test/client/shared-examples/',\n ],\n testURL: 'http://localhost/',\n watchPlugins: [\n 'jest-watch-typeahead/filename',\n 'jest-watch-typeahead/testname',\n ],\n collectCoverageFrom: [\n 'components/**/*.{js,vue}',\n 'layouts/**/*.{js,vue}',\n 'lib/**/*.{js,vue}',\n 'middleware/**/*.{js,vue}',\n 'mixins/**/*.{js,vue}',\n 'pages/**/*.{js,vue}',\n 'store/**/*.{js,vue}',\n '!/node_modules/**',\n '!/test/**',\n ],\n coverageReporters: ['text', 'html'],\n};\n```\n\npackage.json\n\n```\n{\n \"name\": \"stockpicker\",\n \"version\": \"1.0.0\",\n \"description\": \"a stockpicker\",\n \"author\": \"Nico Meyer\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"precommit\": \"npm run lint\",\n \"test\": \"jest\",\n \"test.watch\": \"jest --watch\"\n },\n \"dependencies\": {\n \"@fortawesome/fontawesome-svg-core\": \"^1.2.26\",\n \"@fortawesome/free-solid-svg-icons\": \"^5.12.0\",\n \"@fortawesome/vue-fontawesome\": \"^0.1.9\",\n \"@nuxtjs/axios\": \"^5.3.6\",\n \"axios\": \"^0.19.2\",\n \"bootstrap-vue\": \"^2.3.0\",\n \"chai\": \"^4.2.0\",\n \"core-js\": \"^2.6.11\",\n \"cross-env\": \"^5.2.0\",\n \"firebase\": \"^7.8.0\",\n \"js-cookie\": \"^2.2.1\",\n \"moment\": \"^2.24.0\",\n \"nuxt\": \"^2.11.0\",\n \"vue\": \"^2.6.11\",\n \"vue-async-computed\": \"^3.6.1\",\n \"vue-clickaway2\": \"^2.3.1\",\n \"vue2-touch-events\": \"^2.1.0\",\n \"vuex\": \"^3.1.2\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.8.4\",\n \"@babel/preset-env\": \"^7.8.4\",\n \"@nuxtjs/eslint-config\": \"^0.0.1\",\n \"@vue/test-utils\": \"^1.0.0-beta.31\",\n \"babel-core\": \"^7.0.0-bridge.0\",\n \"babel-eslint\": \"^10.0.1\",\n \"babel-jest\": \"^25.1.0\",\n \"eslint\": \"^5.3.0\",\n \"eslint-config-airbnb-base\": \"^13.1.0\",\n \"eslint-config-standard\": \">=12.0.0\",\n \"eslint-import-resolver-webpack\": \"^0.11.1\",\n \"eslint-loader\": \"^2.1.2\",\n \"eslint-plugin-import\": \"^2.17.2\",\n \"eslint-plugin-jest\": \">=22.3.0\",\n \"eslint-plugin-node\": \">=8.0.1\",\n \"eslint-plugin-nuxt\": \">=0.4.2\",\n \"eslint-plugin-promise\": \">=4.0.1\",\n \"eslint-plugin-standard\": \">=4.0.0\",\n \"eslint-plugin-vue\": \"^5.2.2\",\n \"jest\": \"^25.1.0\",\n \"jest-expect-message\": \"^1.0.2\",\n \"jest-extended\": \"^0.11.5\",\n \"jest-serializer-vue\": \"^2.0.2\",\n \"jest-transform-graphql\": \"^2.1.0\",\n \"jest-transform-stub\": \"^2.0.0\",\n \"jest-watch-typeahead\": \"^0.4.2\",\n \"jsdom\": \"^15.1.0\",\n \"jsdom-global\": \"^3.0.2\",\n \"node-sass\": \"^4.13.1\",\n \"nodemon\": \"^1.18.9\",\n \"resolve-url-loader\": \"^3.1.0\",\n \"sass-loader\": \"^7.1.0\",\n \"vue-jest\": \"^3.0.5\",\n \"webpack\": \"^4.32.0\"\n }\n}\n```\n\nCan you tell me what's wrong here?\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n verbose: true,\n setupFilesAfterEnv: ['<rootDir>/test-framework-scripts.js'],\n moduleFileExtensions: [\n 'js',\n 'jsx',\n 'json',\n 'vue',\n 'node',\n ],\n moduleNameMapper: {\n '^@/(.*)$': '<rootDir>/$1',\n },\n moduleDirectories: [\n 'node_modules',\n 'bower_components',\n 'shared',\n 'test/tmp',\n ],\n transform: {\n '^.+\\\\.vue$': 'vue-jest',\n '.+\\\\.(css|styl|less|sass|scss|png|jpe?g|ttf|woff|woff2)$': 'jest-transform-stub',\n '^.+\\\\.js$': 'babel-jest',\n '^.+\\\\.svg$': '<rootDir>/jest-svg-transform.js',\n '\\\\.(gql|graphql)$': 'jest-transform-graphql',\n },\n transformIgnorePatterns: [\n '<rootDir>/node_modules/(!gsap)',\n ],\n snapshotSerializers: [\n 'jest-serializer-vue',\n ],\n testMatch: [\n '<rootDir>/test/**/*.spec.(js|jsx|ts|tsx)',\n ],\n testPathIgnorePatterns: [\n '<rootDir>/test/client/shared-examples/',\n ],\n testURL: 'http://localhost/',\n watchPlugins: [\n 'jest-watch-typeahead/filename',\n 'jest-watch-typeahead/testname',\n ],\n collectCoverageFrom: [\n 'components/**/*.{js,vue}',\n 'layouts/**/*.{js,vue}',\n 'lib/**/*.{js,vue}',\n 'middleware/**/*.{js,vue}',\n 'mixins/**/*.{js,vue}',\n 'pages/**/*.{js,vue}',\n 'store/**/*.{js,vue}',\n '!<rootDir>/node_modules/**',\n '!<rootDir>/test/**',\n ],\n coverageReporters: ['text', 'html'],\n};\n```\n\n```text\n{\n \"name\": \"stockpicker\",\n \"version\": \"1.0.0\",\n \"description\": \"a stockpicker\",\n \"author\": \"Nico Meyer\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"precommit\": \"npm run lint\",\n \"test\": \"jest\",\n \"test.watch\": \"jest --watch\"\n },\n \"dependencies\": {\n \"@fortawesome/fontawesome-svg-core\": \"^1.2.26\",\n \"@fortawesome/free-solid-svg-icons\": \"^5.12.0\",\n \"@fortawesome/vue-fontawesome\": \"^0.1.9\",\n \"@nuxtjs/axios\": \"^5.3.6\",\n \"axios\": \"^0.19.2\",\n \"bootstrap-vue\": \"^2.3.0\",\n \"chai\": \"^4.2.0\",\n \"core-js\": \"^2.6.11\",\n \"cross-env\": \"^5.2.0\",\n \"firebase\": \"^7.8.0\",\n \"js-cookie\": \"^2.2.1\",\n \"moment\": \"^2.24.0\",\n \"nuxt\": \"^2.11.0\",\n \"vue\": \"^2.6.11\",\n \"vue-async-computed\": \"^3.6.1\",\n \"vue-clickaway2\": \"^2.3.1\",\n \"vue2-touch-events\": \"^2.1.0\",\n \"vuex\": \"^3.1.2\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.8.4\",\n \"@babel/preset-env\": \"^7.8.4\",\n \"@nuxtjs/eslint-config\": \"^0.0.1\",\n \"@vue/test-utils\": \"^1.0.0-beta.31\",\n \"babel-core\": \"^7.0.0-bridge.0\",\n \"babel-eslint\": \"^10.0.1\",\n \"babel-jest\": \"^25.1.0\",\n \"eslint\": \"^5.3.0\",\n \"eslint-config-airbnb-base\": \"^13.1.0\",\n \"eslint-config-standard\": \">=12.0.0\",\n \"eslint-import-resolver-webpack\": \"^0.11.1\",\n \"eslint-loader\": \"^2.1.2\",\n \"eslint-plugin-import\": \"^2.17.2\",\n \"eslint-plugin-jest\": \">=22.3.0\",\n \"eslint-plugin-node\": \">=8.0.1\",\n \"eslint-plugin-nuxt\": \">=0.4.2\",\n \"eslint-plugin-promise\": \">=4.0.1\",\n \"eslint-plugin-standard\": \">=4.0.0\",\n \"eslint-plugin-vue\": \"^5.2.2\",\n \"jest\": \"^25.1.0\",\n \"jest-expect-message\": \"^1.0.2\",\n \"jest-extended\": \"^0.11.5\",\n \"jest-serializer-vue\": \"^2.0.2\",\n \"jest-transform-graphql\": \"^2.1.0\",\n \"jest-transform-stub\": \"^2.0.0\",\n \"jest-watch-typeahead\": \"^0.4.2\",\n \"jsdom\": \"^15.1.0\",\n \"jsdom-global\": \"^3.0.2\",\n \"node-sass\": \"^4.13.1\",\n \"nodemon\": \"^1.18.9\",\n \"resolve-url-loader\": \"^3.1.0\",\n \"sass-loader\": \"^7.1.0\",\n \"vue-jest\": \"^3.0.5\",\n \"webpack\": \"^4.32.0\"\n }\n}\n```\n\n```text\njest --coverage\n```\n\n```text\njest.config.js\n```\n\n```text\n/components\n```\n\n```text\n/lib\n```\n\n```text\njest.config.js\n```\n\n========================================\n\nComments:\n- Is it jest 25 version ?\n- @Ic3m4n Facing the same issue since yesterday, were you able to figure it out?\n- @Aldarund yeah it is. 25.1.0\n- this is outdated","metadata":{"transformedAt":"2026-08-18T18:33:07.845Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":315,"estimatedTokens":1925}}172{"id":"stack-69158842","source":"stackoverflow","questionId":69158842,"title":"Why is my console.log() not logging anything in my browser?","tags":["vue.js","debugging","vuejs2","console","nuxt.js"],"text":"Title: Why is my console.log() not logging anything in my browser?\nTags: vue.js, debugging, vuejs2, console, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a SSR page build on Nuxt (Vue). There is a simple code which runs in the browser.\n\n```\nmethods: {\n submitGeneralForm() {\n alert(\"submit\");\n console.log('teeeeeeeeeeeeeeeeeeeeest')\n },\n```\n\nSSR means that site it rendered on the server and then send to the browser. This piece of code should run in the browser. It is related to the button click. Alert works fine but I dont see any `console.log()` in the browser. Dont understand it. What is wrong with that?\n\n**EDIT:**\n\nHere is the example Github repository. Run yarn install + yarn dev to reproduce the issue. **Node version v14.17.6 npm version 6.14.15 and yarn version 1.22.11** You will see alert() on page load from /layouts/default.vue which contains this code\n\n```\nexport default {\n\n mounted() {\n alert('11111111111111');\n console.log('22222222222222');\n alert('33333333333333');\n }\n};\n```\n\nThis is screenshot of console.log() in console.\n\nhttps://i.sstatic.net/Vw2oQ.png\n\n========================================\n\nTop Answer:\n**Make sure you don't have anything in the console's filter input field.**\n\nFor example, in the following image you can see the word \"status\" is masking the `console.log()` log lines:\n\nhttps://i.sstatic.net/mY3dX.png\n\n========================================\n\nCode:\n```text\nmethods: {\n submitGeneralForm() {\n alert(\"submit\");\n console.log('teeeeeeeeeeeeeeeeeeeeest')\n },\n```\n\n```text\nexport default {\n\n mounted() {\n alert('11111111111111');\n console.log('22222222222222');\n alert('33333333333333');\n }\n};\n```\n\n```text\nconsole.log()\n```\n\n```text\nconsole.log()\n```\n\n```text\nConsole Output\n```\n\n```text\nConsole.logs\n```\n\n```text\nVerbose\n```\n\n```text\nconsole.log()\n```\n\n========================================\n\nComments:\n- Comments are not for extended discussion; this conversation has been moved to chat.\n- @Čamo if you can't the code properly nor give us access to the repo, I guess that you're stuck with your issue here.\n- I can not give you access to company repository. What should I ? ESLint config? Nuxt config? Which one?\n- I add eslintrc.json and nuxt.config.json to the question.\n- Can you reproduce the issue on in a Stackblitz (stackblitz.com)?\n- Yep, make a minimal reproducible example or something. If you come to somebody and say `hi I can't console.log` while he totally can, he will not be able to help you. So, maybe giving some context or a whole minimal reproducible example is a starting point yeah.\n- I made the github repository. The link is in the question.\n- would also double check the browser plugins aren't messing with the output. Preferably disable them all.\n- Pretty much what was told into the chat: stackoverflow.com/questions/69158842/… On top of it, the author already found the solution as you can see.\n- Yup just saw it after posting my answer.","metadata":{"transformedAt":"2026-08-18T18:33:07.845Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":104,"estimatedTokens":745}}173{"id":"stack-47442621","source":"stackoverflow","questionId":47442621,"title":"Managing State for Overlay Dismissed Components in Vuetify","tags":["vuex","nuxt.js","vuetify.js"],"text":"Title: Managing State for Overlay Dismissed Components in Vuetify\nTags: vuex, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nI'm building out a `vuetify/nuxt` frontend for the first time, and I've moved my `v-navigation-drawer` component out of the `default.vue` layout, and into it's own component, so that it can be reused in multiple layouts.\n\nThe activator for this drawer still remains in the `default.vue` component, so I added a `sidebar` state to vuex:\n\n```\nexport const state = () => ({\n baseurl: 'http://example.com/api/',\n sidebar: false,\n authenticated: false,\n token: null,\n user: null,\n})\n```\n\nThe mutator for the sidebar looks like so:\n\n```\nexport const mutations = {\n toggleSidebar(state) {\n state.sidebar = !state.sidebar;\n }\n}\n```\n\nThis works perfectly when opening the drawer, but because the drawer is dismissed via clicking the overlay, or clicking off of sidebar (if you've turned the overlay off) vuex throws a huge error:\n\nhttps://i.sstatic.net/AM4RY.png\n\nHow can I make this work correctly through vuex?\n\n========================================\n\nTop Answer:\nAnother solution is to use vuex-map-fields package which enables two-way data binding for states saved in a Vuex store.\n\nIt makes the code clear, readable more than the normal way (as in the accepted answer).\n\n### Basic example:\n\n**in your store file**\n\n```\n// Import the `getField` getter and the `updateField`\n// mutation function from the `vuex-map-fields` module.\nimport { getField, updateField } from 'vuex-map-fields';\n\nexport const state = () => ({\n baseurl: 'http://example.com/api/',\n sidebar: false,\n authenticated: false,\n token: null,\n user: null,\n})\n\nexport const getters = {\n // Add the `getField` getter to the\n // `getters` of your Vuex store instance.\n getField,\n}\n\nexport const mutations = {\n // Add the `updateField` mutation to the\n // `mutations` of your Vuex store instance.\n updateField,\n}\n```\n\n**in your component**\n\n```\ntemplate>\n \n\nimport { mapFields } from 'vuex-map-fields';\n\nexport default {\n computed: {\n // The `mapFields` function takes an array of\n // field names and generates corresponding\n // computed properties with getter and setter\n // functions for accessing the Vuex store.\n ...mapFields([\n 'baseurl',\n 'sidebar',\n // etc...\n ]),\n }\n }\n\n```\n\nfor more details, you can check its githab page\n\n========================================\n\nCode:\n```text\nexport const state = () => ({\n baseurl: 'http://example.com/api/',\n sidebar: false,\n authenticated: false,\n token: null,\n user: null,\n})\n```\n\n```text\nexport const mutations = {\n toggleSidebar(state) {\n state.sidebar = !state.sidebar;\n }\n}\n```\n\n```text\nvuetify/nuxt\n```\n\n```text\nv-navigation-drawer\n```\n\n```text\ndefault.vue\n```\n\n```text\ndefault.vue\n```\n\n```text\nsidebar\n```\n\n```html\n<template>\n <v-navigation-drawer v-model=\"drawer\" ...>\n</template>\n\n<script>\n export default {\n computed: {\n drawer: {\n get () {\n return this.$store.state.sidebar\n },\n set (val) {\n this.$store.commit('sidebar', val)\n }\n }\n }\n }\n</script>\n```\n\n```js\n// vuex mutation\nsidebar (state, val) {\n state.sidebar = val\n}\n```\n\n```html\n<template>\n <v-navigation-drawer :value=\"$store.state.sidebar\" @input=\"$store.commit('sidebar', $event)\" ...>\n</template>\n```\n\n```text\n$store.state.sidebar\n```\n\n```js\n// Import the `getField` getter and the `updateField`\n// mutation function from the `vuex-map-fields` module.\nimport { getField, updateField } from 'vuex-map-fields';\n\nexport const state = () => ({\n baseurl: 'http://example.com/api/',\n sidebar: false,\n authenticated: false,\n token: null,\n user: null,\n})\n\nexport const getters = {\n // Add the `getField` getter to the\n // `getters` of your Vuex store instance.\n getField,\n}\n\nexport const mutations = {\n // Add the `updateField` mutation to the\n // `mutations` of your Vuex store instance.\n updateField,\n}\n```\n\n```js\ntemplate>\n <v-navigation-drawer v-model=\"sidebar\" ...>\n</template>\n\n<script>\nimport { mapFields } from 'vuex-map-fields';\n\nexport default {\n computed: {\n // The `mapFields` function takes an array of\n // field names and generates corresponding\n // computed properties with getter and setter\n // functions for accessing the Vuex store.\n ...mapFields([\n 'baseurl',\n 'sidebar',\n // etc...\n ]),\n }\n }\n</script>\n```\n\n========================================\n\nComments:\n- You are a flippin genius my friend! To my credit I was VERY close to this ... I just wasn't passing the value into the mutation. But finally after trying everything under the sun .... bingo! Thanks a ton.\n- You are genius. This is what i have looking for. Thanks!\n- Excellent! The missing guide to Vuetify v-navigation-drawer ! There are open issues on Vuetify about this.... And the answer - for most cases - is yours!\n- This is the answer to so many unanswered posts. Can anyone explain where `val` comes from and how it is set? Is it just a default that is generated with v-model?","metadata":{"transformedAt":"2026-08-18T18:33:07.845Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":234,"estimatedTokens":1258}}174{"id":"stack-65042171","source":"stackoverflow","questionId":65042171,"title":"Nuxt link to external url adding slash before URL","tags":["nuxt.js"],"text":"Title: Nuxt link to external url adding slash before URL\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a `nuxt-link` and if I inspect element with the Vue inspector I get something like this:\n\nhttps://i.sstatic.net/Cgn18.png\n\nNote the `to` attribute. But if I inspect element, sure enough the `href` attribute is different:\n\n```\n\n \n Trending →\n \n\n```\n\nA `\\` has been appended. This is not present in the JSON feed that is populating the site.\n\nIs this a common \"gotcha\" with nuxt, or do I need to do something differently? Or do I need to raise an issue?\n\n========================================\n\nTop Answer:\nUpdate in Nuxt 3, NuxtLink now supports all kinds of links, be it external or internal Reference\n\nNuxt provides component to handle any kind of links within your application.\n\nSo your component should work fine now if you update to Nuxt 3.\n\n========================================\n\nCode:\n```text\n<p class=\"more-link-block\">\n <a href=\"/https://www.forbes.com/sites/solitairetownsend/2020/11/16/100-uk-leading-environmentalists-who-happen-to-be-women/?sh=2b11cc462451\" target=\"_blank\" class=\"anchor-tag small-caps\">\n Trending →\n </a>\n</p>\n```\n\n```text\nnuxt-link\n```\n\n```text\nto\n```\n\n```text\nhref\n```\n\n```text\n\\\n```\n\n```text\n<a href=\"https://www.forbes.com/sites/solitairetownsend/2020/11/16/100-uk-leading-environmentalists-who-happen-to-be-women/?sh=2b11cc462451\" target=\"_blank\">External Link to Forbes</a>\n```\n\n```text\n<a>\n```\n\n```text\n<NuxtLink>\n```\n\n```text\n<NuxtLink>\n```\n\n```text\n<NuxtLink>\n```\n\n```text\n<a>\n```\n\n```text\n<a>\n```\n\n========================================\n\nComments:\n- How are you generating the nuxt link?\n- did you fix it?\n- Taking the above example; I'm dynamically setting the link uri text and doing click me and that's having the same issue in that its also generating the leading '/' as above. Any ideas?","metadata":{"transformedAt":"2026-08-18T18:33:07.845Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":93,"estimatedTokens":465}}175{"id":"stack-63973637","source":"stackoverflow","questionId":63973637,"title":"Why does `nuxt generate` with @nuxt/pwa module generates always default icon in Gitlab-CI?","tags":["gitlab","icons","nuxt.js","gitlab-ci","progressive-web-apps"],"text":"Title: Why does `nuxt generate` with @nuxt/pwa module generates always default icon in Gitlab-CI?\nTags: gitlab, icons, nuxt.js, gitlab-ci, progressive-web-apps\nSource: Stack Overflow\n\nQuestion:\nI have the following problem. I am using nuxt with the pwa module to generate a pre-rendered webpage. The @nuxt/pwa icon module should generate the different sized icons for the manifest.\n\nThis is also working when I run `nuxt generate` on my laptop.\n\nIn my gitlab-ci pipeline the generation also is working but it is always generating the default nuxt icon\n\nhttps://i.sstatic.net/KGl5c.png\n\nThis icon I can not in my workspace so I guess it is somehow referenced in the docker build from node_modules.\n\nI am using the following gitlab-ci job\n\n```\nbuild:\n image: node:alpine\n stage: build\n script:\n - npm run generate\n artifacts:\n paths:\n - dist/*\n expire_in: 14 days\n only:\n - master\n```\n\nThe `package.json` looks like this:\n\n```\n\"scripts\": {\n \"generate\": \"nuxt generate\",\n ...\n },\n \"dependencies\": {\n \"@nuxtjs/pwa\": \"^3.0.0-beta.20\",\n \"nuxt\": \"^2.14.0\",\n ...\n },\n \"devDependencies\": {\n ...\n }\n```\n\nI also tried a lot of different settings in my nuxt.conf.js as I guessed that the icon is not referenced correctly.\n\nThis was my last try\n\n```\npwa: {\n icon: {\n source: resolve(__dirname, './client/static/icon.png'),\n },\n },\n```\n\nBut as it is found locally I thik that it is right.\n\nHas anyone an idea why the `nuxt generate` does not work in gitlab-ci?\n\n========================================\n\nTop Answer:\nI had the same issue and the icons didn't get updated also on my local environment. For now I was able to fix it by adding\n\n```\npwa: {\n icon: {\n fileName: 'app-icon.png',\n },\n},\n```\n\nto my nuxt.config.js and change the filename accordingly. But thats probably a little hacky.\n\nI use Netlify for deployment and cleared the cache there but with no luck. Did you cleared your Runner Cache in Gitlab and then tried again?\n\n========================================\n\nCode:\n```text\nbuild:\n image: node:alpine\n stage: build\n script:\n - npm run generate\n artifacts:\n paths:\n - dist/*\n expire_in: 14 days\n only:\n - master\n```\n\n```text\n\"scripts\": {\n \"generate\": \"nuxt generate\",\n ...\n },\n \"dependencies\": {\n \"@nuxtjs/pwa\": \"^3.0.0-beta.20\",\n \"nuxt\": \"^2.14.0\",\n ...\n },\n \"devDependencies\": {\n ...\n }\n```\n\n```text\npwa: {\n icon: {\n source: resolve(__dirname, './client/static/icon.png'),\n },\n },\n```\n\n```text\nnuxt generate\n```\n\n```text\npackage.json\n```\n\n```text\nnuxt generate\n```\n\n```text\ngenerate: 'rm -r /node_modules/.cache/pwa/icon && nuxt generate';\n```\n\n```text\n/node_modules/.cache/pwa/icon\n```\n\n```text\n/node_modules/.cache/pwa/icon\n```\n\n```text\npwa: {\n icon: {\n fileName: 'app-icon.png',\n },\n},\n```\n\n```text\nnpm install\nnpm run generate\n```\n\n========================================\n\nComments:\n- I am not sure and I have to narrow down if it was the clearing of the cache or the change of the config with explicit referencing the icon but now it works. Thanks for the hint.\n- I double-checked my pipeline. It was the runners cache. After clearing it, I can also use the non-explicit version of `nuxt.config.js`. Failed with one of the two hard things in computer science (naming things and) cache invalidation :-O\n- For me i have to use `generate: 'rm -r node_modules/.cache/pwa/icon && nuxt generate';` (remove `/` before node_modules).","metadata":{"transformedAt":"2026-08-18T18:33:07.845Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":164,"estimatedTokens":856}}176{"id":"stack-58093806","source":"stackoverflow","questionId":58093806,"title":"VueJS/nuxt 'state' should be a method that returns an object in store/store.js","tags":["javascript","vuejs2","nuxt.js"],"text":"Title: VueJS/nuxt 'state' should be a method that returns an object in store/store.js\nTags: javascript, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm new to VueJS and confused about the warning from nuxt:\n\n 'state' should be a method that returns an object in store/store.js\n\nSo, my store.js contains the following (yes im trying the tutorial from the documentation):\n\n```\nimport Vue from 'vue';\nimport Vuex from 'vuex';\n\nVue.use(Vuex);\nexport const store = new Vuex.Store({\n state() {\n return {\n todos: [\n { id: 1, text: '...', done: true },\n { id: 2, text: '...', done: false }\n ]\n };\n }\n});\n\nexport default store;\n```\n\nIsn't state a method which returns an object? Or did i misunderstood the message?\n\nupdate:\n\nI also tried the following:\n\n```\nstate: () => ({\n todos: [\n { id: 1, text: '...', done: true },\n { id: 2, text: '...', done: false }\n ]\n}),\n```\n\nBut this will give me the same warning.\n\nhttps://i.sstatic.net/qBVZD.png\n\n========================================\n\nTop Answer:\nTry this\n\n**Use export const store** \n\n```\nimport Vuex from 'vuex'\nimport user from './modules/user'\n\nexport const store = new Vuex.Store({\n modules: {\n user\n }\n})\n```\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue';\nimport Vuex from 'vuex';\n\n\nVue.use(Vuex);\nexport const store = new Vuex.Store({\n state() {\n return {\n todos: [\n { id: 1, text: '...', done: true },\n { id: 2, text: '...', done: false }\n ]\n };\n }\n});\n\nexport default store;\n```\n\n```text\nstate: () => ({\n todos: [\n { id: 1, text: '...', done: true },\n { id: 2, text: '...', done: false }\n ]\n}),\n```\n\n```js\nexport const state = () => ({\n counter: 0\n})\n\nexport const mutations = {\n increment (state) {\n state.counter++\n }\n}\n```\n\n```text\nstore/index.js\n```\n\n```text\nstore/store.js\n```\n\n```text\nstore/index.js\n```\n\n```text\nimport Vuex from 'vuex'\nimport user from './modules/user'\n\nexport const store = new Vuex.Store({\n modules: {\n user\n }\n})\n```\n\n```text\nexport const state = () => ({\n cart: {\n booking: null,\n reservations: [],\n },\n});\n```\n\n```js\nconst getDefaultState = () => {\n return {\n aaa: \"\"\n }\n}\n\nexport const state = () => ({\n ...getDefaultState()\n})\n```\n\n========================================\n\nComments:\n- Not sure which tutorial you're following but your store code seems significantly different from what's described in the Nuxt documentation: nuxtjs.org/guide/vuex-store\n- ah, ok, now its working without warnings. thank you for the hint\n- I don't , what do I put in `./store/index.js`?\n- You should put the code above in `./store/index.js`.\n- That's what I'm doing and I still get this error.\n- Thank you for posting this answer. While this code may answer the question, might you please edit your post to add an explanation as to why/how it works? This can help future readers learn and apply your answer. You are also more likely to get positive feedback (upvotes) when you include an explanation.","metadata":{"transformedAt":"2026-08-18T18:33:07.845Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":164,"estimatedTokens":751}}177{"id":"stack-72945444","source":"stackoverflow","questionId":72945444,"title":"Delete a Cookie in Nuxt.js 3","tags":["nuxt.js","nuxt3.js"],"text":"Title: Delete a Cookie in Nuxt.js 3\nTags: nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a function that deletes a cookie when a button is clicked. I'm using the `useCookie` function from Nuxt 3. Since `useCookie` is provided by `h3`, I tried using `deleteCookie` (another function from h3), but that didn't work. I also tried setting the expire date to the past:\n\n```\nuseCookie('userId', {\n expires: new Date().setDate(new Date().getDate() - 1)\n})\n```\n\nbut that didn't work either.\n\n========================================\n\nTop Answer:\n**Updated Feb 2023:**\n\nTo delete a cookie in Nuxt 3, we can simply set it `null` or `undefined`:\n\n```\n\nfunction logout () {\n const authCookie = useCookie('auth')\n authCookie.value = null\n}\n\n```\n\nThis would automatically remove cookie because in this link , Nuxt will set the `maxAge: -1` if the cookie is `null` or `undefined`\n\n========================================\n\nCode:\n```text\nuseCookie('userId', {\n expires: new Date().setDate(new Date().getDate() - 1)\n})\n```\n\n```text\nuseCookie\n```\n\n```text\nuseCookie\n```\n\n```text\nh3\n```\n\n```text\ndeleteCookie\n```\n\n```text\nconst cookie = useCookie(name, options)\n```\n\n```text\ncookie.value = YOUR_VALUE\n```\n\n```text\ncookie.value = null\n```\n\n```js\nconst userIdCookie = useCookie('userId')\nuserIdCookie.value = null\n```\n\n```js\nif (value === null || value === undefined) {\n return serialize(name, value, { ...opts, maxAge: -1 })\n}\n```\n\n```text\nnull\n```\n\n```text\nnull\n```\n\n```text\nundefined\n```\n\n```text\nMax-Age\n```\n\n```text\nnull\n```\n\n```text\nuserIdCookie\n```\n\n```text\nuseCookie\n```\n\n```text\ndocument.cookie = serializeCookie(...)\n```\n\n```text\nappendHeader(event, 'Set-Cookie', serializeCookie(...)\n```\n\n```text\nuseCookie()\n```\n\n```js\ndeleteCookie(event, 'token', {\n httpOnly: true,\n path: '/',\n sameSite: 'strict',\n})\n```\n\n```text\ndeleteCookie\n```\n\n```text\n<script setup>\nfunction logout () {\n const authCookie = useCookie('auth')\n authCookie.value = null\n}\n<script>\n```\n\n```text\nnull\n```\n\n```text\nundefined\n```\n\n```text\nmaxAge: -1\n```\n\n```text\nnull\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- Not sure if this is the exact issue, but according to `cookie-es` (the library used by Nuxt to process cookies) typings (github.com/unjs/cookie-es/blob/main/src/types.ts), `expires` is required to be a `Date` object.\n- Can you be more precise regarding `that didn't work`?\n- I meant that the cookie wasn't deleted\n- This should be the selected answer. Same discussion has been on the official nuxt page: github.com/nuxt/framework/discussions/2576\n- setting it to null or undefined does not remove the cookie\n- This should be: 'userIdCookie.value = null'\n- constant variables are not reassignable\n- what about ssr? how to clear cookies during ssr?","metadata":{"transformedAt":"2026-08-18T18:33:07.846Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":173,"estimatedTokens":698}}178{"id":"stack-51809041","source":"stackoverflow","questionId":51809041,"title":"Error: No build files found, please run `nuxt build` before launching `nuxt start","tags":["vue.js","yarnpkg","nuxt.js"],"text":"Title: Error: No build files found, please run `nuxt build` before launching `nuxt start\nTags: vue.js, yarnpkg, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI created a nuxt boilerplate using \n\n vue-cli nuxt-community/starter-template\n\nI also created another using\n\n create-nuxt-app\n\n. They both create my boilerplate properly. But anytime i try to build start my projects using \n\n yarn start\n\nI get this error:\n\n Error: No build files found, please run `nuxt build` before launching\n `nuxt start\n\nfurthermore, whenever i run \n\n nuxt build\n\nI get this: \n\n No command 'nuxt' found, did you mean: Command 'next' from package\n 'nmh' (universe) nuxt: command not found\n\nbut when i run \n\n yarn build\n\nit builds and running yarn start a second time works but without hot module reloading. I don't know what the problem is. I don't know whether my yarn is broken or nuxt. Please help!\n\n========================================\n\nTop Answer:\n`nuxt build` does not work from your command line, because you have not added it to your `PATH` variable. `npm run build` will look in your dependencies and use that instead.\n\nTo get a dev server running, use `npm run dev`. I believe by default it will start a dev server with live reload on port 3000. To build for production, use `npm run build` and `npm run start`.\n\n========================================\n\nCode:\n```text\nnuxt build\n```\n\n```text\n\"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"precommit\": \"npm run lint\"\n },\n```\n\n```text\nnuxt build\n```\n\n```text\nyarn global add nuxt\n```\n\n```text\nnuxt build\n```\n\n```text\nyarn build\n```\n\n```text\nnuxt\n```\n\n```text\nyarn dev\n```\n\n```text\nnuxt build\n```\n\n```text\nPATH\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run start\n```\n\n========================================\n\nComments:\n- thanks, i noticed that npm run dev, npm run build and npm run start work properly, but how do i fix this issue with yarn so that i can use yarn instead of npm. i want to run yarn start successfully.\n- @TeddyMcZieuwa yarn is a program built upon `npm`. If I remember correctly, you can use both `yarn run dev` or `yarn dev`, `yarn run build` or `yarn build` and `yarn run start` or `yarn start`. It executes scripts as defined in the package.json file.\n- I know, it works well with npm but whenever i use yarn, i get the errors stated above. I am confused.\n- Thanks for the help guys, it was a little problem with my linux. I ran sudo apt upgrade and sudo apt update. This fixed the issue. It had nothing to do with nuxt.\n- Thank your Charles\n- @TeddyMcZieuwa If the answer worked for you, you should mark it as accepted answer","metadata":{"transformedAt":"2026-08-18T18:33:07.846Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":119,"estimatedTokens":695}}179{"id":"stack-60451671","source":"stackoverflow","questionId":60451671,"title":"using different env for different cases in nuxt","tags":["vue.js","environment-variables","nuxt.js"],"text":"Title: using different env for different cases in nuxt\nTags: vue.js, environment-variables, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am new to Nuxt or any sort of node stuff.I m trying to create different environment for different cases, e.g. If I want to test my app, I want the block of dev object to run (pointing to dev endpoint) etc, following is a example\n\n```\n[\n prod: {\n server: www.mysite.com,\n api: 'www.jsonplaceholder.com/'\n },\n dev: {\n server: www.internal-mysite.com,\n api: 'www.jsonplaceholder.com/'\n }\n]\n```\n\nso when I do `npm run dev`, it run the app with those endpoints I know that `.env` won't allowed objects or array so I cannot use that .I have tried `dotenv` but not much help I can get out of it, I tried watching this but I cannot pass NODE_ENV=config.dev (given that config is a file containing the object) How can I make my app to work like that? \n\nA detailed answered would be helpful.\n\n========================================\n\nTop Answer:\nI answered the same question here\n\n[How to set custom path for dotenv in nuxt]\nhttps://stackoverflow.com/a/71346654/10537000\n\n**If you are using version > 2.13 then you won't need to install dotenv anymore because it's already built in**\nhttps://nuxtjs.org/docs/directory-structure/nuxt-config/#runtimeconfig\n\n.env support\nSimilar to vue-cli (*), .env file will be always loaded via dotenv and is accessible via process.env and options._env. process.env is updated so one can use it right inside nuxt.config for runtime config. Values are interpolated and expanded with an improved version of dotenv-expand. .env file is also watched to reload during nuxt dev. Path can be set via cli --dotenv or disabled by --dotenv false.\n\n**I created the .env.xxx files and created the corresponding scripts**\n\nhttps://i.sstatic.net/ekozb.jpg\n\nhttps://i.sstatic.net/DwKDQ.png\n\n========================================\n\nCode:\n```text\n[\n prod: {\n server: www.mysite.com,\n api: 'www.jsonplaceholder.com/'\n },\n dev: {\n server: www.internal-mysite.com,\n api: 'www.jsonplaceholder.com/'\n }\n]\n```\n\n```text\nnpm run dev\n```\n\n```text\n.env\n```\n\n```text\ndotenv\n```\n\n```text\nconst MasterKeys = {\n development: {\n apiEndPoint: 'example.com',\n clientId: '1234567',\n clientSecret: '11111111'\n },\n staging: {\n apiEndPoint: 'staging.example.com',\n clientId: '1234567',\n clientSecret: '11111111'\n },\n production: {\n apiEndPoint: 'prod.example.com',\n clientId: '1234567',\n clientSecret: '11111111'\n }\n};\n\nexport { MasterKeys };\n```\n\n```text\nlet appEnv = process.env.NODE_ENV || 'development';\nimport { MasterKeys } from './config.js';\n```\n\n```text\nenv: {\n apiEndPoint: MasterKeys[appEnv].apiEndPoint,\n clientId: MasterKeys[appEnv].clientId\n }\n```\n\n```text\n\"scripts\": {\n \"dev\": \"nuxt\",\n \"stagingbuild\": \"NODE_ENV=staging nuxt build\",\n \"staging\": \"NODE_ENV=staging nuxt start\",\n \"build\": \"NODE_ENV=production nuxt build\",\n \"start\": \"NODE_ENV=production nuxt start\"\n }\n```\n\n```text\nconfig.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\napiEndPoint\n```\n\n```text\nMasterKeys[appEnv].apiEndPoint\n```\n\n```text\nconfig.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nprocess.env.apiEndPoint\n```\n\n```text\npackage.json\n```\n\n```text\nconst CONFIG = process.env.NODE_ENV === 'development' ? require('dev-config') : require('prod-config');\n\nmodule.exports = {\n axios: {\n baseURL: CONFIG.API_BASE\n }\n}\n```\n\n========================================\n\nComments:\n- But it is not just one url, there r bunch of url which need to change depending upon what env will run and how do I use that SERVER in nuxt config?\n- when u say require `('dev-config')`, does the file name shld be dev-config.env ?\n- what is `[appEnv]`, I see that u created a object but `[appEnv]` is an array syntax?\n- let appEnv = process.env.NODE_ENV || 'development'; in nuxt.config.js declaring environment variable\n- Default means when you run `npm run dev` there in package.json we are not providing any `NODE_ENV` so it will take `development` as per our declaration in `nuxt.config.js` for appEnv\n- `nuxt.config.js` doesn't let u import statement outside a module.\n- Can you elaborate?\n- so when u use `import { MasterKeys } from './config.js';`outside of module.exports it gives error SyntaxError: Cannot use import statement outside a module, I think browser doesn't understand import statements?\n- which version of `Nuxt` you are using?? In my case it was not giving error I'm on `\"nuxt\": \"2.7.1\"`\n- Let us continue this discussion in chat.\n- Can we save secret keys in config.js?\n- npm run build && npm run start is the production command isnt it? where will you put --dotenv .env.production in this script?","metadata":{"transformedAt":"2026-08-18T18:33:07.846Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":173,"estimatedTokens":1168}}180{"id":"stack-55614771","source":"stackoverflow","questionId":55614771,"title":"Nuxt export 'default' (imported as 'mod') was not found","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Nuxt export 'default' (imported as 'mod') was not found\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using Nuxt with Typescript. I create a following component:\n\n```\n\n \n {{ label }}\n \n \n \n \n \n\nimport { Vue, Component, Prop } from \"vue-property-decorator\"\n\n@Component({})\nexport default class AppInput extends Vue {\n @Prop({ type: String, required: false, default: \"input\" })\n inputType!: string\n\n @Prop({ type: String, required: false })\n label!: string\n\n @Prop({ type: String, required: false, default: \"text\" })\n type!: string\n}\n\n```\n\nAnd then in `@/plugins/components.ts`, I import the component as following:\n\n```\nimport Vue from \"vue\"\nimport AppInput from \"@/components/Forms/AppInput.vue\"\n\nVue.component(\"AppInput\", AppInput)\n```\n\nWhen I compile the project with Nuxt, it throws me `export 'default' (imported as 'mod') was not found` error. Please help!\n\n========================================\n\nTop Answer:\nYou will need atleast an empty export default script in your vue files to not see this error. If you don't have any export default statement, it gives this error/warning.\n\n```\nexport default {\n\n}\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div class=\"field\">\n <label class=\"label\" v-if=\"typeof label !== 'undefined'\">{{ label }}</label>\n <div class=\"control\">\n <textarea\n v-if=\"inputType === 'textarea'\"\n class=\"textarea\"\n @input=\"$emit('input', $event.target.value)\"\n ></textarea>\n <input\n v-if=\"inputType === 'input'\"\n :type=\"type\"\n class=\"input\"\n @input=\"$emit('input', $event.target.value)\"\n >\n </div>\n </div>\n</template>\n\n<script lang=\"ts\">\nimport { Vue, Component, Prop } from \"vue-property-decorator\"\n\n@Component({})\nexport default class AppInput extends Vue {\n @Prop({ type: String, required: false, default: \"input\" })\n inputType!: string\n\n @Prop({ type: String, required: false })\n label!: string\n\n @Prop({ type: String, required: false, default: \"text\" })\n type!: string\n}\n</script>\n\n<style>\n</style>\n```\n\n```text\nimport Vue from \"vue\"\nimport AppInput from \"@/components/Forms/AppInput.vue\"\n\nVue.component(\"AppInput\", AppInput)\n```\n\n```text\n@/plugins/components.ts\n```\n\n```text\nexport 'default' (imported as 'mod') was not found\n```\n\n```text\n{\n \"compilerOptions\": {\n \"target\": \"esnext\",\n \"module\": \"esnext\",\n \"moduleResolution\": \"node\",\n \"lib\": [\"esnext\", \"esnext.asynciterable\", \"dom\"],\n \"esModuleInterop\": true,\n \"experimentalDecorators\": true,\n \"allowJs\": true,\n \"sourceMap\": true,\n \"strict\": false,\n \"allowSyntheticDefaultImports\": true,\n \"noImplicitAny\": false,\n \"noEmit\": true,\n \"baseUrl\": \".\",\n \"resolveJsonModule\": true,\n \"paths\": {\n \"~/*\": [\"./*\"]\n },\n \"types\": [\"@nuxt/vue-app\", \"@types/node\", \"@types/webpack-env\"]\n }\n}\n```\n\n```text\nnpm run dev\n```\n\n```text\n<template>\n```\n\n```text\n<div id=\"my-app\">\n```\n\n```text\n<div id=\"app\">\n```\n\n```text\nexport default {\n\n}\n```\n\n========================================\n\nComments:\n- Show full error with stacktrace. And where do u import mod\n- I don't import `mod`\n- `\"export 'default' (imported as 'mod') was not found in '-!../../node_modules/babel-loader/lib/index.js??ref--3-0!..‌​/../node_modules/ts-‌​loader/index.js??ref‌​--3-1!../../node_mod‌​ules/vue-loader/lib/‌​index.js??vue-loader‌​-options!./AppInput.‌​vue?vue&type=script&‌​lang=ts&'`\n- Which one of those entries fixed the problem? (My guess is `\"target\": \"esnext\"`, from this GitHub comment: github.com/nuxt/nuxt.js/issues/5508#issuecomment-491099733)\n- @MasterofDucks Yup that fixed it.","metadata":{"transformedAt":"2026-08-18T18:33:07.846Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":168,"estimatedTokens":993}}181{"id":"stack-53322525","source":"stackoverflow","questionId":53322525,"title":"How to set beforeResolve navigation guard in Nuxt.js","tags":["vue.js","vuex","vue-router","nuxt.js"],"text":"Title: How to set beforeResolve navigation guard in Nuxt.js\nTags: vue.js, vuex, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIs there a way to add beforeResolve navigation guard in nuxt.config.js?\n\nMy nuxt.config.js\n\n```\nmodule.exports {\n ...\n router: {\n beforeResolve(to, from, next) {\n if (this.$store.getters.isLoggedIn)\n next('/resource')\n }\n }\n ...\n}\n```\n\nBut its never gets called!\n\nI've been trying to achieve a redirection before the component is mounted based on the users logged in state on the vuex store.\n\n========================================\n\nCode:\n```text\nmodule.exports {\n ...\n router: {\n beforeResolve(to, from, next) {\n if (this.$store.getters.isLoggedIn)\n next('/resource')\n }\n }\n ...\n}\n```\n\n```text\n// middleware/route-guard.js\nexport default function ({ app }) {\n\n app.router.beforeResolve((to, from, next) => {\n if (app.store.getters.isLoggedIn) {\n next('/resource')\n } else {\n next();\n }\n });\n\n}\n```\n\n```text\n// Nuxt Page Component\nexport default {\n beforeResolve (to, from, next) {\n if (this.$store.getters.isLoggedIn) {\n next('/resource')\n } else {\n next();\n }\n }\n }\n```\n\n========================================\n\nComments:\n- Nuxt introduces middleware exaclty for such purpose.","metadata":{"transformedAt":"2026-08-18T18:33:07.846Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":74,"estimatedTokens":342}}182{"id":"stack-43929099","source":"stackoverflow","questionId":43929099,"title":"How to bind dynamic props to dynamic components in VueJS 2","tags":["javascript","vue.js","vuejs2","vue-component","nuxt.js"],"text":"Title: How to bind dynamic props to dynamic components in VueJS 2\nTags: javascript, vue.js, vuejs2, vue-component, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'd like to know how I can iterate a list of component names (which come from an AJAX call to an API server) and render them as components, and pass relevant properties to each component (i.e. bind their properties dynamically).\n\nSo far I have managed to iterate a JSON list of items that represent components, and successfully render these components. What I'd like to do now is bind the properties for each component using `v-bind`.\n\nIn the example below, the `item-one` component would receive the `image` property with the `item1.jpg` value; and the `item-two` component wouldn't receive any properties.\n\n```\n\n \n \n \n\n import ItemOne from '../components/item-one'\n import ItemTwo from '../components/item-two'\n\n export default {\n components: {\n ItemOne,\n ItemTwo\n },\n asyncData () {\n return {\n items: [\n { 'item-one': { 'image': 'item1.jpg' } },\n { 'item-two': { } }\n ]\n }\n }\n }\n\n```\n\nI tried using `:v-bind=\"Object.values(Object.keys(item)[0])\"` but I get the attribute `v-bind=\"[object Object]\"` in the rendered element.\n\n========================================\n\nCode:\n```text\n<template>\n <div v-for=\"item in items\">\n <component :is=\"Object.keys(item)[0]\" :v-bind=\"???\"></component>\n </div>\n</template>\n\n<script>\n import ItemOne from '../components/item-one'\n import ItemTwo from '../components/item-two'\n\n export default {\n components: {\n ItemOne,\n ItemTwo\n },\n asyncData () {\n return {\n items: [\n { 'item-one': { 'image': 'item1.jpg' } },\n { 'item-two': { } }\n ]\n }\n }\n }\n</script>\n```\n\n```text\nv-bind\n```\n\n```text\nitem-one\n```\n\n```text\nimage\n```\n\n```text\nitem1.jpg\n```\n\n```text\nitem-two\n```\n\n```text\n:v-bind=\"Object.values(Object.keys(item)[0])\"\n```\n\n```text\nv-bind=\"[object Object]\"\n```\n\n```text\nv-bind=\"item[Object.keys(item)[0]]\"\n```\n\n```text\nitems: [{ \n type: 'item-one', \n props: { 'image': 'item1.jpg' },\n}, {\n type: 'item-two',\n}]\n```\n\n```text\n<div v-for=\"item in items\">\n <component :is=\"item.type\" v-bind=\"item.props\"></component>\n</div>\n```\n\n```text\nv-bind\n```\n\n```text\nv-bind\n```\n\n```text\nv-bind\n```\n\n```text\nObject.keys\n```\n\n```text\nitems\n```\n\n========================================\n\nComments:\n- its just `v-bind`. no colon\n- @thanksd that still doesn't work.\n- It would be `v-bind=\"item[Object.keys(item)[0]]\"`. Probably would be helpful to change the structure of `items`.\n- Yes I was confused about how I might structure this, but I really like the simplicity of your refactoring instead. Much easier to reason about, almost self-explanatory.\n- It works! Excellent answer, you've made my day. I like the legibility of your refactoring very much and have applied it. I had to remove the colon from the `v-bind` in your answer above though ;-)","metadata":{"transformedAt":"2026-08-18T18:33:07.846Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":145,"estimatedTokens":726}}183{"id":"stack-73070695","source":"stackoverflow","questionId":73070695,"title":"Test a component with Vitest using useNuxtApp with Nuxt 3","tags":["nuxt.js","nuxt3.js","vitest"],"text":"Title: Test a component with Vitest using useNuxtApp with Nuxt 3\nTags: nuxt.js, nuxt3.js, vitest\nSource: Stack Overflow\n\nQuestion:\nI want to test a component using the `useNuxtApp` composable.\nThis is the component(`MyComponent.vue`):\n\n```\n\n \n {{ $fmt(12) }}\n \n\nconst { $fmt } = useNuxtApp()\n\n```\n\n`$fmt` is a plugin in `plugins` folder.\n\nThe problem is when I try to test `MyComponent.vue` with `vitest`, the test is not started and this error appears:\n\n```\nReferenceError: useNuxtApp is not defined\n```\n\nI don't know how to mock the `useNuxtApp` composable\n\n========================================\n\nTop Answer:\nInstead of mocking, you can use stubbing:\n\n```\nvi.stubGlobal(\"useNuxtApp\", () => ({\n $fmt: vi.fn(),\n}));\n```\n\nIf you need to mock functions of `$fmt` (let's say `doSomething()`), then just extend it like this:\n\n```\nvi.stubGlobal(\"useNuxtApp\", () => ({\n $fmt: { doSomething: vi.fn() },\n}));\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div class=\"flex justify-between\">\n <span>{{ $fmt(12) }}</span>\n </div>\n</template>\n\n<script lang=\"ts\" setup>\nconst { $fmt } = useNuxtApp()\n</script>\n```\n\n```text\nReferenceError: useNuxtApp is not defined\n```\n\n```text\nuseNuxtApp\n```\n\n```text\nMyComponent.vue\n```\n\n```text\n$fmt\n```\n\n```text\nplugins\n```\n\n```text\nMyComponent.vue\n```\n\n```text\nvitest\n```\n\n```text\nuseNuxtApp\n```\n\n```text\n<template>\n <div class=\"flex justify-between\">\n <span>{{ $fmt(12) }}</span>\n </div>\n</template>\n\n<script lang=\"ts\" setup>\nimport { useNuxtApp } from '#app'\nconst { $fmt } = useNuxtApp()\n</script>\n```\n\n```text\nimport path from 'path'\nimport vue from '@vitejs/plugin-vue'\n\nexport default {\n plugins: [vue()],\n test: {\n globals: true,\n environment: 'jsdom',\n setupFiles: './tests/unit/setup/index.ts',\n },\n resolve: {\n alias: {\n '@': path.resolve(__dirname, '.'),\n '#app': path.resolve(\n __dirname,\n './node_modules/nuxt/dist/app/index.d.ts'\n ),\n '#head': path.resolve(\n __dirname,\n './node_modules/nuxt/dist/app/index.d.ts'\n ),\n },\n },\n}\n```\n\n```text\nimport { vi } from 'vitest'\nimport * as nuxt from '#app'\nimport { currency } from '@/plugins/utils/fmt-util'\n\n// @ts-ignore\nvi.spyOn(nuxt, 'useNuxtApp').mockImplementation(() => ({\n $fmt: { currency },\n}))\n```\n\n```text\nuseNuxtApp\n```\n\n```text\n#app\n```\n\n```text\n#head\n```\n\n```text\nvitest.config.js\n```\n\n```text\nuseNuxtApp\n```\n\n```text\nuseNuxtApp\n```\n\n```text\nvi.stubGlobal(\"useNuxtApp\", () => ({\n $fmt: vi.fn(),\n}));\n```\n\n```text\nvi.stubGlobal(\"useNuxtApp\", () => ({\n $fmt: { doSomething: vi.fn() },\n}));\n```\n\n```text\n$fmt\n```\n\n```text\ndoSomething()\n```\n\n========================================\n\nComments:\n- works like a charm!","metadata":{"transformedAt":"2026-08-18T18:33:07.846Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":193,"estimatedTokens":681}}184{"id":"stack-63981989","source":"stackoverflow","questionId":63981989,"title":"How to fix `Invalid component name` when changing page with custom layout in nuxt?","tags":["nuxt.js"],"text":"Title: How to fix `Invalid component name` when changing page with custom layout in nuxt?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\n`[Vue warn]: Invalid component name: \"layouts/default.vue\". Component names should conform to valid custom element name in html5 specification.`\n\nAs you ca see in above error I'm facing a problem when i used custom layout for my Auth page. Problem is when i go to Auth page with custom layout, i don't get any error, but anytime i try to back from Auth page, I'll get above error. when i do success `login/register` or just hit Back button I'll get that warning on loading homepage\n\nHere's default layout which is located in default place when nuxt installed :\n\n```\n\n \n \n \n \n \n\n export default {\n components: {AppHeader, AppFooter},\n async fetch () {\n try {\n const layout= await this.$axios.$get('/app')\n this.app= layout;\n } catch (e) {\n console.log(e)\n }\n },\n data() {\n return{\n app: null,\n }\n }\n }\n\n```\n\n========================================\n\nTop Answer:\nI managed to fix this by adding name attribute to the layout...\n\n### layouts/default.vue\n\n```\nexport default {\n name: \"default\"\n ...\n}\n```\n\nAnd the error is gone\n\n========================================\n\nCode:\n```text\n<template>\n <v-main>\n <v-flex>\n <Nuxt />\n </v-flex>\n </v-main>\n</template>\n\n<script>\n export default {\n components: {AppHeader, AppFooter},\n async fetch () {\n try {\n const layout= await this.$axios.$get('/app')\n this.app= layout;\n } catch (e) {\n console.log(e)\n }\n },\n data() {\n return{\n app: null,\n }\n }\n }\n</script>\n```\n\n```text\n[Vue warn]: Invalid component name: \"layouts/default.vue\". Component names should conform to valid custom element name in html5 specification.\n```\n\n```text\nlogin/register\n```\n\n```text\nasync fetch\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nasync fetch\n```\n\n```text\nNuxt 2\n```\n\n```text\nasync fetch\n```\n\n```text\nDynamic Page Render\n```\n\n```text\nWordpress\n```\n\n```text\nDynamic Layout changer\n```\n\n```text\nasync fetch\n```\n\n```text\nasync fetch\n```\n\n```text\nVue\n```\n\n```text\nname : {layoutName}\n```\n\n```text\nasync fetch\n```\n\n```text\nNuxt 2\n```\n\n```text\nNuxtServerInit\n```\n\n```text\nasync fetch\n```\n\n```text\nNuxtServerInit\n```\n\n```text\nexport default {\n name: \"auth\"\n }\n```\n\n```text\nexport default {\n name: \"default\"\n ...\n}\n```\n\n========================================\n\nComments:\n- Thanks but problem was because of fetch in default.\n- This works, however, you may want to hold to some of the eslint vuejs options. In this case `vue/component-definition-name-casing`. This rule states you should use PascalCasing. So instead of `default` you should use `Default` or even better `DefaultLayout`","metadata":{"transformedAt":"2026-08-18T18:33:07.846Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":184,"estimatedTokens":697}}185{"id":"stack-68837954","source":"stackoverflow","questionId":68837954,"title":"How do dynamic API calls work in Nuxt.js static vs SSR mode?","tags":["vue.js","http","nuxt.js","hosting","web-deployment"],"text":"Title: How do dynamic API calls work in Nuxt.js static vs SSR mode?\nTags: vue.js, http, nuxt.js, hosting, web-deployment\nSource: Stack Overflow\n\nQuestion:\nEven after reading through multiple articles explaining the differences between static and SSR rendering I still don't understand how dynamic API calls work in these different modes.\n\nI know that Nuxt has the `fetch` and `asyncData` hooks which are only called once during static generation, but what if I use dynamic HTTP requests inside component methods (e.g. when submitting a form via a POST request)? Does that even work in static sites?\n\nI'm making a site that shows user generated content on most pages, so I have to make GET requests everytime one of those pages is visited to keep the content up to date. Can I do that with a static site or do I have to use SSR / something else? I don't want to use client side rendering (SPA mode) because it's slow and bad for SEO. So what is my best option?\n\n========================================\n\nTop Answer:\nI use dynamic HTTP requests inside component methods (e.g. when submitting a form via a POST request)? Does that even work in static sites?\n\nThe short answer to this question is that yes, it does work. In fact you can have http requests in any life cycle hooks or methods in your code, and they all work fine with static mode too.\n\nStatic site generation and ssr mode in Nuxt.js are tools to help you with SEO issues and I will explain the difference with an example.\n\nImagine you have a blog post page at a url like `coolsite.com/blogs` with some posts that are coming from a database.\n\n**SPA**\n\nIn this mode, when a user visits the said URL server basically responds with a .js file, then in the client this .js file will be rendered. A Vue instance gets created and when the app reaches the code for the `get posts` request for example in the `created` hook, it makes an API call, gets the result and renders the posts to the DOM.\n\nThis is not cool for SEO since at the first app load there isn't any content and all search engine web crawlers are better at understanding content as html rather than js.\n\n**SSR**\n\nIn this mode if you use the asyncData hook, when the user requests for the said URL, the server runs the code in the asyncData hook in which you should have your API call for the blog posts. It gets the result, renders it as an html page and sends that back to the user with the content already inside it (the Vue instance still gets created in the client). There is no need for any further request from client to server. Of course you still can have api calls in other methods or hooks.\n\nThe drawback here is that you need a certain way for deployment for this to work since the code must run on the server. For example you need node.js web hosting to run your app on the server.\n\n**STATIC**\n\nThis mode is actually a compromise between the last two. It means you can have static web hosting but still make your app better for SEO.\n\nThe way it works is simple. You use asyncData again but here, when you are generating your app in your local machine it runs the code inside asyncData, gets the posts, and then renders the proper html for each of your app routes. So when you deploy and the user requests that URL, she/he will get a rendered page just like the one in SSR mode.\n\nBut the drawback here is that if you add a post to your database, you need to generate your app in your local machine, and update the required file(s) on your server with newly generated files in order for the user to get the latest content.\n\nApart from this, any other API call will work just fine since the code required for this is already shipped to the client.\n\nSide note: I used asyncData in my example since this is the hook you should use in page level but fetch is also a Nuxt.js hook that works more or less the same for the component level.\n\n========================================\n\nCode:\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nasyncData()\n```\n\n```text\nfetch()\n```\n\n```text\ntarget: static\n```\n\n```text\ntarget: server\n```\n\n```text\nSSG + SPA\n```\n\n```text\nSSR + SPA\n```\n\n```text\nasyncData()\n```\n\n```text\nfetch()\n```\n\n```text\nfetch\n```\n\n```text\npayload\n```\n\n```text\nasyncData\n```\n\n```text\napp built ahead of time, with no need for a Node.js server\n```\n\n```text\nssr: true\n```\n\n```text\ntarget: server\n```\n\n```text\nyarn build && yarn start\n```\n\n```text\nssr: true\n```\n\n```text\ntarget: static\n```\n\n```text\nyarn generate && yarn start\n```\n\n```text\nssr: false\n```\n\n```text\ntarget: static\n```\n\n```text\ntarget: server\n```\n\n```text\nyarn generate && yarn start\n```\n\n```text\nTwitter\n```\n\n```text\nFacebook\n```\n\n```text\ncoolsite.com/blogs\n```\n\n```text\nget posts\n```\n\n```text\ncreated\n```\n\n========================================\n\nComments:\n- But if API calls are still made from the static site, can't I simply put the GET /blogposts request in the mounted() hook instead of the asyncData() hook and thus keep the content up to date without having to generate it again?\n- @DaDo you can totally also make the call each time if you want something really dynamic yeah. Meanwhile, prefer using either `asyncData()` or `fetch()` since those 2 are aimed towards this usage and, are available here. Even in a VueJS app, I'd recommend running async calls in a `created()` hook, not a `mounted()`.\n- @DaDo you can! but client doesn't get a page populated with content, it gets the page, then gets the posts then populate the page with content. the whole point of `asyncData` here is to deliver a page filled with content so it performs better when it comes to SEO\n- @hamidniakan so a static site with API calls is basically the same as an SPA but with slightly better SEO because you're still getting the whole HTML structure just not filled with dynamic content yet (?)\n- @DaDo in the bigger picture yeah. It's a bit more complex looking at what is happening behind the curtains but an universal app is basically an SPA on steroids yeah. And *static* could be named *ready for CDN* (lol), because it usually confuses people thinking that it's just a hardcoded static file while it is `static + JS`, with `static` meaning that the file is already generated but JS can do totally dynamic things. So `generated ahead of time with Single Page App hydration` is the more accurate naming for this one.\n- @DaDo yes a static site with API calls is the same as a SPA, in terms of SEO I'm not sure if you send a html page to the client but with no content filled in it in its first load how much better it would be ¯_(ツ)_/¯ . to get a better understanding of this concept and know how to use the full potential of a `static` site generated with nuxt i recomment you to check this video noti.st/debbie/wH1qH8\n- @hamidniakan you do actually send raw HTML to the end user yeah. Try disabling your JS to be sure! Of course, it also depends on what you do have in your page. And yeah, Debbie did some awesome videos/talks. :D\n- @kissu yes I'm sure you send raw HTML to the client ^_~ what I'm not sure about is how much difference is between a raw HTML which should get the content after loaded to the client and populate the page and the all js version in a full SPA app in terms of SEO. I guess the first one might be better! if I were to chose static generation, I would choose it in situation where I would use `asyncData` and if the content needs to be updated I would generate the site again. of course I'm talking about a content-full site not an admin panel or alike. this way I make sure to take full advantage for SEO\n- @hamidniakan you don't really have any SEO in an SPA. Or at least, Google will give you a far better score if it doesn't need to understand the JS but just to read the HTML (web metrics can be found on web.dev). I do prefer `fetch()` all day vs `asyncData()` tbh.\n- @DaDo I think that hamidniakan's answer deserves to be accepted. It really gives a good perspective on a multifaceted topic, and it helped me a lot\n- Have tried to edit the answer to improve style and punctuation, but it seems the edit queue is permanently full?\n- @Sharkfin try it another time? Also, what edit do you want to do? Minor details like punctuation and alike are not good enough to be considered as a good edit usually.\n- Thank you for this detailed answer, but I'm still confused about some things. The first is you said that asyncData and fetch hooks are called on route changes in the SPA even with an SSG app, but the documentation says something different: \"For static hosting, the fetch hook is only called during page generation, and the result is then cached for use on the client\". The second is you wrote `ssr: false` + `target: static` for SPA but this stackoverflow answer says that's not possible: stackoverflow.com/a/63638062/13575631\n- @DaDo if you read the answer closely, you'll find that a comment of mine saying that this one is faulty. Looking at the sentence you quoted, available here: nuxtjs.org/docs/2.x/features/data-fetching#the-fetch-hook It is comparing both the behavior of `fetch()` during SSR and during SSG. When you SSR, it will generate the thing each time you reach the server (page reload or typing the URL), but if you SSG it, it will create it as static, hence no need to generate the page on the server each time aka `the fetch hook is only called during page generation` + on client after hydration ofc\n- ok I saw your comment on that other answer now. Regarding fetch, does that mean when I first visit the page (or refresh it) it will show potentially outdated content but when I navigate to that same page from inside the app it will show updated content?\n- @DaDo first off, if you use `asyncData()` on first page visit or refresh, this hook will just not be triggered (it does only during page transitions). Meanwhile, if you use `fetch()`, it will totally be called once your hydration is done and it will get the latest content, up to date. The cached version of the `fetch()` hook can maybe sometimes help performance-wise I guess. I am using a middleware in our app, so I cannot be totally sure of the behavior if the data is different from server to client. But I don't see why it won't be updated. Here, you'll need to try it yourself IMO.\n- Sorry for necroing this old question, but I have yet another question regarding your previous comments. You said `fetch()` will be called after hydration on client side in SSG mode, adding onto the cached data if any new content was found (or overriding the cache, not sure about that). But in this official Nuxt article there's this quote on the new `nuxt-generate`: **\"no more HTTP calls to your API on client-side navigation\"**. Were you talking about the old static generation?\n- @DaDo if you're accessing the data that Nuxt have generated statically, you will not make any HTTP calls indeed. Like in my answer here. Meanwhile, if you're reaching for Google (for example) or any other external API via an axios request, you will need to make an HTTP call.\n- But if that external API call to Google (for example) is inside a `fetch()` or `asyncData()` then that will be statically generated, or not? The only HTTP calls during runtime should be those **outside** of the Nuxt hooks, like in `mounted()` or any method. Or are there exceptions even to `fetch()`?\n- @DaDo sorry, I'm not sure of having the answer exactly here. For me, you should not make exceptions on what you do put inside of `fetch()` or `asyncData()`. Also, the best solution is to try the calls you're wishing to have. Either inspect the `/dist` directory or look in your devtools network tab to see what will be called.\n- Ok thank you anyway, it's a very confusing topic. I'll continue this discussion on the Nuxt Discord.\n- @DaDo please feel free to report back your findings here!\n- @DaDo I believe I'm trying to get an answer for the same question. I've asked this on GitHub but unfortunately, so far without a response. github.com/nuxt/nuxt.js/discussions/9825","metadata":{"transformedAt":"2026-08-18T18:33:07.846Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":191,"estimatedTokens":2986}}186{"id":"stack-60792922","source":"stackoverflow","questionId":60792922,"title":"Contentful with Nuxt.JS \"Expected parameter accessToken\"","tags":["javascript","vue.js","axios","nuxt.js","contentful"],"text":"Title: Contentful with Nuxt.JS \"Expected parameter accessToken\"\nTags: javascript, vue.js, axios, nuxt.js, contentful\nSource: Stack Overflow\n\nQuestion:\nI made a page which pulls data from Contentful. The data is pulling correctly, but buttons which use functions from methods don't work. Live updating of variables (for example, using `v-model`) doesn't work either.\n\nI see this error in the console:\n\nhttps://i.sstatic.net/K5azi.png\n\nI think this error is the problem. Does anyone know what's wrong? I have no clue how to solve it :(\n\nMy contentful.js:\n\n```\nconst contentful = require('contentful')\n\nconst client = contentful.createClient({\n space: process.env.CONTENTFUL_ENV_SPACE_ID,\n accessToken: process.env.CONTENTFUL_ENV_ACCESS_TOKEN\n})\n\nmodule.exports = client\n```\n\nCode which pulls data:\n\n```\nexport default {\n layout: \"landing_page\",\n asyncData() {\n return client\n .getEntries({\n content_type: \"landingPage\"\n })\n .then(entries => {\n return { contentfulData: entries.items[0].fields };\n });\n },\n computed: {\n styles() {\n return landingPageCss;\n }\n },\n components: {\n priceBox,\n contact,\n home,\n aboutUs,\n footerDiv\n }\n};\n```\n\n========================================\n\nTop Answer:\nIf you use dotenv you need to do following steps:\n\n```\nnpm install --save-dev @nuxtjs/dotenv\n```\n\nThen you install it as an module. Note here if you using Nuxt.js older then v2.9 then you ahve to go to `nuxt.config.js` and put your code into the `module` section:\n\n```\n...\n module: [\n '@nuxtjs/dotenv'\n ]\n...\n```\n\nIf there is no `module` section then create one.\n\nIf you using newer then v2.9 then you put it into the `buildModules`\n\n```\n...\n buildModules: [\n '@nuxtjs/dotenv'\n ]\n...\n```\n\nYour variables that are saved in the `.env` file are now accessable through `context.env` or `process.env`\n\n========================================\n\nCode:\n```text\nconst contentful = require('contentful')\n\nconst client = contentful.createClient({\n space: process.env.CONTENTFUL_ENV_SPACE_ID,\n accessToken: process.env.CONTENTFUL_ENV_ACCESS_TOKEN\n})\n\nmodule.exports = client\n```\n\n```text\nexport default {\n layout: \"landing_page\",\n asyncData() {\n return client\n .getEntries({\n content_type: \"landingPage\"\n })\n .then(entries => {\n return { contentfulData: entries.items[0].fields };\n });\n },\n computed: {\n styles() {\n return landingPageCss;\n }\n },\n components: {\n priceBox,\n contact,\n home,\n aboutUs,\n footerDiv\n }\n};\n```\n\n```text\nv-model\n```\n\n```text\nconst env = require('dotenv').config()\n\nexport default {\n mode: 'universal',\n ...\n env: env.parsed,\n ...\n}\n```\n\n```text\n.env\n```\n\n```text\nnpm install --save-dev @nuxtjs/dotenv\n```\n\n```text\n...\n module: [\n '@nuxtjs/dotenv'\n ]\n...\n```\n\n```text\n...\n buildModules: [\n '@nuxtjs/dotenv'\n ]\n...\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nmodule\n```\n\n```text\nmodule\n```\n\n```text\nbuildModules\n```\n\n```text\n.env\n```\n\n```text\ncontext.env\n```\n\n```text\nprocess.env\n```\n\n========================================\n\nComments:\n- have you tried outputting the contents of `process.env.CONTENTFUL_ENV_ACCESS_TOKEN`? Maybe the environment isn't being loaded correctly?\n- @milgner Yes, it doesn't work :(\n- So the question is: how are you setting the environment? Are you using `https://www.npmjs.com/package/dotenv`? Via another mechanism?\n- Yes, I use dotenv\n- Okay but then your question isn't about Nuxt or the Contentful API but about your environment not being loaded correctly? You should add some code about how you're loading dotenv and maybe a redacted version of your `.env` file?","metadata":{"transformedAt":"2026-08-18T18:33:07.846Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":204,"estimatedTokens":899}}187{"id":"stack-58845658","source":"stackoverflow","questionId":58845658,"title":"What is the best approach in dynamic Vuex module initialisation when using Nuxt.js?","tags":["vue.js","vuex","store","nuxt.js","server-side-rendering"],"text":"Title: What is the best approach in dynamic Vuex module initialisation when using Nuxt.js?\nTags: vue.js, vuex, store, nuxt.js, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nLately, I have been building a large scale application that uses a lot of separate Vuex modules. Let's take a look at one of them (e.g. `support-chat`). Support chat is located on it's own separate page, and it would be redundant to pollute the store with this module on initial application load. My goal is to register this module dynamically when it's page is loaded. So my question is – where, when and how should I register that module?\n\nI end up registering this module in the `beforeCreate` hook of the page component:\n\n```\nimport supportChatModule from '@/vuex/modules/support-chat'\n\n// ...\nbeforeCreate() {\n this.$store.registerModule('support-chat', supportChatModule, { preserveState: process.client })\n},\nbeforeDestroy() {\n this.$store.unregisterModule('support-chat')\n}\n// ...\n```\n\nWhat pitfalls does that approach have?\n\nIt would be great if you can your approach in solving that issue.\n\n========================================\n\nTop Answer:\n**Step 1:**\n\nCreate a mixin, I named it `register-vuex-module.js`:\n\n```\nexport const registerVuexModule = (name, module) => ({\n beforeCreate() {\n const { $store } = this\n\n if ($store.hasModule(name)) $store.commit(`${name}/resetState`)\n else $store.registerModule(name, module().default)\n }\n})\n```\n\n**Step 2:**\nUse the mixin to import a module:\n\n```\n\n...\n\n// Mixins\nimport { registerVuexModule } from '@/mixins/register-vuex-module'\n\nexport default {\n mixins: [registerVuexModule('module-name', () => require('./vuex/MyVuexModule.js'))],\n}\n\n```\n\n**Step 3:**\n\nMake sure your Vuex module has a `resetState` mutation and also the state gets returned from a function. Here is an example of how `MyVuexModule.js` should look like:\n\n```\nconst initialState = () => ({\n count: null\n})\n\nexport default {\n namespaced: true,\n\n state: initialState(),\n\n mutations: {\n // ...\n resetState: state => Object.assign(state, initialState())\n }\n}\n```\n\n========================================\n\nCode:\n```js\nimport supportChatModule from '@/vuex/modules/support-chat'\n\n// ...\nbeforeCreate() {\n this.$store.registerModule('support-chat', supportChatModule, { preserveState: process.client })\n},\nbeforeDestroy() {\n this.$store.unregisterModule('support-chat')\n}\n// ...\n```\n\n```text\nsupport-chat\n```\n\n```text\nbeforeCreate\n```\n\n```js\nrouter.beforeEach((to, from, next) => {\n\n // unregister modules\n if (from.meta.modules) {\n for (const key in from.meta.modules.primary) {\n if (to.meta.modules && to.meta.modules.primary.hasOwnProperty(key)) {\n continue;\n }\n if (store.state.hasOwnProperty(key)) {\n // don't unregister freeze modules\n if (from.meta.modules.hasOwnProperty('freeze') && from.meta.modules.freeze.find(item => item == key)) {\n continue;\n }\n store.unregisterModule(key);\n }\n }\n }\n // register modules\n if (to.meta.modules) {\n for (const key in to.meta.modules.primary) {\n const module = to.meta.modules.primary[key]();\n if (!store.state.hasOwnProperty(key)) {\n store.registerModule(key, module.default);\n }\n }\n }\n});\n```\n\n```js\n{\n path: 'users',\n name: 'users',\n meta: {\n modules: {\n primary: {\n user: () => require('@/store/modules/moduleUser')\n }\n },\n },\n component: () => import('../views/users.vue')\n},\n\n{\n path: 'foods',\n name: 'foods',\n meta: {\n modules: {\n primary: {\n food: () => require('@/store/modules/moduleFood'),\n user: () => require('@/store/modules/moduleUser')\n },\n freeze: ['food']\n },\n },\n component: () => import('../views/foods.vue')\n},\n```\n\n```text\nregister\n```\n\n```text\nunregister\n```\n\n```text\nrouter file\n```\n\n```text\nrouter/index.js\n```\n\n```text\nbeforeEach\n```\n\n```text\npath\n```\n\n```js\nexport const registerVuexModule = (name, module) => ({\n beforeCreate() {\n const { $store } = this\n\n if ($store.hasModule(name)) $store.commit(`${name}/resetState`)\n else $store.registerModule(name, module().default)\n }\n})\n```\n\n```html\n<template>\n...\n</template>\n\n<script>\n// Mixins\nimport { registerVuexModule } from '@/mixins/register-vuex-module'\n\nexport default {\n mixins: [registerVuexModule('module-name', () => require('./vuex/MyVuexModule.js'))],\n}\n</script>\n```\n\n```js\nconst initialState = () => ({\n count: null\n})\n\nexport default {\n namespaced: true,\n\n state: initialState(),\n\n mutations: {\n // ...\n resetState: state => Object.assign(state, initialState())\n }\n}\n```\n\n```text\nregister-vuex-module.js\n```\n\n```text\nresetState\n```\n\n```text\nMyVuexModule.js\n```\n\n========================================\n\nComments:\n- why exactly does the default not work for you? can you elaborate?\n- Looks great, looking forward to check it out","metadata":{"transformedAt":"2026-08-18T18:33:07.847Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":249,"estimatedTokens":1214}}188{"id":"stack-53993252","source":"stackoverflow","questionId":53993252,"title":"Dynamically get image paths in folder with Nuxt","tags":["javascript","vue.js","webpack","nuxt.js"],"text":"Title: Dynamically get image paths in folder with Nuxt\nTags: javascript, vue.js, webpack, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nhttps://i.sstatic.net/3FKZH.png\n\nI'm using nuxt with vuetify. I have a working carousel component .I want to generate a list of The .png files in the static folder. Following Dynamically import images from a directory using webpack and Following https://webpack.js.org/guides/dependency-management/#context-module-api my component looks like:\n\n```\n\n \n \n \n\n var cache = {};\n function importAll(r) {\n r.keys().forEach(key => cache[key] = r(key));\n }\n var getImagePaths = importAll(require.context('../static/', false, /\\.png$/));\n // At build-time cache will be populated with all required modules. \n export default {\n data: function() {\n return {\n items: getImagePaths\n };\n }\n };\n // export default {\n // data() {\n // return {\n // items: [{\n // src: \"/52lv.PNG\"\n // },\n // {\n // src: \"https://cdn.vuetifyjs.com/images/carousel/sky.jpg\"\n // },\n // {\n // src: \"https://cdn.vuetifyjs.com/images/carousel/bird.jpg\"\n // },\n // {\n // src: \"https://cdn.vuetifyjs.com/images/carousel/planet.jpg\"\n // }\n // ]\n // };\n // }\n // };\n //\n\n```\n\nI want to search through the static folder and grab the paths to the images , put them in an array and export them to the html template. \n\nI've found that if I edit the script's items array to look the following it will work:\n\nitems: [\n {\n src: '/52iv.png'\n },\n {\n src: '/91Iv.png'\n },\n ....\n\nHow can I adjust my code to get the result I need?\n\nEDIT:\n\nI looked at the proposed solution , but after copying it verbatum I got the following error.\n\nhttps://i.sstatic.net/ThiTL.png\n\n========================================\n\nCode:\n```text\n<template>\n <v-carousel>\n <v-carousel-item v-for=\"(item,i) in items\" :key=\"i\" :src=\"item.src\"></v-carousel-item>\n </v-carousel>\n</template>\n\n\n<script>\n\n var cache = {};\n function importAll(r) {\n r.keys().forEach(key => cache[key] = r(key));\n }\n var getImagePaths = importAll(require.context('../static/', false, /\\.png$/));\n // At build-time cache will be populated with all required modules. \n export default {\n data: function() {\n return {\n items: getImagePaths\n };\n }\n };\n // export default {\n // data() {\n // return {\n // items: [{\n // src: \"/52lv.PNG\"\n // },\n // {\n // src: \"https://cdn.vuetifyjs.com/images/carousel/sky.jpg\"\n // },\n // {\n // src: \"https://cdn.vuetifyjs.com/images/carousel/bird.jpg\"\n // },\n // {\n // src: \"https://cdn.vuetifyjs.com/images/carousel/planet.jpg\"\n // }\n // ]\n // };\n // }\n // };\n //\n</script>\n```\n\n```text\n<template>\n <v-carousel>\n <v-carousel-item v-for=\"(item,i) in items\" :key=\"i\" :src=\"item.src\"></v-carousel-item>\n </v-carousel>\n</template>\n\n\n<script>\n var cache = {};\n const images = require.context('../static/', false, /\\.png$/);\n var imagesArray = Array.from(images.keys());\n var constructed = [];\n function constructItems(fileNames, constructed) {\n fileNames.forEach(fileName => {\n constructed.push({\n 'src': fileName.substr(1)\n })\n });\n return constructed;\n }\n var res = constructItems(imagesArray, constructed);\n console.log(res);\n export default {\n data: function() {\n return {\n items: res\n };\n }\n };\n```\n\n========================================\n\nComments:\n- Does this help?\n- Thank you I tried it verbatim but got the following error - Please see edit\n- are you sure your path is correct? what happens if you do `'../main/'` or `'~/main/` instead? in regards to your original code. it looks like your carousel component is only one folder deep.\n- @ryeMoss , I've changed the folder to static\n- I believe I was able to get it working using require.context() and the files in /main/. I imagine it would work the same in /static/. Unfortunately I'm also not very familiar with webpack to help out with your new method\n- Unable to comment, so adding it here. Can you try excluding node_modules from Babel transpilation? A similar '*webpack*' issue was bypassed through this simple hack.\n- I'm brand new to node, webpack etc. (Mostly use python ) Would you mind explaining how to do this?\n- @user61629 pls this link, the discussion in the comments sums up the understanding.","metadata":{"transformedAt":"2026-08-18T18:33:07.847Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":164,"estimatedTokens":1113}}189{"id":"stack-55272347","source":"stackoverflow","questionId":55272347,"title":"Easily add script tags to nuxtjs","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: Easily add script tags to nuxtjs\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nBasically I need to add the script to the head of my index.html,\n\n```\n\n```\n\nso what I've tried is...\n\nin my nuxt.config.js\n\n```\nhead: {\n script: [\n { \n type: 'text/javascript', \n src: 'https://a.optmnstr.com/app/js/api.min.js',\n data-account: 'XXXXX',\n data-user: 'XXXXX',\n async: true\n }\n ]\n}\n```\n\nnow obviously this isn't working since `data-account` and `data-user` is not valid, so how can I make this work??\n\nAny help would be appreciated!\n\nThanks\n\n========================================\n\nTop Answer:\nYou can also just enclose the data attributes in single quotes like this:\n\n```\nhead: {\n script: [\n { \n type: 'text/javascript', \n src: 'https://a.optmnstr.com/app/js/api.min.js',\n 'data-account': 'XXXXX',\n 'data-user': 'XXXXX',\n async: true\n }\n ]\n}\n```\n\n========================================\n\nCode:\n```text\n<script type=\"text/javascript\" src=\"https://a.optmnstr.com/app/js/api.min.js\" data-account=\"XXXXX\" data-user=\"XXXXX\" async></script>\n```\n\n```text\nhead: {\n script: [\n { \n type: 'text/javascript', \n src: 'https://a.optmnstr.com/app/js/api.min.js',\n data-account: 'XXXXX',\n data-user: 'XXXXX',\n async: true\n }\n ]\n}\n```\n\n```text\ndata-account\n```\n\n```text\ndata-user\n```\n\n```text\n<!DOCTYPE html>\n<html {{ HTML_ATTRS }}>\n <head>\n {{ HEAD }}\n </head>\n <body {{ BODY_ATTRS }}>\n {{ APP }}\n </body>\n <script type=\"text/javascript\" src=\"https://a.optmnstr.com/app/js/api.min.js\" data-account=\"XXXX\" data-user=\"XXXX\" async></script>\n</html>\n```\n\n```text\napp.html\n```\n\n```text\napp.html\n```\n\n```text\napp.html\n```\n\n```text\nhead: {\n script: [\n { \n type: 'text/javascript', \n src: 'https://a.optmnstr.com/app/js/api.min.js',\n 'data-account': 'XXXXX',\n 'data-user': 'XXXXX',\n async: true\n }\n ]\n}\n```\n\n```js\nexport default {\n data () {\n return {\n message: '',\n head: {\n type: Object,\n default: function () {\n return {\n title: ' Default Home page ',\n meta: [\n {\n 'hid': 'description',\n 'name': ' description',\n 'content': ' Home page content '\n }\n ],\n script: [\n {\n innerHTML: {\n 'url': 'https://www.example.com',\n 'logo': 'https://www.example.com/icon/logo.png',\n 'parentOrganization': {\n 'name': 'The X Company Inc',\n 'url': 'https://example.io',\n 'logo': 'https://example.io/logo-est.png',\n '@type': 'Organization'\n },\n 'foundingLocation': {\n 'address': {\n 'addressLocality': 'Dakar',\n 'addressRegion': 'Selegal',\n '@type': 'PostalAddress'\n },\n '@type': 'Place'\n },\n 'sameAs': ['https://www.facebook.com/example', 'https://www.twitter.com/example'],\n '@context': 'http://schema.org',\n '@type': 'Organization'\n },\n type: 'application/ld+json'\n }\n ]\n }\n }\n }\n }\n }\n}\n</script>\n```\n\n========================================\n\nComments:\n- You could try and look at this or this.\n- How do you add js that is in the assets folder rather than externally\n- This solution was validated by @atinux here: github.com/nuxt/nuxt.js/issues/1580#issuecomment-327114193\n- This solution works. One question, how to add the custom HEAD script only for production `(target: 'static')` ? And avoid loading it while working on `development`?","metadata":{"transformedAt":"2026-08-18T18:33:07.847Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":181,"estimatedTokens":973}}190{"id":"stack-56155534","source":"stackoverflow","questionId":56155534,"title":"What is the cause of [Vue warn]: Invalid prop: custom validator check failed for prop \"value\"","tags":["vue.js","nuxt.js","vuejs-datepicker"],"text":"Title: What is the cause of [Vue warn]: Invalid prop: custom validator check failed for prop \"value\"\nTags: vue.js, nuxt.js, vuejs-datepicker\nSource: Stack Overflow\n\nQuestion:\nI have nuxt.js app, which uses vuejs-datepicker:\n\n```\n\n \n \n \n```\n\nand bunch of date variables:\n\n```\n\nimport DatePicker from 'vuejs-datepicker'\nimport { DateTime } from 'luxon'\n\nconst moment = require('moment')\n\nconst date = new Date(2016, 8, 16)\nconst date2 = moment('2016-09-16').toDate()\nconst date3 = DateTime.local(2016, 9, 16).toJSDate()\n\nexport default {\n components: {\n DatePicker\n },\n data() {\n return {\n datePicker: {\n mondayFirst: true,\n format: 'dd.MM.yyyy',\n value: date\n }\n }\n }\n}\n```\n\nWhen I bind its 'value' property to usual Date variable 'date', everything is ok, but when I choose date2 or date3, I get this annoying warning\n\n```\n[Vue warn]: Invalid prop: custom validator check failed for prop \"value\".\n\nfound in\n\n---> \n at components/StaticPositions.vue\n \n \n at pages/index.vue\n \n at layouts/default.vue\n \n```\n\nI found custom validator for value property and it is very straightforward and simple and return true in all three cases:\n\n```\nvalue: {\n validator: function (val) { return utils$1.validateDateInput(val); }\n }\n```\n\n...\n\n```\nvalidateDateInput (val) {\n return val === null || val instanceof Date || typeof val === 'string' || typeof val === 'number'\n }\n```\n\nbut what makes the difference then? Could it be Vue.js bug itself?\n\n========================================\n\nCode:\n```text\n<template>\n<!-- ... -->\n\n <DatePicker :value=\"datePicker.value\" />\n <!-- ... -->\n </template>\n```\n\n```text\n<script>\nimport DatePicker from 'vuejs-datepicker'\nimport { DateTime } from 'luxon'\n\nconst moment = require('moment')\n\nconst date = new Date(2016, 8, 16)\nconst date2 = moment('2016-09-16').toDate()\nconst date3 = DateTime.local(2016, 9, 16).toJSDate()\n\nexport default {\n components: {\n DatePicker\n },\n data() {\n return {\n datePicker: {\n mondayFirst: true,\n format: 'dd.MM.yyyy',\n value: date\n }\n }\n }\n}\n```\n\n```text\n[Vue warn]: Invalid prop: custom validator check failed for prop \"value\".\n\nfound in\n\n---> <DatePicker>\n <StaticPositionsTab> at components/StaticPositions.vue\n <BTab>\n <BTabs>\n <Pages/index.vue> at pages/index.vue\n <Nuxt>\n <Layouts/default.vue> at layouts/default.vue\n <Root>\n```\n\n```text\nvalue: {\n validator: function (val) { return utils$1.validateDateInput(val); }\n }\n```\n\n```text\nvalidateDateInput (val) {\n return val === null || val instanceof Date || typeof val === 'string' || typeof val === 'number'\n }\n```\n\n```text\nconst date2 = moment('2016-09-16').toDate()\nconst date3 = DateTime.local(2016, 9, 16).toJSDate()\n\ntypeof date2 // object\ntypeof date3 // object\n```\n\n```text\nconst date2 = moment('2016-09-16').toString()\nconst date2 = moment('2016-09-16').toISOString()\nconst date3 = DateTime.local(2016, 9, 16).toString()\n```\n\n```text\nconst date2 = moment('2016-09-16').unix()\nconst date3 = moment('2016-09-16').valueOf()\nconst date4 = moment('2016-09-16').getTime()\nconst date5 = DateTime.local(2016, 9, 16).valueOf()\n```\n\n```text\ndate2\n```\n\n```text\ndate3\n```\n\n```text\n.toString()\n```\n\n========================================\n\nComments:\n- this is very strange... all of them are objects, including Date itself, you can see it in my codesandbox snippet codesandbox.io/s/f96vz. Moreover, you can see that all of date, date2 and date3 are instances of Date. But.. in browser console. In server side console latter two are not Date instances! ibb.co/yg4hhxt\n- Interesting. I saw that `typeof` and `instanceof` are very different. Might be you should convert to string or unix timestamp to make it works on both server and client.","metadata":{"transformedAt":"2026-08-18T18:33:07.847Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":182,"estimatedTokens":946}}191{"id":"stack-55695816","source":"stackoverflow","questionId":55695816,"title":"Run function AFTER route fully rendered in Nuxt.js","tags":["javascript","vue.js","vue-router","nuxt.js"],"text":"Title: Run function AFTER route fully rendered in Nuxt.js\nTags: javascript, vue.js, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\n### Background:\n\nI'm building an SSR website using Nuxt. I want to run a script to fix some typography issues (orphaned text in headers). I can't do this UNTIL AFTER the DOM is rendered. How can I implement this function once so it runs after each page's DOM is rendered? It can be either in the Router or in a Nuxt Layout, or elsewhere.\n\n### What I've tried:\n\nIn my `layout.vue`, `Mounted()` only runs on the first load (as expected) and adding `$nextTick` doesn't seem to affect that. This is even true for generated static pages served from a real webserver.\n\nIn my `layout.vue`, using Vue's `Updated()` never seems to fire. I assume this means Nuxt is getting in the way.\n\nUsing `app.router.afterEach()` the function runs on each route change (including first load), but way before the DOM is rendered making it worthless.\n\nIf I add `Vue.nextTick()` into the `.afterEach()` the function runs on the current page JUST BEFORE the route changes (you can see it flash) but DOES NOT run before that.\n\n### What works but seems dumb:\n\nPutting the function in the `Mounted()` block on each page.\n\n```\nmounted: function(){\n this.$nextTick(function () {\n const tm = new TypeMate(undefined, { selector: 'h2, h3, p, li' });\n tm.apply();\n \n })\n },\n```\n\nBut this seems like a bad idea especially as we add pages. What am I missing? Is there a smart way to do this? Nuxt's documentation is next to useless for some of this stuff.\n\n========================================\n\nTop Answer:\nYou can simply use NuxtApp hooks. I use that in my default layout and work like a charm.\n\n```\n\nconst nuxtApp = useNuxtApp();\n\nnuxtApp.hook('page:loading:end', () => {\n // doSomething();\n});\n\n```\n\n========================================\n\nCode:\n```text\nmounted: function(){\n this.$nextTick(function () {\n const tm = new TypeMate(undefined, { selector: 'h2, h3, p, li' });\n tm.apply();\n \n })\n },\n```\n\n```text\nlayout.vue\n```\n\n```text\nMounted()\n```\n\n```text\n$nextTick\n```\n\n```text\nlayout.vue\n```\n\n```text\nUpdated()\n```\n\n```text\napp.router.afterEach()\n```\n\n```text\nVue.nextTick()\n```\n\n```text\n.afterEach()\n```\n\n```text\nMounted()\n```\n\n```text\n<script setup lang=\"ts\">\nconst nuxtApp = useNuxtApp();\n\nnuxtApp.hook('page:loading:end', () => {\n // doSomething();\n});\n</script>\n```\n\n========================================\n\nComments:\n- Hmm thanks @Aldarund, is that the same as a Plugin in Nuxt or does it function at a lower level?\n- @BryceHowitson lower. E.g. if you want global mixin you can create nuxt plugin where u just place this mixin\n- can't we add the `readystatechange` event in the `layout` itself?","metadata":{"transformedAt":"2026-08-18T18:33:07.847Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":115,"estimatedTokens":683}}192{"id":"stack-69926027","source":"stackoverflow","questionId":69926027,"title":"Command failed with exit code 134: npm run generate","tags":["node.js","vue.js","continuous-integration","nuxt.js","netlify"],"text":"Title: Command failed with exit code 134: npm run generate\nTags: node.js, vue.js, continuous-integration, nuxt.js, netlify\nSource: Stack Overflow\n\nQuestion:\nI'm trying to deploy my nuxt js project to netlify. The installation part works fine, But it returns an error in the build process.\n\nI tried to search google but I can't find any solution to this problem.\n\nI also tried this command `CI= npm run generate`\n\n```\n3:16:42 PM: $ npm run generate\n3:16:43 PM: > portfolio@1.0.0 generate\n3:16:43 PM: > nuxt generate\n3:16:50 PM: node: ../src/coroutine.cc:134: void* find_thread_id_key(void*): Assertion `thread_id_key != 0x7777' failed.\nAborted\n3:16:50 PM: \n3:16:50 PM: ────────────────────────────────────────────────────────────────\n3:16:50 PM: \"build.command\" failed \n3:16:50 PM: ────────────────────────────────────────────────────────────────\n3:16:50 PM: \n3:16:50 PM: Error message\n3:16:50 PM: Command failed with exit code 134: npm run generate\n3:16:50 PM: \n3:16:50 PM: Error location\n3:16:50 PM: In Build command from Netlify app:\n3:16:50 PM: npm run generate\n3:16:50 PM: \n3:16:50 PM: Resolved config\n3:16:50 PM: build:\n3:16:50 PM: command: npm run generate\n3:16:50 PM: commandOrigin: ui\n3:16:50 PM: publish: /opt/build/repo/dist\n3:16:50 PM: publishOrigin: ui\n3:16:50 PM: Caching artifacts\n3:16:50 PM: Started saving node modules\n3:16:50 PM: Finished saving node modules\n3:16:50 PM: Started saving build plugins\n3:16:50 PM: Finished saving build plugins\n3:16:50 PM: Started saving pip cache\n3:16:50 PM: Finished saving pip cache\n3:16:50 PM: Started saving emacs cask dependencies\n3:16:50 PM: Finished saving emacs cask dependencies\n3:16:50 PM: Started saving maven dependencies\n3:16:50 PM: Finished saving maven dependencies\n3:16:50 PM: Started saving boot dependencies\n3:16:50 PM: Finished saving boot dependencies\n3:16:50 PM: Started saving rust rustup cache\n3:16:50 PM: Finished saving rust rustup cache\n3:16:50 PM: Started saving go dependencies\n3:16:50 PM: Finished saving go dependencies\n3:16:52 PM: Build failed due to a user error: Build script returned non-zero exit code: 2\n3:16:52 PM: Creating deploy upload records\n3:16:52 PM: Failing build: Failed to build site\n3:16:52 PM: Failed during stage 'building site': Build script returned non-zero exit code: 2\n3:16:52 PM: Finished processing build request in 1m34.230804646s\n```\n\nHere is the Nuxt Config -\nMy target is to build a static site. You may guess this is my portfolio site. I'm working on my portfolio to get a better job.\n\n`nuxt.config.js`\n\n```\nexport default {\n // Target: https://go.nuxtjs.dev/config-target\n target: 'static',\n\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: 'Hasibur',\n htmlAttrs: {\n lang: 'en'\n },\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: '' },\n { name: 'format-detection', content: 'telephone=no' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\n '@/assets/scss/main.scss'\n ],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [\n { src: '~/plugins/components.js', mode: 'client' },\n { src: '~/plugins/fontawesome.js', mode: 'client' },\n ],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n // https://go.nuxtjs.dev/tailwindcss\n '@nuxtjs/tailwindcss',\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\n // https://go.nuxtjs.dev/axios\n '@nuxtjs/axios',\n ],\n\n // Axios module configuration: https://go.nuxtjs.dev/config-axios\n axios: {},\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {\n }\n}\n```\n\n========================================\n\nCode:\n```text\n3:16:42 PM: $ npm run generate\n3:16:43 PM: > portfolio@1.0.0 generate\n3:16:43 PM: > nuxt generate\n3:16:50 PM: node: ../src/coroutine.cc:134: void* find_thread_id_key(void*): Assertion `thread_id_key != 0x7777' failed.\nAborted\n3:16:50 PM: \n3:16:50 PM: ────────────────────────────────────────────────────────────────\n3:16:50 PM: \"build.command\" failed \n3:16:50 PM: ────────────────────────────────────────────────────────────────\n3:16:50 PM: \n3:16:50 PM: Error message\n3:16:50 PM: Command failed with exit code 134: npm run generate\n3:16:50 PM: \n3:16:50 PM: Error location\n3:16:50 PM: In Build command from Netlify app:\n3:16:50 PM: npm run generate\n3:16:50 PM: \n3:16:50 PM: Resolved config\n3:16:50 PM: build:\n3:16:50 PM: command: npm run generate\n3:16:50 PM: commandOrigin: ui\n3:16:50 PM: publish: /opt/build/repo/dist\n3:16:50 PM: publishOrigin: ui\n3:16:50 PM: Caching artifacts\n3:16:50 PM: Started saving node modules\n3:16:50 PM: Finished saving node modules\n3:16:50 PM: Started saving build plugins\n3:16:50 PM: Finished saving build plugins\n3:16:50 PM: Started saving pip cache\n3:16:50 PM: Finished saving pip cache\n3:16:50 PM: Started saving emacs cask dependencies\n3:16:50 PM: Finished saving emacs cask dependencies\n3:16:50 PM: Started saving maven dependencies\n3:16:50 PM: Finished saving maven dependencies\n3:16:50 PM: Started saving boot dependencies\n3:16:50 PM: Finished saving boot dependencies\n3:16:50 PM: Started saving rust rustup cache\n3:16:50 PM: Finished saving rust rustup cache\n3:16:50 PM: Started saving go dependencies\n3:16:50 PM: Finished saving go dependencies\n3:16:52 PM: Build failed due to a user error: Build script returned non-zero exit code: 2\n3:16:52 PM: Creating deploy upload records\n3:16:52 PM: Failing build: Failed to build site\n3:16:52 PM: Failed during stage 'building site': Build script returned non-zero exit code: 2\n3:16:52 PM: Finished processing build request in 1m34.230804646s\n```\n\n```text\nexport default {\n // Target: https://go.nuxtjs.dev/config-target\n target: 'static',\n\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: 'Hasibur',\n htmlAttrs: {\n lang: 'en'\n },\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: '' },\n { name: 'format-detection', content: 'telephone=no' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\n '@/assets/scss/main.scss'\n ],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [\n { src: '~/plugins/components.js', mode: 'client' },\n { src: '~/plugins/fontawesome.js', mode: 'client' },\n ],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n // https://go.nuxtjs.dev/tailwindcss\n '@nuxtjs/tailwindcss',\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\n // https://go.nuxtjs.dev/axios\n '@nuxtjs/axios',\n ],\n\n // Axios module configuration: https://go.nuxtjs.dev/config-axios\n axios: {},\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {\n }\n}\n```\n\n```text\nCI= npm run generate\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnpm uninstall fibers\n```\n\n```text\npackage-lock.json\n```\n\n```text\nnode_modules/\n```\n\n```text\nnpm install\n```\n\n```text\npackage.json\n```\n\n```text\npackage-lock.json\n```\n\n========================================\n\nComments:\n- Does it work locally? Also, can you please your `nuxt.config.js` file? Also, do you know what is `coroutine.cc`?\n- Yes, It works locally very well. And I don't know this file `coroutine.cc` .\n- What if you generate your project and then, upload your `/dist` directory on app.netlify.com/drop?\n- The problem was ```fibers````. Thanks\n- But I have to use fibers because I'm using `sass` and `sass-loader`. Nuxt required to use `fibers` when you need `sass`\n- Nuxt doesn't require it, they just recommended it since it improved build time. When you look in the docs now, they actually don't mention it anymore.","metadata":{"transformedAt":"2026-08-18T18:33:07.847Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":270,"estimatedTokens":2059}}193{"id":"stack-61967891","source":"stackoverflow","questionId":61967891,"title":"How to create back button using NuxtJS ?","tags":["nuxt.js"],"text":"Title: How to create back button using NuxtJS ?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a fairly new Nuxt project I'm working on, and I'm running in to an issue setting up a back button. I even looked at the \"vue-router-back-button\" package which still doesn't want to work (I was getting unrelated errors). With the code that I have, the link wants to navigate to the same page that the user is currently on, rather than the one previous. I do receive an error on my server that there is an `Invalid prop: type check failed for prop \"to\". Expected String, Object, got Function.`, however would I make the back button dynamic?\n\n```\n\n \n \n \n \n Back\n \n\n \n \n {{ text }}\n \n \n\n export default {\n props: {\n back: {\n type: Boolean,\n default: false,\n },\n text: {\n type: String,\n default: 'Page'\n }\n },\n\n methods: {\n to() {\n this.$router.go(-1); \n```\n\n========================================\n\nTop Answer:\nYou can also use this by checking window history length. If window history is 1 or less than 1 then it's going back to your home page. More usable.\n\n```\nwindow.history.length > 1 ? this.$router.go(-1) : this.$router.push('/')\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div class=\"page-title-wrapper\">\n <nuxt-link\n v-if=\"back\"\n :to=\"to\"\n class=\"back-wrapper\">\n <icon\n name=\"angle-left\"\n fill=\"#9e9e9e\"\n height=\"20px\"\n width=\"20px\"\n class=\"d-flex\" />\n <p class=\"display-1 grey--text\">\n Back\n </p>\n </nuxt-link>\n <h1 class=\"display-3 text-center\">\n {{ text }}\n </h1>\n </div>\n</template>\n\n<script>\n export default {\n props: {\n back: {\n type: Boolean,\n default: false,\n },\n text: {\n type: String,\n default: 'Page'\n }\n },\n\n methods: {\n to() {\n this.$router.go(-1); <---- evaluates to current page?\n },\n }\n }\n</script>\n```\n\n```text\nInvalid prop: type check failed for prop \"to\". Expected String, Object, got Function.\n```\n\n```text\nthis.$router.go(-1)\n```\n\n```text\n<div @click=\"goToPrev()\">My Button</div>\n```\n\n```text\nmethods: {\n goToPrev() {\n\n // ...\n // Do other logic like logging, etc.\n // ...\n\n // Tell router to go back one\n this.$router.go(-1);\n },\n}\n```\n\n```text\n<template> \n <v-btn text :ripple=\"false\" class=\"back-wrapper\" @click=\"to\">\n <icon name=\"angle-left\" fill=\"#9e9e9e\" height=\"20px\" width=\"20px\" class=\"d-flex\" />\n <p class=\"display-1 grey--text\">\n Back\n </p>\n </v-btn>\n </template>\n\n <script>\n methods: {\n to() {\n this.$router.go(-1)\n },\n }\n </script>\n```\n\n```text\n<v-btn>\n```\n\n```text\nwindow.history.length > 1 ? this.$router.go(-1) : this.$router.push('/')\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.847Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":148,"estimatedTokens":691}}194{"id":"stack-71537227","source":"stackoverflow","questionId":71537227,"title":"How to deploy and generate a static site on Nuxt 3?","tags":["deployment","nuxt.js","nuxt3.js"],"text":"Title: How to deploy and generate a static site on Nuxt 3?\nTags: deployment, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm creating website on Nuxt and I have created a new app on Nuxt 3. But I have a problem for the deployment, there is no 'normal' build for 'normal server' as Nuxt 2.x.\n\nI'm using 'Lambda' preset.\nhttps://v3.nuxtjs.org/docs/deployment/presets/lambda\n\n\r\n\r\n\n```\n// nuxt.config.ts\n\nimport { defineNuxtConfig } from 'nuxt3'\n\n// https://v3.nuxtjs.org/docs/directory-structure/nuxt.config\nexport default defineNuxtConfig({\n // Global page headers: https://go.nuxtjs.dev/config-head\n\n nitro: {\n preset: 'lambda'\n },\n\n head: {\n title: 'Title',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' }\n \n \n ],\n link: [\n { rel: 'icon', type: 'image/png', href: '/favicon.png' }\n ],\n script: [\n { \n type: 'text/javascript', \n src: '/mana.js',\n }\n]\n},\n})\n```\n\n\r\n\r\n\r\n\nAnd on Nuxt 2.x I used this:\n\n\r\n\r\n\n```\n// nuxt.config.js\n\nexport default {\n // Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode\n ssr: false,\n\n // Target: https://go.nuxtjs.dev/config-target\n target: 'static'\n}\n```\n\n\r\n\r\n\r\n\n**What configuration should I use on Nuxt 3 to have 'normal' export with an `index.html` file at the root for all server?**\n\n========================================\n\nTop Answer:\nPlease use generate script like `yarn generate` this will create the `.output/public` and output will depend on `ssr: boolean` property in `nuxt.config.ts`.\n\nif `ssr` is true which is by default, then there will be individual html for each dynamic route and that means dynamic routes are rendered at build time and whenever there is change in data or number of dynamic routes then you will need to run this command again.\n\nif `ssr` is false then rendering will be done at client side, like SPA app and dynamic routes will have only one file that will do client side rendering and data will be fetched at client side that way site will show latest data.\n\nCheck static-hosting\n\n========================================\n\nCode:\n```js\n// nuxt.config.ts\n\nimport { defineNuxtConfig } from 'nuxt3'\n\n// https://v3.nuxtjs.org/docs/directory-structure/nuxt.config\nexport default defineNuxtConfig({\n // Global page headers: https://go.nuxtjs.dev/config-head\n\n nitro: {\n preset: 'lambda'\n },\n\n head: {\n title: 'Title',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' }\n \n \n ],\n link: [\n { rel: 'icon', type: 'image/png', href: '/favicon.png' }\n ],\n script: [\n { \n type: 'text/javascript', \n src: '/mana.js',\n }\n]\n},\n})\n```\n\n```js\n// nuxt.config.js\n\nexport default {\n // Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode\n ssr: false,\n\n // Target: https://go.nuxtjs.dev/config-target\n target: 'static'\n}\n```\n\n```text\nindex.html\n```\n\n```js\nexport default defineNuxtConfig({\n target: 'static' // default is 'server'\n})\n```\n\n```json\n{\n \"scripts\": {\n \"build\": \"nuxi generate\"\n }\n}\n```\n\n```text\ntarget: 'static'\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nnuxi generate\n```\n\n```text\npackage.json\n```\n\n```text\nnuxi build\n```\n\n```text\nyarn generate\n```\n\n```text\n.output/public\n```\n\n```text\nssr: boolean\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nssr\n```\n\n```text\nssr\n```\n\n```text\ngenerate: {routes: ['/','all','my','other','routes']} ....\n```\n\n```text\n\"deploy\": \"touch .output/.nojekyll && gh-pages --dotfiles -d .output\"\n```\n\n```text\nnuxi generate\n```\n\n========================================\n\nComments:\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Concise but explicit answer ! At the time being the RFC is available here: github.com/nuxt/framework/discussions/560\n- becareful what you mention is about migration from nuxt2 to nuxt3 there is not only those things to do,so...\n- This is the nuxt 2 answer, but the question is regarding nuxt 3","metadata":{"transformedAt":"2026-08-18T18:33:07.847Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":215,"estimatedTokens":1033}}195{"id":"stack-61181593","source":"stackoverflow","questionId":61181593,"title":"Nuxt.js + vuetify image not loading","tags":["javascript","vue.js","webpack","vuetify.js","nuxt.js"],"text":"Title: Nuxt.js + vuetify image not loading\nTags: javascript, vue.js, webpack, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt.js + Vuetify, but the images are not able to load in my next page files. For example, in my `./pages/browse/index.vue`, I have a vuetify image tag like this:\n\n```\n\n```\n\nThe image is located at `assets/img/test.png`, however, whenever I started my Nuxt server, the image won't show up, below is the copied div element from Chrome dev tool: \n\n```\n\n```\n\nThe image only works if I do not use Vuetify image component like this:\n\n```\n\n```\n\n========================================\n\nTop Answer:\nAre you using Nuxt 2.0? If so, note the warning in their webpack section here: \n\n Warning: Starting from Nuxt 2.0 the ~/ alias won't be resolved\n correctly in your CSS files. You must use ~assets (without a slash) or\n the @ alias in url CSS references, i.e. background:\n url(\"~assets/banner.svg\")\n\n========================================\n\nCode:\n```text\n<v-img\n src=\"~/assets/img/test.png\"\n style=\"width:300px\"\n contain\n></v-img>\n```\n\n```text\n<div class=\"v-image__image v-image__image--contain\" style=\"background-image: url("http://localhost:3333/browse/~/assets/img/test.png"); background-position: center center;\"></div>\n```\n\n```text\n<img\n src=\"~/assets/img/test.png\"\n style=\"width:300px\"\n/>\n```\n\n```text\n./pages/browse/index.vue\n```\n\n```text\nassets/img/test.png\n```\n\n```text\n--static\n --img\n```\n\n```text\n<v-img src=\"img/test.png\"/>\n```\n\n```text\nstatic\n```\n\n```text\nassets\n```\n\n```text\nassets\n```\n\n```text\n<img />\n```\n\n```text\n<v-img />\n```\n\n```text\n<img />\n```\n\n```text\n<v-img />\n```\n\n```text\nsrc\n```\n\n```text\nstatic\n```\n\n```text\n<no-ssr>\n <v-img\n src=\"~/assets/img/test.png\"\n style=\"width:300px\"\n contain\n ></v-img>\n</no-ssr>\n```\n\n```text\n<v-img\n :src=\"require('@/assets/img/test.jpg')\"\n style=\"width:300px\"\n contain\n ></v-img>\n```\n\n```text\nv-img\n```\n\n```text\nno-ssr\n```\n\n```text\n<v-img :src=\"require('~/assets/images/background-1.jpg')\" />\n```\n\n========================================\n\nComments:\n- Thanks, I have tested it, It's actually\n- This works for me without the leading / so YMMV.","metadata":{"transformedAt":"2026-08-18T18:33:07.847Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":143,"estimatedTokens":542}}196{"id":"stack-54593785","source":"stackoverflow","questionId":54593785,"title":"How to redirect to home page after logout in nuxt?","tags":["vue-router","nuxt.js"],"text":"Title: How to redirect to home page after logout in nuxt?\nTags: vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nafter login in site i want when i click to specific button , user log out from site to home page.\n\nhere is my `template` code:\n\n```\n\n \n \n \n \n \n \n\n```\n\nand here is my `script` code:\n\n```\nexport default {\n name: 'HeadeAfterLogin',\n methods: {\n LogOut() {\n localStorage.removeItem('token')\n }\n }\n}\n```\n\nany one can help me to complete LogOut function ?\n\n========================================\n\nTop Answer:\nWhat I am doing is:\n\n**Component:**\n\n```\n### html \nLogOut\n\n### script\nexport default {\n methods: {\n signOut() {\n this.$auth.logout();\n }\n }\n}\n```\n\n**nuxt.config.js**\n\n```\nauth: {\n strategies: {\n ...\n },\n redirect: {\n login: '/login',\n logout: '/login', # after logout, user will be redirected here.\n home: '/'\n },\n}\n```\n\n========================================\n\nCode:\n```text\n<template>\n <nav id=\"header\" class=\"navbar navbar-expand header-setting\">\n <div class=\"main-content\">\n <div class=\"notification\" @click=\"LogOut()\"></div>\n </div>\n </div>\n </nav>\n</template>\n```\n\n```text\nexport default {\n name: 'HeadeAfterLogin',\n methods: {\n LogOut() {\n localStorage.removeItem('token')\n }\n }\n}\n```\n\n```text\ntemplate\n```\n\n```text\nscript\n```\n\n```text\nexport default {\n name: 'HeadeAfterLogin',\n methods: {\n LogOut() {\n localStorage.removeItem('token')\n this.$router.push('/')\n }\n }\n}\n```\n\n```text\nthis.$router\n```\n\n```text\n### html \n<a href=\"#\" class=\"dropdown-item\" @click.prevent=\"signOut\">LogOut</a>\n\n### script\nexport default {\n methods: {\n signOut() {\n this.$auth.logout();\n }\n }\n}\n```\n\n```text\nauth: {\n strategies: {\n ...\n },\n redirect: {\n login: '/login',\n logout: '/login', # after logout, user will be redirected here.\n home: '/'\n },\n}\n```\n\n========================================\n\nComments:\n- may wanna use this.$router.replace instead of push\n- @PirateApp Why?\n- @Čamo if the person hits back button on the browser they ll go back to the page where they were logged in, no?","metadata":{"transformedAt":"2026-08-18T18:33:07.847Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":153,"estimatedTokens":530}}197{"id":"stack-48265531","source":"stackoverflow","questionId":48265531,"title":"nuxt vue router afterEach guard","tags":["javascript","vue.js","nuxt.js"],"text":"Title: nuxt vue router afterEach guard\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHow can I set an afterEach handler that executes after route changes in nuxt? The middleware can be used as an beforeEach, but I could not find a way to implement the afterEach hook.\n\n========================================\n\nCode:\n```text\n// plugins/after-each.js:\nexport default async ({ app }) => {\n\n app.router.afterEach((to, from) => {\n // Do something\n });\n\n}\n```\n\n```text\nplugins: [ { src: '~/plugins/after-each.js', mode: 'client' } ]\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nmode\n```\n\n```text\nplugins\n```\n\n```text\nclient\n```\n\n```text\nserver\n```\n\n```text\nssr: false\n```\n\n```text\nmode: 'client'\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.847Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":52,"estimatedTokens":180}}198{"id":"stack-67865654","source":"stackoverflow","questionId":67865654,"title":"What is a proper way to create a type for Vue props","tags":["typescript","vue.js","nuxt.js","typescript-typings","vue-props"],"text":"Title: What is a proper way to create a type for Vue props\nTags: typescript, vue.js, nuxt.js, typescript-typings, vue-props\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a custom `type` for my prop in Vue js, I've created a types folder and added it in the `tsconfig.typeRoots` the IntelliSense and all the other things work correctly, no issues at compile time but when I visit that component, I get an error that `Car is not defined` but I have already defined it and it works at other places but after checking official documentation I got to know that prop expects a `constructor` so I redefined the type to `declare class Car` and added a constructor prototype but again the same issue.\n\nHere are the files:\n**car component**\n\n```\n\nimport Vue from \"vue\";\n\nexport default Vue.extend({\n name: \"the-car\",\n props: {\n car: {\n required: true,\n type: Car,\n },\n },\n});\n\n```\n\n**the `types/common/index.d.ts` declaration file**\n\n```\ndeclare class Car {\n name: String;\n image: String;\n kms: Number;\n gears: String;\n desc: String;\n fuel: String;\n engine: String;\n price: Number;\n constructor(name: String, image: String, kms: Number, gears: String, desc: String, fuel: String, engine: String, price: Number);\n}\n```\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\nimport Vue from \"vue\";\n\nexport default Vue.extend({\n name: \"the-car\",\n props: {\n car: {\n required: true,\n type: Car,\n },\n },\n});\n</script>\n```\n\n```text\ndeclare class Car {\n name: String;\n image: String;\n kms: Number;\n gears: String;\n desc: String;\n fuel: String;\n engine: String;\n price: Number;\n constructor(name: String, image: String, kms: Number, gears: String, desc: String, fuel: String, engine: String, price: Number);\n}\n```\n\n```text\ntype\n```\n\n```text\ntsconfig.typeRoots\n```\n\n```text\nCar is not defined\n```\n\n```text\nconstructor\n```\n\n```text\ndeclare class Car\n```\n\n```text\ntypes/common/index.d.ts\n```\n\n```js\nimport { PropType } from 'vue'\n\nprops: {\n car: {\n type: Object as PropType<Car>,\n required: true,\n },\n},\n```\n\n```text\ntype: Car\n```\n\n```text\ntype: Object as Car\n```\n\n```text\ntype: Object as () => Car\n```\n\n```text\nPropType\n```\n\n========================================\n\nComments:\n- Hi, I think you need to import the `index.d.ts` file in the component.\n- @YashMaheshwari I've already added an entry in the `tsconfig.json` and type checking works well without importing","metadata":{"transformedAt":"2026-08-18T18:33:07.847Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":131,"estimatedTokens":607}}199{"id":"stack-57537711","source":"stackoverflow","questionId":57537711,"title":"How to check my create-nuxt-app version and upgrade it?","tags":["vue.js","vuejs2","nuxt.js","create-nuxt-app"],"text":"Title: How to check my create-nuxt-app version and upgrade it?\nTags: vue.js, vuejs2, nuxt.js, create-nuxt-app\nSource: Stack Overflow\n\nQuestion:\n**Background:**\n\nPreviously, running yarn create nuxt-app myApp installs Nuxt v2.4.0 but today for example I noticed you downgraded to Nuxt v2.0.0. I did not change the development environment so I can not understand this behavior.\n\nI did some search and complained elsewhere when I landed on this:\n\nhttps://i.sstatic.net/rrflW.png\n\nSo the OP was asked to upgrade his create-nuxt-app version.\n\n**Question**:\n\nBut how to do that ? How to check which `create-nuxt-app` I do have ?\n\n**Bonus:**\n\nI read why does Create-Nuxt-App installs nuxt version 1.4.5? and the answer says you: \"Make sure you don't have a version of create-nuxt-app installed locally or globally.\" But how do you even install `create-nuxt-app` locally and globally ?\n\n**Info:**\n\nWhen I run `npm list -g | grep 'nuxt-app'` I do not get anything.\n\n========================================\n\nTop Answer:\nYou are fine. You don't need to do anything.\n\nIf you create a project with `create-nuxt-app` you get `\"nuxt\": \"^2.0.0\"` in your `package.json` which means that your project automatically uses the latest 2.x.x version of `nuxt`. Also if there'll be an update to `nuxt` your project with update itself.\n\nAnd to answer your two questions:\n\n- If you have `create-nuxt-app` installed in your project you can check its version using `npm list create-nuxt-app` (make sure you are in the project's directory). If it's installed globally you can check the version using `npm list create-nuxt-app -g`.\n\n- You can install `create-nuxt-app` locally using `npm install create-nuxt-app` and globally with `npm install -g create-nuxt-app`.\n\n========================================\n\nCode:\n```text\ncreate-nuxt-app\n```\n\n```text\ncreate-nuxt-app\n```\n\n```text\nnpm list -g | grep 'nuxt-app'\n```\n\n```text\ncreate-nuxt-app\n```\n\n```text\n\"nuxt\": \"^2.0.0\"\n```\n\n```text\npackage.json\n```\n\n```text\nnuxt\n```\n\n```text\nnuxt\n```\n\n```text\ncreate-nuxt-app\n```\n\n```text\nnpm list create-nuxt-app\n```\n\n```text\nnpm list create-nuxt-app -g\n```\n\n```text\ncreate-nuxt-app\n```\n\n```text\nnpm install create-nuxt-app\n```\n\n```text\nnpm install -g create-nuxt-app\n```\n\n```text\nnpm uninstall -g create-nuxt-app\n```\n\n```text\nnpm install -g create-nuxt-app\n```\n\n```text\nyarn why nuxt\n```\n\n========================================\n\nComments:\n- Try to invalidate your `npm` cache. Maybe this will help.\n- Also you don't need to install `create-nuxt-app` globally. It's just used with `npx`. Running `npx create-nuxt-app -v` I get `create-nuxt-app/2.9.2 darwin-x64 node-v10.16.2`. What result do you get after running that command?","metadata":{"transformedAt":"2026-08-18T18:33:07.847Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":116,"estimatedTokens":673}}200{"id":"stack-73293352","source":"stackoverflow","questionId":73293352,"title":"NUXT 3: How to use route middleware in a layout? (Can I?)","tags":["vue.js","nuxt.js","nuxt3.js"],"text":"Title: NUXT 3: How to use route middleware in a layout? (Can I?)\nTags: vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI've been looking to use Nuxt middleware in a layout. But I am not sure if I even can, however, since I used it in **Nuxt 2**, it may be possible in **Nuxt 3**.\n\nThe project has 2 different layouts: `Public.vue` and `Admin.vue`. I only want to use the middleware in pages that consume the **Admin layout**. Because the pages that use it should be accessed only by logged-in users, and it will be checked inside the middleware.\n\nI tried this (doesn't work):\n\nAdmin layout | Admin.vue\n\n```\n\n \n \n \n \n \n \n \n \n \n \n \n\nimport AdminHeader from \"~~/components/admin/Header.vue\"\nimport AdminFooter from \"~~/components/admin/Footer.vue\"\n\ndefinePageMeta({\n middleware: \"admin-auth\"\n});\n\n```\n\nMiddleware | adminAuth.ts\n\n```\nexport default defineNuxtRouteMiddleware((to, from) => {\n console.log(to);\n console.log(\"Acessando o admin auth middleware\");\n})\n```\n\n========================================\n\nTop Answer:\nIt is not possible to use middleware in layout because middleware only can be use in pages, but you can try to use this method.\n\nCreate a global middleware by declaring `.global` suffix after your middleware file name for example `auth.global.ts`.\n\nIn `auth.global.ts` file you can use layout meta as your logic to simulate as if the middleware is in your layout setup.\n\nSample logic is like this\n\n```\nexport default defineNuxtRouteMiddleware((to, from) => {\n const user = useUserStore();\n \n if (!user && to.meta.layout === auth) {\n return navigateTo(\"/login\");\n }\n});\n```\n\nHope this helps\n\n========================================\n\nCode:\n```html\n<template>\n <div>\n <client-only>\n <admin-header />\n </client-only>\n <main>\n <slot />\n </main>\n <client-only>\n <admin-footer />\n </client-only>\n </div>\n</template>\n\n<script lang=\"ts\">\nimport AdminHeader from \"~~/components/admin/Header.vue\"\nimport AdminFooter from \"~~/components/admin/Footer.vue\"\n\ndefinePageMeta({\n middleware: \"admin-auth\"\n});\n</script>\n```\n\n```js\nexport default defineNuxtRouteMiddleware((to, from) => {\n console.log(to);\n console.log(\"Acessando o admin auth middleware\");\n})\n```\n\n```text\nPublic.vue\n```\n\n```text\nAdmin.vue\n```\n\n```text\n<template>\n // you can add auth based components as well\n <NuxtPage />\n</template>\n\n<script setup lang=\"ts\">\n definePageMeta({\n middleware: \"admin-auth\"\n });\n</script>\n```\n\n```text\nNuxtPage\n```\n\n```text\n.global\n```\n\n```text\n/middleware/adminAuth.global.ts\n```\n\n```js\nexport default defineNuxtRouteMiddleware((to, from) => {\n const user = useUserStore();\n \n if (!user && to.meta.layout === auth) {\n return navigateTo(\"/login\");\n }\n});\n```\n\n```text\n.global\n```\n\n```text\nauth.global.ts\n```\n\n```text\nauth.global.ts\n```\n\n```text\nexport default defineNuxtRouteMiddleware((to) => {\n if (to.fullPath.includes('+')) to.fullPath = to.fullPath.replace(/\\+/g, '%20');\n});\n```\n\n```text\nrouter: {\n middleware: ['router'],\n},\n```\n\n```text\nrouter.global.ts\n```\n\n```text\n/src/middleware/router.global.ts\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n<script setup lang=\"ts\">\nimport { ref, nextTick } from \"vue\";\n\ndefinePageMeta({\n layout: \"lay1\",\n layoutTransition: {\n name: \"slide-left\",\n },\n});\n\nconst sw = () => {\n const route = useRoute();\n\n if (route.meta.layout === \"lay2\") {\n route.meta.layoutTransition = { name: \"slide-left\" };\n nextTick(() => {\n setPageLayout(\"lay1\");\n });\n } else {\n route.meta.layoutTransition = { name: \"slide-right\" };\n nextTick(() => {\n setPageLayout(\"lay2\");\n });\n }\n};\n</script>\n```\n\n```text\n{ name }\n```\n\n```text\nuseRoute()\n```\n\n```js\nexport default defineNuxtRouteMiddleware((to, from) => {\n\n if (process.client) {\n const user = UtilsUser.user //Get from localStorage.getItem('user')\n\n if (!user && to.meta.layout === 'profile') {\n //Prevent Loop:\n if (to.path !== '/auth/login') {\n return navigateTo('/auth/login', { external: true })\n }\n }\n }\n\n})\n```\n\n========================================\n\nComments:\n- Is your file in `middleware` directory? Maybe try to name it `admin-auth`, not sure if this may help. This seems to work pretty well: v3.nuxtjs.org/examples/routing/middleware But yeah, client side middleware is feasible.\n- Hm, I'm pretty sure that you can apply a middleware to a layout.\n- let me know how it is possible please\n- You are right. After some research, I found the same answer but forgot to write here. That's a shame...\n- how to call global middlewares?\n- `` is not used in Nuxt 3. See: nuxt.com/docs/migration/pages-and-layouts#migration-2\n- nested route solved my exact problem. thanks.\n- `to.meta.layout` is a string, so needs to be `=== 'auth'`","metadata":{"transformedAt":"2026-08-18T18:33:07.848Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":247,"estimatedTokens":1202}}201{"id":"stack-53963634","source":"stackoverflow","questionId":53963634,"title":"Nuxt loading bar not showing between routes","tags":["vue.js","vuetify.js","nuxt.js"],"text":"Title: Nuxt loading bar not showing between routes\nTags: vue.js, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nThe loading bar is enabled in nuxt.config.js as seen below, but it's not showing up between routes. I'm using Vuetify.\n\n```\n/*\n** Customize the progress-bar color\n*/\nloading: {\n color: '#333333'\n},\n```\n\nI'm using the following way to switch routes:\n\n```\nAdmin\n```\n\n========================================\n\nTop Answer:\nTry this:\n\n```\nloading: {\n color: 'blue',\n height: '5px',\n throttle: 0\n}\n```\n\nBut if you use \n\n Npx nuxt-create {app name}\n\nThen in nuxt.config on line 20, there is already a loading object remove that.\nGood luck.\n\n========================================\n\nCode:\n```text\n/*\n** Customize the progress-bar color\n*/\nloading: {\n color: '#333333'\n},\n```\n\n```text\n<nuxt-link to=\"/auth/admin\">Admin</nuxt-link>\n```\n\n```text\nloading: { color: '#333333', throttle: 0 },\n```\n\n```text\nloading: {\n color: 'blue',\n height: '5px',\n throttle: 0\n}\n```\n\n========================================\n\nComments:\n- any console errors?\n- Is this a new project? because if so then the progress bar doesn't have a chance to pop up because of it's throttle property which sets a delay before showing the bar and if the request is completed in less than 200ms (its default value) it then doesn't pop up.\n- if you use loading: { color: '#333333', duration: 3000 } does it show?\n- This also worked for me. It would be nice to know why this helps and if this is not a best practice then why.","metadata":{"transformedAt":"2026-08-18T18:33:07.848Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":77,"estimatedTokens":375}}202{"id":"stack-71372916","source":"stackoverflow","questionId":71372916,"title":"use onMounted Hook","tags":["vue.js","nuxt.js","vuejs3","server-side-rendering","nuxt3.js"],"text":"Title: use onMounted Hook\nTags: vue.js, nuxt.js, vuejs3, server-side-rendering, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm using nuxt3 with vue3 for my website.\nBut I have problem when using onMounted hook.\n\nhere is my vue page.\n\n```\n\n import { onMounted } from '@vue/runtime-core';\n\n onMounted(() => {\n console.log('myheader mounted');\n })\n\n \n\n### test\n\n```\n\nI get this errors:\n\n```\n[Vue warn]: onMounted is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.\n```\n\nIt makes me confused...... T.T\n\n========================================\n\nCode:\n```html\n<script setup lang=\"ts\">\n import { onMounted } from '@vue/runtime-core';\n\n onMounted(() => {\n console.log('myheader mounted');\n })\n</script>\n\n<template>\n <h1>test</h1>\n</template>\n```\n\n```text\n[Vue warn]: onMounted is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.\n```\n\n```html\n<script setup lang=\"ts\">\n // import { onMounted } from '@vue/runtime-core'; ❌\n import { onMounted } from 'vue'; ✅\n\n onMounted(() => {\n console.log('myheader mounted');\n })\n</script>\n```\n\n```html\n<script setup lang=\"ts\">\n // onMounted auto imported ✅\n\n onMounted(() => {\n console.log('myheader mounted');\n })\n</script>\n```\n\n```text\nvue\n```\n\n```text\n@vue/runtime-core\n```\n\n```text\nimport\n```\n\n```text\nonMounted\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.848Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":89,"estimatedTokens":417}}203{"id":"stack-58474763","source":"stackoverflow","questionId":58474763,"title":"Nuxt TypeScript error: nuxt:typescript Cannot find module '@/my-module'","tags":["typescript","vue.js","nuxt.js","tsconfig"],"text":"Title: Nuxt TypeScript error: nuxt:typescript Cannot find module '@/my-module'\nTags: typescript, vue.js, nuxt.js, tsconfig\nSource: Stack Overflow\n\nQuestion:\nI have setup Nuxt with TypeScript using the instructions from https://typescript.nuxt.org. The transition was pretty seamless and ok, except that I can't get rid of this error that `nuxt:typescript` \"Cannot find module\", which obviously is a false-positive.\n\nMy imports look like this:\n\n```\nimport InputField from '@/components/InputField.vue'\n```\n\nI have tried with `~/` and without the `.vue` extension. Nothing works.\n\nMy `tsconfig.json` looks like this:\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"esnext\",\n \"module\": \"esnext\",\n \"moduleResolution\": \"node\",\n \"lib\": [\"esnext\", \"esnext.asynciterable\", \"dom\"],\n \"esModuleInterop\": true,\n \"allowJs\": true,\n \"sourceMap\": true,\n \"strict\": true,\n \"noEmit\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"~/*\": [\"src/*\"],\n \"~*\": [\"src/*\"],\n \"@/*\": [\"src/*\"]\n },\n \"types\": [\"@types/node\", \"@nuxt/types\"]\n },\n \"exclude\": [\"node_modules\"]\n}\n```\n\nAnd I have this object in my `nuxt.config.js`:\n\n```\ntypescript: {\n typeCheck: {\n eslint: true,\n vue: true\n }\n}\n```\n\nhttps://i.sstatic.net/FCOb1.png\n\n========================================\n\nCode:\n```text\nimport InputField from '@/components/InputField.vue'\n```\n\n```text\n{\n \"compilerOptions\": {\n \"target\": \"esnext\",\n \"module\": \"esnext\",\n \"moduleResolution\": \"node\",\n \"lib\": [\"esnext\", \"esnext.asynciterable\", \"dom\"],\n \"esModuleInterop\": true,\n \"allowJs\": true,\n \"sourceMap\": true,\n \"strict\": true,\n \"noEmit\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"~/*\": [\"src/*\"],\n \"~*\": [\"src/*\"],\n \"@/*\": [\"src/*\"]\n },\n \"types\": [\"@types/node\", \"@nuxt/types\"]\n },\n \"exclude\": [\"node_modules\"]\n}\n```\n\n```text\ntypescript: {\n typeCheck: {\n eslint: true,\n vue: true\n }\n}\n```\n\n```text\nnuxt:typescript\n```\n\n```text\n~/\n```\n\n```text\n.vue\n```\n\n```text\ntsconfig.json\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ndeclare module '*.vue' {\n import Vue from 'vue';\n export default Vue\n}\n```\n\n```text\n{\n \"compilerOptions\": {\n ...\n \"baseUrl\": \".\",\n \"paths\": {\n \"~/*\": [\"./*\"],\n \"@/*\": [\"./*\"]\n }\n }\n}\n```\n\n```text\nimport SomeComponent from '~/components/SomeComponent.vue'\n```\n\n```text\nts-shim.d.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\n.vue\n```\n\n```text\n.ts\n```\n\n========================================\n\nComments:\n- Try to change to \"@/*\": [\"./src/*\"]\n- @Aldarund sadly, that didn't help.\n- create a minimal reproduction on github please\n- There's a fix here, but it only covers `.vue` files, and not `.ts` file imports: github.com/nuxt/typescript/issues/153\n- ye, thats right, didnt know u dont have it :)\n- \"It is now absolutely mandatory to include .vue \" helped me thanks","metadata":{"transformedAt":"2026-08-18T18:33:07.848Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":163,"estimatedTokens":692}}204{"id":"stack-72419491","source":"stackoverflow","questionId":72419491,"title":"Nested useFetch in Nuxt 3","tags":["vue.js","nuxt.js","vuejs3","vue-composition-api","nuxt3.js"],"text":"Title: Nested useFetch in Nuxt 3\nTags: vue.js, nuxt.js, vuejs3, vue-composition-api, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nHow do you accomplish nested fetching in Nuxt 3?\nI have two API's. The second API has to be triggered based on a value returned in the first API.\n\nI tried the code snippet below, but it does not work, since `page.Id` is `null` at the time it is called. And I know that the first API return valid data. So I guess the second API is triggered before the result is back from the first API.\n\n```\n\n const route = useRoute()\n const { data: page } = await useFetch(`/api/page/${route.params.slug}`)\n const { data: paragraphs } = await useFetch(`/api/page/${page.Id}/paragraphs`)\n\n```\n\nObviously this is a simple attempt, since there is no check if the first API actually return any data. And it is not even waiting for a response.\n\nIn Nuxt2 I would have placed the second API call inside `.then()` but with this new Composition API setup i'm a bit clueless.\n\n========================================\n\nTop Answer:\nYou can set your 2nd `useFetch` to not immediately execute until the first one has value:\n\n```\n\n const route = useRoute()\n const { data: page } = await useFetch(`/api/page/${route.params.slug}`)\n const { data: paragraphs } = await useFetch(`/api/page/${page.value?.Id}/paragraphs`, {\n // prevent the request from firing immediately\n immediate: false,\n // watch reactive sources to auto-refresh\n watch: [page]\n })\n\n```\n\nYou can also omit the `watch` option there and manually `execute` the 2nd `useFetch`.\nBut for it to be reactive, pass a function that returns a URL instead:\n\n```\nconst { data: page } = await useFetch(`/api/page/${route.params.slug}`)\nconst { data: paragraphs, execute } = await useFetch(() => `/api/page/${page.value?.Id}/paragraphs`, {\n immediate: false,\n})\n\nwatch(page, (val) => {\n if (val.Id === 69) {\n execute()\n }\n})\n```\n\nYou should never invoke composables inside lifecycle hooks.\n\nMore `useFetch` options can be found here.\n\n========================================\n\nCode:\n```html\n<script setup>\n const route = useRoute()\n const { data: page } = await useFetch(`/api/page/${route.params.slug}`)\n const { data: paragraphs } = await useFetch(`/api/page/${page.Id}/paragraphs`)\n</script>\n```\n\n```text\npage.Id\n```\n\n```text\nnull\n```\n\n```text\n.then()\n```\n\n```html\n<script setup>\nconst paragraphs = ref()\n\nconst route = useRoute()\n\nconst { data: page } = await useFetch(`/api/page/${route.params.slug}`)\n\n\nwatch(page, (newPage)=>{\n if (newPage.Id) {\n\n useFetch(`/api/page/${newPage.Id}/paragraphs`).then((response)=>{\n paragraphs.value = response.data\n\n })\n \n }\n}, {\n deep: true,\n immediate:true\n})\n</script>\n```\n\n```text\npage\n```\n\n```text\nparagraphs\n```\n\n```text\nref\n```\n\n```html\n<script setup>\n const route = useRoute()\n const page = ref()\n const paragraphs = ref()\n useFetch(`/api/page/${route.params.slug}`).then(it=> {\n page.value = it\n useFetch(`/api/page/${page.value.Id}/paragraphs`).then(it2=> {\n paragraphs.value = it2\n }\n }\n</script>\n```\n\n```text\nawait\n```\n\n```html\n<script setup>\n const route = useRoute()\n const { data: page } = await useFetch(`/api/page/${route.params.slug}`)\n const { data: paragraphs } = await useFetch(`/api/page/${page.value?.Id}/paragraphs`, {\n // prevent the request from firing immediately\n immediate: false,\n // watch reactive sources to auto-refresh\n watch: [page]\n })\n</script>\n```\n\n```js\nconst { data: page } = await useFetch(`/api/page/${route.params.slug}`)\nconst { data: paragraphs, execute } = await useFetch(() => `/api/page/${page.value?.Id}/paragraphs`, {\n immediate: false,\n})\n\nwatch(page, (val) => {\n if (val.Id === 69) {\n execute()\n }\n})\n```\n\n```text\nuseFetch\n```\n\n```text\nwatch\n```\n\n```text\nexecute\n```\n\n```text\nuseFetch\n```\n\n```text\nuseFetch\n```\n\n========================================\n\nComments:\n- can you show us the serverside code?\n- @Ifaruki The server side code is not the issue here. The API return data. Lets just assume that both API calls are successful.\n- What version of Nuxt are you using? RC1 or 3? Try the other one.\n- At the moment I use `npm:nuxt3@latest` and that is `3.0.0-rc.3-27578655.a802b87`\n- This is a valid option but I think you lose access to things like `pending` and `refresh`, which are both pretty handy?\n- what is deep and immediate attributes ?\n- `deep` means to watch the nested properties of an object or an array, `immediate` to trigger the watcher at the first rendering\n- and if there is an error how to process it ? because i have a big page error 500 :/\n- I think this should be the answer, it's more vue3-ish.\n- Your second answer resolve my problem with chained queries, thank you","metadata":{"transformedAt":"2026-08-18T18:33:07.848Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":197,"estimatedTokens":1180}}205{"id":"stack-52874435","source":"stackoverflow","questionId":52874435,"title":"How to watch on Route changes with Nuxt and asyncData","tags":["vue.js","vue-router","nuxt.js"],"text":"Title: How to watch on Route changes with Nuxt and asyncData\nTags: vue.js, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHi everybody i'm trying to watch on route changes in my nuxt js app.\n\nHere my middleware: \n\n```\nexport default function ({ route }) {\n return route; but i don't know what to write here\n}\n```\n\nindex.vue File\n\n```\nmiddleware: [routeReact]\n```\n\ni'm trying to write this: \n\n```\napp.context.route = route\n```\n\nbut it says to me that app.context doesn't exist\n\nHere's the point of my question i'm trying to update my data that gets from my api with axios on page if route changing\nlike this \n\nthis the page\nhttps://i.sstatic.net/myyBS.jpg\n\ni'm clicking link to next page :\n\nhttps://i.sstatic.net/5B7hk.jpg\n\nbut when i'm route to next page, nothing happens all data is the same: \n\nhttps://i.sstatic.net/FGOW4.jpg\n\nhere my asyncData code: \n\n```\nasyncData({ app }) {\nreturn app.$axios.$get('apps/' + app.context.route.fullPath.replace(/\\/categories\\/?/, ''))\n.then(res => {\n return {\n info: res.results,\n nextPage: res.next,\n prevPage: res.prev\n };\n })\n```\n\n}\n\nThanks for your help\n\n========================================\n\nTop Answer:\nFor Composition API (Nuxt 3 or Nuxt 2 Bridge) you can use the `watch` option on `useAsyncData` / `useLazyAsyncData` / etc.\n\n```\nconst route = useRoute()\nconst { data: posts } = await useAsyncData(\n 'posts',\n () => {},\n {\n watch: [route]\n }\n)\n```\n\nIn my case, on Nuxt 2 Bridge, this resulted in an infinite loop (`RangeError: Maximum call stack size exceeded`) and solved it with a workaround:\n\n```\nconst fetchSomething = () => {}\n\n// This is a hack because `watch(route)` results in an infinite loop\nconst watchFlag = ref(true)\nonMounted(() => {\n watchFlag.value = false\n})\n\nuseLazyAsyncData('', () => {\n return fetchSomething()\n})\n\nwatch(watchFlag, async () => {\n await fetchSomething()\n})\n```\n\n========================================\n\nCode:\n```text\nexport default function ({ route }) {\n return route; but i don't know what to write here\n}\n```\n\n```text\nmiddleware: [routeReact]\n```\n\n```text\napp.context.route = route\n```\n\n```text\nasyncData({ app }) {\nreturn app.$axios.$get('apps/' + app.context.route.fullPath.replace(/\\/categories\\/?/, ''))\n.then(res => {\n return {\n info: res.results,\n nextPage: res.next,\n prevPage: res.prev\n };\n })\n```\n\n```text\n<nuxt-link :to=\"{ name: 'index', query: { start: 420 }}\"\n```\n\n```text\nwatchQuery: true,\n\nasyncData ({ query, app }) {\n const { start } = query\n const queryString = start ? `?start=${start}` : ''\n return app.$axios.$get(`apps/${queryString}`)\n .then(res => {\n return {\n info: res.results,\n nextPage: res.next,\n prevPage: res.prev\n }\n })\n},\n```\n\n```text\n<nuxt :key=\"$route.fullPath\" />\n```\n\n```text\ncontext.route\n```\n\n```text\nthis.$route\n```\n\n```text\nthis.$router\n```\n\n```text\n<nuxt-link>\n```\n\n```text\n<router-link>\n```\n\n```text\nasyncData\n```\n\n```text\nasyncData\n```\n\n```text\nmiddleware\n```\n\n```text\nkey\n```\n\n```text\nkey\n```\n\n```text\nnuxt\n```\n\n```js\nconst route = useRoute()\nconst { data: posts } = await useAsyncData(\n 'posts',\n () => {},\n {\n watch: [route]\n }\n)\n```\n\n```js\nconst fetchSomething = () => {}\n\n// This is a hack because `watch(route)` results in an infinite loop\nconst watchFlag = ref(true)\nonMounted(() => {\n watchFlag.value = false\n})\n\nuseLazyAsyncData('', () => {\n return fetchSomething()\n})\n\nwatch(watchFlag, async () => {\n await fetchSomething()\n})\n```\n\n```text\nwatch\n```\n\n```text\nuseAsyncData\n```\n\n```text\nuseLazyAsyncData\n```\n\n```text\nRangeError: Maximum call stack size exceeded\n```\n\n========================================\n\nComments:\n- upvoted! what is this queryString? does it work on both server and client\n- @PirateApp thanks! \"queryString\" in the example is a valid URL query parameter and totally depends on your application. Since route navigation occurs on the loaded page, it is reasonable to say that this functionality is relevant on the client side only. All the component lifecycle hooks will be executed if current route stays the same, but query params change (which is not happening with `watchQuery: false`)","metadata":{"transformedAt":"2026-08-18T18:33:07.848Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":245,"estimatedTokens":1030}}206{"id":"stack-72052807","source":"stackoverflow","questionId":72052807,"title":"How to use any icons with Nuxt or Vue?","tags":["javascript","vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: How to use any icons with Nuxt or Vue?\nTags: javascript, vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm facing an error with Nuxtjs when I try to use the vue-fontawesome framework and also the @nuxtjs/fontawesome framework, this is the error:\n\n```\n[nuxt] [request error] Cannot read properties of undefined (reading 'component')\n at $id_c50a96b3 (./.nuxt/dist/server/server.mjs:3239:31)\n at async __instantiateModule__ (./.nuxt/dist/server/server.mjs:19193:3)\n```\n\nthis is my code in `nuxt.config.ts`:\n\n```\nimport { defineNuxtConfig } from 'nuxt'\n\nexport default defineNuxtConfig({\n modules: [\n '@nuxtjs/fontawesome'\n ],\n\n fontawesome: {\n icons: {\n solid: ['faXmark']\n }\n }\n})\n```\n\nAnd this is the component where I want to use the icon:\n\n```\n\n \n \n \n \n\n```\n\nBy the way, the error just appear when I try to load the page, not when I run it.\n\n========================================\n\nTop Answer:\nYou can also use the rather new package nuxt-icon which is made by the CEO of NuxtLabs and used in the nuxt3/content2 starter template content-wind.\n\n**Instalation**\n\n```\nnpm install --save-dev nuxt-icon\n\nyarn add --dev nuxt-icon\n```\n\n**Setting up Nuxt 3**\n\nnuxt.config.ts\n\n```\nexport default defineNuxtConfig({\n modules: ['nuxt-icon']\n})\n```\n\n**Usage**\n\nJust copy and paste name of icon you want from icones.js.org. Package will fetch icon and paste to your code. You have 100k+ icons to pick.\n\n```\n\n```\n\n========================================\n\nCode:\n```text\n[nuxt] [request error] Cannot read properties of undefined (reading 'component')\n at $id_c50a96b3 (./.nuxt/dist/server/server.mjs:3239:31)\n at async __instantiateModule__ (./.nuxt/dist/server/server.mjs:19193:3)\n```\n\n```text\nimport { defineNuxtConfig } from 'nuxt'\n\nexport default defineNuxtConfig({\n modules: [\n '@nuxtjs/fontawesome'\n ],\n\n fontawesome: {\n icons: {\n solid: ['faXmark']\n }\n }\n})\n```\n\n```html\n<template>\n <div :class=\"props.className\">\n <font-awesome-icon icon=\"xmark\" />\n <slot />\n </div>\n</template>\n```\n\n```text\nnuxt.config.ts\n```\n\n```js\n// @ts-nocheck\nimport { defineNuxtConfig } from 'nuxt'\nimport Icons from 'unplugin-icons/vite'\n\nexport default defineNuxtConfig({\n vite: {\n plugins: [\n Icons({\n // the feature below is experimental ⬇️\n autoInstall: true\n })\n ]\n }\n})\n```\n\n```html\n<script setup>\nimport IconXmark from `~icons/fa6-solid/xmark`\n</script>\n\n<template>\n <icon-xmark style=\"font-size: 2em; color: blue\" />\n</template>\n```\n\n```html\n<script setup>\nimport IconXmark from '~icons/fa6-solid/xmark'\nimport IconAccountBox from '~icons/mdi/account-box'\nimport TastyPizza from '~icons/noto-v1/pizza'\nimport IconPs from '~icons/ri/playstation-line'\n</script>\n\n<template>\n <icon-xmark style=\"font-size: 2em; color: blue\" />\n <icon-account-box style=\"font-size: 2em; color: red\" />\n <tasty-pizza style=\"font-size: 2em\" />\n <icon-ps style=\"font-size: 2em\" />\n</template>\n```\n\n```text\npnpm dlx nuxi init nuxt3-unplugin-icons\n```\n\n```text\npnpm i --shamefully-hoist\n```\n\n```text\npnpm add -D unplugin-icons\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n[collection-id]:[name]\n```\n\n```text\nfa6-solid:xmark\n```\n\n```text\n.vue\n```\n\n```text\nfa6-solid:xmark\n```\n\n```text\n~icons/fa6-solid/xmark\n```\n\n```text\nautoInstall\n```\n\n```text\n@iconify-json/[your collection id]\n```\n\n```text\n@iconify-json/fa6-solid\n```\n\n```text\nnpm install --save-dev nuxt-icon\n\nyarn add --dev nuxt-icon\n```\n\n```js\nexport default defineNuxtConfig({\n modules: ['nuxt-icon']\n})\n```\n\n```html\n<Icon name=\"logos:google-icon\"></Icon>\n<Icon name=\"logos:facebook\"></Icon>\n<Icon name=\"logos:apple\" fill=\"#97a3b6\"></Icon>\n```\n\n```text\nyarn add vite-svg-loader --dev\n```\n\n```text\nimport svgLoader from 'vite-svg-loader'\n\nexport default defineNuxtConfig({\n vite: {\n plugins: [\n svgLoader({})\n ]\n }\n})\n```\n\n```text\n<template>\n <component :is=\"icon\" />\n</template>\n\n<script>\n const props = defineProps<{ name: string }>()\n const icon = computed(() => \n defineAsyncComponent(() => import(`../assets/icons/${props.name}.svg`))\n )\n</script>\n```\n\n```text\n<template>\n <icon-loader name=\"calendar\" /> // assuming there is a calendar.svg file in your assets folder.\n</template>\n```\n\n========================================\n\nComments:\n- It looks like the error is not coming from what you've shared. Isn't there a `.component` somewhere in your code? The left part looks to be undefined sometimes.\n- No, theres no other file that I created that have some line with that, but actually the rest of the error show this: `at $id_c50a96b3 (./.nuxt/dist/server/server.mjs:3239:31) at async __instantiateModule__ (./.nuxt/dist/server/server.mjs:19193:3)`\n- Oh, so you're using Nuxt3. Not sure if this module is compatible with it.\n- Since last commit was 15months ago, we can be sadly confident it's not compatible with Nuxt 3. You'll have to find another way to install your fontawesome library with a plugin / module of your own!\n- Could you edit your answer with some instructions on how does it work exactly? Usually, a few hyperlinks are not enough for an answer.\n- While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review\n- This is how you should write an answer. I edited the answer because it is the best library for icons right now.\n- @Mises haha, you could have posted your own answer at this point.\n- @kissu No make sense repeating answer. XD I'm not greedy like you. XD\n- @Mises if you're adding a substantial amount of explanation that could be deserving it's own answer, I don't feel like it's being greedy. But you do as you'd like for sure.\n- @kissu I'm just messing with you","metadata":{"transformedAt":"2026-08-18T18:33:07.848Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":271,"estimatedTokens":1454}}207{"id":"stack-60303086","source":"stackoverflow","questionId":60303086,"title":"merge 2 values and put in a v-data-table column (Vuetify)","tags":["javascript","vue.js","datatable","vuetify.js","nuxt.js"],"text":"Title: merge 2 values and put in a v-data-table column (Vuetify)\nTags: javascript, vue.js, datatable, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to merge to values and put into one column in v-data-table?\n\n***List.vue***\n\n```\n\n \n \n \n\nexport default {\n data() {\n return {\n items: [\n { first_name: \"Peter\", last_name: \"Johnson\" },\n { first_name: \"Simon\", last_name: \"Walker\" }\n ],\n headers: [\n { text: \"first_name\", value: \"first_name\" },\n { text: \"last_name\", value: \"last_name\" },\n ]\n };\n }\n};\n\n```\n\nFor example I want to put `Peter Johnson` in `Full name` column of my v-data-table, While it doesn't have `Full name` column.\n\n========================================\n\nTop Answer:\nOn Pierre Said's answer,\n'v-slot' directive doesn't support any modifier. (eslint-plugin-vue)\n\n```\n\n {{ item.first_name }} {{ item.last_name }}\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <v-app>\n <v-data-table\n :items=\"items\"\n :headers=\"headers\"\n />\n </v-app>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n items: [\n { first_name: \"Peter\", last_name: \"Johnson\" },\n { first_name: \"Simon\", last_name: \"Walker\" }\n ],\n headers: [\n { text: \"first_name\", value: \"first_name\" },\n { text: \"last_name\", value: \"last_name\" },\n ]\n };\n }\n};\n</script>\n```\n\n```text\nPeter Johnson\n```\n\n```text\nFull name\n```\n\n```text\nFull name\n```\n\n```html\n<v-data-table :headers=\"headers\" :items=\"items\">\n <template #item.full_name=\"{ item }\">{{ item.first_name }} {{ item.last_name }}</template>\n</v-data-table>\n```\n\n```js\nexport default {\n data() {\n return {\n items: [\n { first_name: \"Peter\", last_name: \"Johnson\" },\n { first_name: \"Simon\", last_name: \"Walker\" }\n ],\n headers: [{ text: \"Full Name\", value: \"full_name\" }]\n };\n }\n};\n```\n\n```text\nv-data-table\n```\n\n```text\nfull_name\n```\n\n```text\n<v-data-table :headers=\"headers\" :items=\"items\">\n <template v-slot:[`item.full_name`]=\"{ item }\">{{ item.first_name }} {{ item.last_name }}</template>\n</v-data-table>\n```\n\n========================================\n\nComments:\n- If you're getting an ES lint error with the above you might want to try it in this format: ``\n- Very bad approach, be carefull guys because filtering will no longer works when you do this\n- `#item.full_name` not works for me. I use `v-slot:item.full_name`\n- May be `first_name` and `last_name` column are also shown in the table.","metadata":{"transformedAt":"2026-08-18T18:33:07.848Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":130,"estimatedTokens":626}}208{"id":"stack-43746782","source":"stackoverflow","questionId":43746782,"title":"Running nuxt js application in Docker","tags":["javascript","docker","vue.js","nuxt.js"],"text":"Title: Running nuxt js application in Docker\nTags: javascript, docker, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to run nuxt application in docker container. In order to do so, I created the following Dockerfile:\n\n```\nFROM node:6.10.2\n\nRUN mkdir -p /app\n\nEXPOSE 3000\n\nCOPY . /app\nWORKDIR /app\nRUN npm install\nRUN npm run build\n\nCMD [ \"npm\", \"start\" ]\n```\n\nHowever, when I build the image and run the container (`docker run -p 3000:3000 `) I get nothing while hitting `localhost:3000` in my browser. What could be the cause?\n\n========================================\n\nCode:\n```text\nFROM node:6.10.2\n\nRUN mkdir -p /app\n\nEXPOSE 3000\n\nCOPY . /app\nWORKDIR /app\nRUN npm install\nRUN npm run build\n\nCMD [ \"npm\", \"start\" ]\n```\n\n```text\ndocker run -p 3000:3000 <image-id>\n```\n\n```text\nlocalhost:3000\n```\n\n```text\nFROM node:6.10.2\n\nENV HOST 0.0.0.0\n\n# rest of the file\n```\n\n```text\nhttp://127.0.0.1:3000\n```\n\n```text\n0.0.0.0\n```\n\n```text\n\"scripts\": { \"start\": \"HOST=0.0.0.0 nuxt start\" ...}\n```\n\n========================================\n\nComments:\n- Visitors from the future, can take a look at this cookbook recipe for dockerizing your vue app\n- Absolutely right, I didn't find your answer since I googled wrong - but had the same problem. It's also in the nuxt FAQ docs. Setting `HOST=0.0.0.0` is key.\n- Using Paketo.io / Cloud Native Buildpacks would free you from the need to write your own `Dockerfile` - then you need to pass the `HOST=0.0.0.0` as `--env` variable to the `docker run` command (see this answer).","metadata":{"transformedAt":"2026-08-18T18:33:07.848Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":76,"estimatedTokens":382}}209{"id":"stack-56830238","source":"stackoverflow","questionId":56830238,"title":"How to add a link to download a pdf file nuxt?","tags":["pdf","vue.js","nuxt.js"],"text":"Title: How to add a link to download a pdf file nuxt?\nTags: pdf, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI just wants to add a link to download a pdf file in nuxt project. \n\n### How do I do that?\n\nI have tried the following:\n\n```\nDownload\n```\n\nwhich works well for images but not for pdf files. I found `vue-pdf` but I feel its an extra work for the purpose of just linking a pdf file. I have no work view a pdf files with all those events.\n\n========================================\n\nTop Answer:\nThis works:\n\n```\nDownload my CV\n```\n\nif you put the PDF in the static folder. You don't need the /static/ as NUXT does the magic.\n\n========================================\n\nCode:\n```text\n<a :href=\"require('@/static/documents/WTSDL2019_Pamplet.pdf')\" download class=\"btn btn-sm btn-sub-color\" >Download</a>\n```\n\n```text\nvue-pdf\n```\n\n```text\n<a href=\"/WTSDL2019_Pamplet.pdf\" download=\"\">Download</a>\n```\n\n```text\npublic\n```\n\n```text\nstatic\n```\n\n```text\n<a :href=\"require('../assets/documents/WTSDL2019_Pamplet.pdf')\" download>\nDownload\n</a>\n```\n\n```text\n<a href=\"/cv.pdf\">Download my CV</a>\n```\n\n```text\n<a href=\"../../1111.pdf\" download=\"\" target=\"_blank\" >Download</a>\n```\n\n========================================\n\nComments:\n- If it works for images but not for pdfs, what is the error with the pdf?\n- Did you try to directly link to static folder like: ``?\n- pdf download try this\n- Please add some explanation to your answer such that others can learn from it. For example, why are there multiple backticks in that `a` tag?\n- Don't know why the downvote, people should read the answer and understand it, it doesn't need much explanation. PS: add a slash to the href=\"/WTSDL2019_Pamplet.pdf\"\n- Notice that in Nuxt 3, static files should rather be in the public/ folder.\n- Code only answers can almost always be improved by adding some explanation of how and why they work.\n- it's nothing major to explain, he just needs to replace the `@` with `../` but i don't recommend this method since it will actually load the file to the compiler when you run npm run dev and make your project slow, i uploaded my files to the server and just used the link from my storage server\n- This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review","metadata":{"transformedAt":"2026-08-18T18:33:07.848Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":77,"estimatedTokens":600}}210{"id":"stack-59885664","source":"stackoverflow","questionId":59885664,"title":"Nuxt: how to prevent nuxt-link goes to another page?","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Nuxt: how to prevent nuxt-link goes to another page?\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI need to stop `nuxt-link` going to another page.\n\nThis is my code\n\n```\n\nmethods: {\n toggleSubMenuIcon(index) {\n this.$store.dispatch('layout/TOGGLE_SUBMENU_ICON', index)\n }\n }\n```\n\nI need a similar e.preventDefault() to block browser to visit the page at item.url\n\nI has tried also\n\n```\n event.preventDefault()\">\n```\n\nwithout success.\n\nI would not use a simple \"hash\" into the url 'cause I don't like it printed in the URL browser.\n\nThank you\n\n========================================\n\nTop Answer:\n```\n\n {{ album.albumName }}\n\n```\n\n========================================\n\nCode:\n```text\n<nuxt-link :to=\"item.url\" data-toggle=\"collapse\" class=\"nav-link\" v-b-toggle=\"'collapse-'+index\" :ref=\"'parent-'+index\" @click.native=\"toggleSubMenuIcon(index)\">\n\n\nmethods: {\n toggleSubMenuIcon(index) {\n this.$store.dispatch('layout/TOGGLE_SUBMENU_ICON', index)\n }\n }\n```\n\n```text\n<nuxt-link :to=\"item.url\" data-toggle=\"collapse\" class=\"nav-link\" v-b-toggle=\"'collapse-'+index\" :ref=\"'parent-'+index\" @click.native=\"toggleSubMenuIcon(index), event => event.preventDefault()\">\n```\n\n```text\nnuxt-link\n```\n\n```text\n<nuxt-link event=\"\" :to=\"item.url\" data-toggle=\"collapse\" class=\"nav-link\" v-b-toggle=\"'collapse-'+index\" :ref=\"'parent-'+index\" @click.native=\"toggleSubMenuIcon(index), event => event.preventDefault()\">\n```\n\n```text\nevent=\"\"\n```\n\n```text\n<nuxtLink :to=\"album?.route\" @click.stop.prevent class=\"album-name\">\n {{ album.albumName }}\n</nuxtLink>\n```\n\n========================================\n\nComments:\n- Please see stackoverflow.com/a/74561723/19901666 and adapt to it by your needs.\n- whats the point of having Nuxt-Link when disabling it's main purpose?\n- this is so strange. i had a **NuxtLink** that was working perfectly when defined like so: `link`. however, somewhere along the way, the event capturing stopped working and now only works after i've updated it to:` event.preventDefault()\">link`... i don't understand why, but thanks for the tip!\n- This works for me. I wanted a link that was \"alive\" in all other ways other than allowing the click event, so that someone could open it via right-click, for example. FYI this is a Vue Router thing, and it works with Vue Router 3 (Vue2/Nuxt2). When upgrading to Vue3/Nuxt3 and Vue Router 4, you'll have to use a different way; see docs here: router.vuejs.org/guide/migration/…\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:07.848Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":85,"estimatedTokens":691}}211{"id":"stack-54346345","source":"stackoverflow","questionId":54346345,"title":"Nuxt.js - force trailing slash at the end of all urls","tags":["vue.js","nuxt.js"],"text":"Title: Nuxt.js - force trailing slash at the end of all urls\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm looking for a way to make sure that all of my urls end with a trailing slash (so first check if there is already a trailing slash at the end, and if not add one).\n\nI have tried with nuxt-redirect-module, and it works adding the slash but then it leads to an infinite redirect\n\n```\nredirect: [\n {\n from: '^(.*)$',\n to: (from, req) => {\n let trailingUrl = req.url.endsWith('/') ? req.url : req.url + '/'\n return trailingUrl\n }\n }\n]\n```\n\nAny insight will be welcome. Thanks!\n\n========================================\n\nTop Answer:\nThe following regex handles query string as well:\n\n```\nredirect: [\n {\n from: '^(\\\\/[^\\\\?]*[^\\\\/])(\\\\?.*)?$',\n to: '$1/$2',\n },\n],\n```\n\n========================================\n\nCode:\n```text\nredirect: [\n {\n from: '^(.*)$',\n to: (from, req) => {\n let trailingUrl = req.url.endsWith('/') ? req.url : req.url + '/'\n return trailingUrl\n }\n }\n]\n```\n\n```text\nredirect: [\n {\n from: '^.*(?<!\\/)$',\n to: (from, req) => req.url + '/'\n }\n]\n```\n\n```js\nredirect: [\n {\n from: '^(\\\\/[^\\\\?]*[^\\\\/])(\\\\?.*)?$',\n to: '$1/$2',\n },\n],\n```\n\n```text\nrouter: {\n prefetchLinks: false,\n middleware: 'navigation',\n routeNameSplitter: '/',\n extendRoutes(routes, resolve) {\n routes.push(\n {\n name: 'kaufen',\n path: '/kaufen//',\n component: resolve(__dirname, 'pages/listing/index.vue'),\n },\n {\n name: 'mieten',\n path: '/mieten//',\n component: resolve(__dirname, 'pages/listing/index.vue'),\n },\n```\n\n```text\nhttps://example.com/kaufen/?alternate=true&ignoreToplisting=false\n```\n\n========================================\n\nComments:\n- That's exactly what I needed. Thanks!\n- How can I \"not match\" routes that end with filenames, such as .jpg, etc.?\n- @Manas You can specify the non-matching file extensions in the negative lookbehind part of regex, e.g: `^.*(?<!\\.(png|jpg))$`\n- I have set up a bounty to a question related with this. You can check it out at stackoverflow.com/questions/54346345/…","metadata":{"transformedAt":"2026-08-18T18:33:07.848Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":100,"estimatedTokens":546}}212{"id":"stack-53659450","source":"stackoverflow","questionId":53659450,"title":"Props should at least define their types","tags":["vue.js","vue-component","eslint","nuxt.js","storyblok"],"text":"Title: Props should at least define their types\nTags: vue.js, vue-component, eslint, nuxt.js, storyblok\nSource: Stack Overflow\n\nQuestion:\n```\n\n \n \n \n\nexport default {\n props: ['blok']\n}\n\n```\n\nIm doing tutorial at Storyblok, and I do get such an error.\n\nhttps://www.storyblok.com/tp/nuxt-js-multilanguage-website-tutorial#creating-the-homepage-components\n\n Props should at least define their types vue/require-prop-types\n\n========================================\n\nTop Answer:\nFor current `nuxt` version(v2.8.1), we should set **props** as follows:\n\n```\n\nexport default {\n props: {\n blok: {\n type: Object,\n default: null\n }\n }\n}\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div \n v-editable=\"blok\" \n class=\"util__flex\">\n <component \n v-for=\"blok in blok.columns\" \n :key=\"blok._uid\" \n :blok=\"blok\" \n :is=\"blok.component\"/>\n </div>\n</template>\n\n<script>\nexport default {\n props: ['blok']\n}\n</script>\n```\n\n```text\n<script>\nexport default {\n props: {\n blok: Object\n }\n}\n</script>\n```\n\n```text\ncreate-nuxt-app\n```\n\n```text\n<script>\nexport default {\n props: {\n blok: {\n type: Object,\n default: null\n }\n }\n}\n</script>\n```\n\n```text\nnuxt\n```\n\n========================================\n\nComments:\n- See prop types and prop validation.","metadata":{"transformedAt":"2026-08-18T18:33:07.848Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":99,"estimatedTokens":327}}213{"id":"stack-74559363","source":"stackoverflow","questionId":74559363,"title":"How to use nuxtjs/auth-next module with Nuxt3?","tags":["vue.js","authentication","nuxt.js","nuxt3.js","nuxt-module"],"text":"Title: How to use nuxtjs/auth-next module with Nuxt3?\nTags: vue.js, authentication, nuxt.js, nuxt3.js, nuxt-module\nSource: Stack Overflow\n\nQuestion:\nJust trying to add authentication to my NuxtJs 3 app folloging `nuxt/auth` configuration docs, but still get an error during app start:\n\nhttps://i.sstatic.net/XFaWE.png\n\n```\n// nuxt.config.js\n\nexport default defineNuxtConfig({\n auth: {\n // ...\n },\n modules: [\n // '@nuxtjs/axios',\n '@nuxtjs/auth-next'\n ],\n})\n```\n\nReceived same error for `@nuxtjs/axios` but I just commented it out since its official documentation indicates to switch to `$fetch API`.\n\nCannot figure out where the error is\n\n========================================\n\nTop Answer:\nAt the time being, `nuxt/auth` module is not supported by Nuxt3.\n\nYou can find the list of modules supported by Nuxt3 here https://nuxt.com/modules?version=3.x\n\n========================================\n\nCode:\n```js\n// nuxt.config.js\n\nexport default defineNuxtConfig({\n auth: {\n // ...\n },\n modules: [\n // '@nuxtjs/axios',\n '@nuxtjs/auth-next'\n ],\n})\n```\n\n```text\nnuxt/auth\n```\n\n```text\n@nuxtjs/axios\n```\n\n```text\n$fetch API\n```\n\n```text\nnuxt-auth\n```\n\n```text\nnuxt/auth\n```\n\n========================================\n\nComments:\n- Thanks, totally missed it, kinda feel stupid now\n- @fudo all good, no shame. Happens to everybody.\n- Third party maintainer but it's indeed a viable solution in the meantime.","metadata":{"transformedAt":"2026-08-18T18:33:07.848Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":77,"estimatedTokens":358}}214{"id":"stack-48001813","source":"stackoverflow","questionId":48001813,"title":"Best way to config Global Headers for Get, Post, Patch in VueJS","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: Best way to config Global Headers for Get, Post, Patch in VueJS\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm new with VueJs, I'm finding best way to config Global Headers for Get, Post, Patch in VueJS, which is **easy to use and strong security**. In the current I just write it in `export default {}` for every components and it's very bad I know. So I ask you guys to help.\n\nFixed Thanks to @Hardik Satasiya\n\n~/plugins/axios.js\n\nEvery Components:\n\n```\nimport axios from 'axios'\n\nvar api = axios.create({\n baseURL: 'http://localhost:8000/api/v1/',\n headers: {'Authorization': 'JWT ' + store.state.token}\n})\n\nexport default api\n```\n\nIssues: Can't tranmit store in to axios.create, so `store is not defined`\n\n========================================\n\nTop Answer:\nON YOUR MAIN.JS\n\n```\nimport axios from \"axios\";\nconst base = axios.create({\n baseURL: \"http://127.0.0.1:8000/\", \n});\n\nVue.prototype.$http = base;\n\n Vue.prototype.$http.interceptors.request.use(\n config => {\n let accessToken = localStorage.getItem('token');\n if (accessToken) {\n config.headers = Object.assign({\n Authorization: `Bearer ${accessToken}`\n }, config.headers);\n }\n return config;\n },\n error => {\n return Promise.reject(error);\n }\n);\n```\n\n========================================\n\nCode:\n```text\nimport axios from 'axios'\n\nvar api = axios.create({\n baseURL: 'http://localhost:8000/api/v1/',\n headers: {'Authorization': 'JWT ' + store.state.token}\n})\n\nexport default api\n```\n\n```text\nexport default {}\n```\n\n```text\nstore is not defined\n```\n\n```text\nimport axios from 'axios';\n\naxios.defaults.baseURL = 'https://api.example.com';\naxios.defaults.headers.common['Authorization'] = AUTH_TOKEN;\naxios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';\n```\n\n```text\nimport axios from 'axios';\n\nvar myApi = axios.create({\n baseURL: 'https://my-domain.com/api/',\n timeout: 1000,\n headers: {'X-Custom-Header': 'CustomHeader1'}\n});\n\n// another api service\nvar amazonApi = axios.create({\n baseURL: 'https://amazon-domain.com/api/',\n timeout: 2000,\n headers: {'X-Custom-Header': 'CustomHeader2'}\n});\n\nexport default {\n myApi,\n amazonApi\n}\n```\n\n```text\nmyApi.defaults.headers.authorization = 'JWT ' + yourToken;\n```\n\n```text\naxios\n```\n\n```text\ninstances\n```\n\n```text\nmultiple api\n```\n\n```text\napi\n```\n\n```text\nready callback\n```\n\n```text\nlocalStorage\n```\n\n```text\nVue.http.interceptors.push(function(request, next) {\n\n // modify method\n request.method = 'POST';\n\n // modify headers\n request.headers.set('X-CSRF-TOKEN', 'TOKEN');\n request.headers.set('Authorization', 'Bearer TOKEN');\n\n // continue to next interceptor\n next();\n});\n```\n\n```text\nvue-resource\n```\n\n```text\ninterceptors\n```\n\n```text\nimport axios from \"axios\";\nconst base = axios.create({\n baseURL: \"http://127.0.0.1:8000/\", \n});\n\nVue.prototype.$http = base;\n\n Vue.prototype.$http.interceptors.request.use(\n config => {\n let accessToken = localStorage.getItem('token');\n if (accessToken) {\n config.headers = Object.assign({\n Authorization: `Bearer ${accessToken}`\n }, config.headers);\n }\n return config;\n },\n error => {\n return Promise.reject(error);\n }\n);\n```\n\n========================================\n\nComments:\n- Now I use Axios @Manish\n- Axios supports interceptors too: github.com/axios/axios#interceptors. Also look into this: stackoverflow.com/questions/44207197/…\n- Thank you @Hardik Satasiya. Best answer for you!\n- glad, you liked it :)\n- Excuse me, Can you show me how to get **Token in Store** or **Token in LocalStorage in your code**?\n- can you describe in more detail, means you need to add token to created instance after its created right ?\n- I fixed my code above and issues. You can take a look :)\n- ok added update, you can set header again when you get token for that instance.\n- Could I import it directly to axios.create?\n- yes but you need to have it from the begging then only you can import, other wise you have to add it later.","metadata":{"transformedAt":"2026-08-18T18:33:07.849Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":195,"estimatedTokens":1005}}215{"id":"stack-74637529","source":"stackoverflow","questionId":74637529,"title":"router-link-active Nuxt 3 / VueJS on nested routes not applying to parent","tags":["javascript","vue.js","nuxt.js","vue-router","nuxt3.js"],"text":"Title: router-link-active Nuxt 3 / VueJS on nested routes not applying to parent\nTags: javascript, vue.js, nuxt.js, vue-router, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI have created a simple reproduction to better explain myself. I have:\n\n```\n-| pages/\n---| test/\n------| index.vue\n------| nested.vue\n```\n\nAnd I have a navbar, having read the documentation I assume if I NuxtLink to `/test` or `/test/nested.vue` then I would have `router-link-active` css class applied to both in the navbar but it doesn't seem to do that.\n\nThe docs seem to suggest you should be laying out your content as:\n\n```\n-| pages/\n---| parent/\n------| child.vue\n---| parent.vue\n```\n\nI tried that and just doesn't work - the child is never rendered (unless I add another `` to parent.vue which is not what I want since that would show content of parent and child.\n\nReproduction here: https://stackblitz.com/edit/nuxt-app-config-t3nvjv?file=app.vue\n\nHelp would be much appreciated appreciated.\n\n========================================\n\nCode:\n```text\n-| pages/\n---| test/\n------| index.vue\n------| nested.vue\n```\n\n```text\n-| pages/\n---| parent/\n------| child.vue\n---| parent.vue\n```\n\n```text\n/test\n```\n\n```text\n/test/nested.vue\n```\n\n```text\nrouter-link-active\n```\n\n```text\n<NuxtPage>\n```\n\n```text\n/pages\n /posts\n [postId].vue\n index.vue\n posts.vue\n```\n\n```text\n<template>\n <h1>All posts page</h1>\n <p>Whatever...</p>\n</template>\n```\n\n```text\n<template>\n <h1>Single post page</h1>\n <p>{{ postId }}</p>\n</template>\n```\n\n```text\n<template>\n <NuxtPage />\n</template>\n```\n\n```text\nNuxtPage\n```\n\n```text\n/posts/index.vue\n```\n\n```text\n/posts/[postId].vue\n```\n\n```text\nposts.vue\n```\n\n```text\nindex.vue\n```\n\n```text\n[postId].vue\n```\n\n```text\nNuxtLink\n```\n\n```text\nrouter-link-active\n```\n\n```text\nrouter-link-exact-active\n```\n\n========================================\n\nComments:\n- Coming from Nuxt 2 thinking, the top-level `posts.vue` was what I was missing to make routes properly nest so that the activeClass actually applies.\n- I kept hitting this issue, thanks so much for writing this answer this completely solved it for me\n- This is the solution. works like a charm. thanks!\n- This worked! But is it documented somewhere in the official (nuxt 3) docs?\n- Found it: nuxt.com/docs/guide/directory-structure/pages#nested-routes","metadata":{"transformedAt":"2026-08-18T18:33:07.849Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":136,"estimatedTokens":578}}216{"id":"stack-49889003","source":"stackoverflow","questionId":49889003,"title":"Cannot write into input field on safari","tags":["ios","vue.js","nuxt.js"],"text":"Title: Cannot write into input field on safari\nTags: ios, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have an input field that cannot be selected on my Iphone. I can click on the input but it is not focusing. The keyboard to write appears but when I write something into it nothing happens. Therefore I cannot fill out the input fields.\nIs something missing in my CSS?\n\n```\n\n \n \n \n \n \n \n \n Log In\n \n \n```\n\n========================================\n\nTop Answer:\nTry to put your `input` nested in a `form`.\nThis is better for validations and accessibility, and that might fix your issue as well.\n\nYour login button should also be of the `submit` type. See that link:\nhttps://www.w3schools.com/html/html_forms.asp\n\n========================================\n\nCode:\n```text\n<div class=\"container\" v-if=\"user === null\">\n <div class=\"input\">\n <input type=\"text\" v-model=\"username\" placeholder=\"E-Mail\">\n </div>\n <div class=\"input\">\n <input type=\"password\" @keyup.enter=\"authenticate\" v-model=\"password\" placeholder=\"Passwort\">\n </div>\n <div class=\"buttons\">\n <button @click=\"authenticate\">Log In</button>\n </div>\n </div>\n```\n\n```text\n* {\n user-select: none;\n -khtml-user-select: none;\n -o-user-select: none;\n -moz-user-select: -moz-none;\n -webkit-user-select: none;\n}\n```\n\n```text\ninput, input:before, input:after {\n -webkit-user-select: initial;\n -khtml-user-select: initial;\n -moz-user-select: initial;\n -ms-user-select: initial;\n user-select: initial;\n}\n```\n\n```text\ninput\n```\n\n```text\nform\n```\n\n```text\nsubmit\n```\n\n========================================\n\nComments:\n- There is no css here\n- I did not modify anything. thats why i have no css. Is there something that should be added?\n- hackernoon.com/… ?\n- Which field are you writing to? What does `nothing happens` mean? What is expected?\n- Possible dup: stackoverflow.com/questions/20495827/…\n- This saved me! Thank you. I was getting very confused as all the other browsers behaved normally with user-select applied.\n- GREAT! Saved my day! My textarea on iphone with cordova had a fuzzy behavior with this additonal css styles it worked fine on the iphone.","metadata":{"transformedAt":"2026-08-18T18:33:07.849Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":90,"estimatedTokens":554}}217{"id":"stack-53444093","source":"stackoverflow","questionId":53444093,"title":"Getting error when trying to use Nuxt font awesome 5 although I followed the official manual page","tags":["javascript","nuxt.js"],"text":"Title: Getting error when trying to use Nuxt font awesome 5 although I followed the official manual page\nTags: javascript, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use font awesome 5 in my Nuxt project following the official guide below.\nhttps://www.npmjs.com/package/nuxt-fontawesome\n\nHowever, I'm getting a strange error and can't display what I want. \n\n [Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the \"name\" option.\n\nHere is how my code looks like:\n\n```\n//index.vue\n\n \n \n\n import { fas } from '@fortawesome/free-solid-svg-icons'\n import { faGithub } from '@fortawesome/free-brands-svg-icons'\n computed: {\n fas () {\n return fas\n },\n faGithub () {\n return faGithub\n }\n },\nand more.....\n\n//nuxt.config.js\n modules: [\n [\n 'bootstrap-vue/nuxt', { css: true },\n ['nuxt-fontawesome', {\n component: 'fa',\n\n imports: [\n //import whole set\n {\n set: '@fortawesome/free-solid-svg-icons',\n icons: ['fas']\n },\n ]\n }]\n ],\n ],\n fontawesome: {\n component: 'fa',\n imports: [\n {\n set: '@fortawesome/free-solid-svg-icons',\n icons: ['fas']\n },\n ],\n },\n```\n\nPlease let me ask for your help. I have spent long enough time on this issue already. Thank you in advance!\n\n========================================\n\nCode:\n```text\n//index.vue\n<template>\n <fa :icon=\"fas.faAddressBook\" />\n <fa :icon=\"faGithub\" />\n</template>\n<script>\n import { fas } from '@fortawesome/free-solid-svg-icons'\n import { faGithub } from '@fortawesome/free-brands-svg-icons'\n computed: {\n fas () {\n return fas\n },\n faGithub () {\n return faGithub\n }\n },\nand more.....\n\n\n//nuxt.config.js\n modules: [\n [\n 'bootstrap-vue/nuxt', { css: true },\n ['nuxt-fontawesome', {\n component: 'fa',\n\n imports: [\n //import whole set\n {\n set: '@fortawesome/free-solid-svg-icons',\n icons: ['fas']\n },\n ]\n }]\n ],\n ],\n fontawesome: {\n component: 'fa',\n imports: [\n {\n set: '@fortawesome/free-solid-svg-icons',\n icons: ['fas']\n },\n ],\n },\n```\n\n```text\nimport Vue from 'vue'\nimport { library, config } from '@fortawesome/fontawesome-svg-core'\nimport { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'\nimport { fas } from '@fortawesome/free-solid-svg-icons'\nimport { fab } from '@fortawesome/free-brands-svg-icons'\n\n// This is important, we are going to let Nuxt.js worry about the CSS\nconfig.autoAddCss = false\n\n// You can add your icons directly in this plugin. See other examples for how you\n// can add other styles or just individual icons.\nlibrary.add(fas)\nlibrary.add(fab)\n\n// Register the component globally\nVue.component('font-awesome-icon', FontAwesomeIcon)\n```\n\n```text\ncss: [\n '@fortawesome/fontawesome-svg-core/styles.css'\n ],\n\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n '~/plugins/fontawesome.js',\n\n ],\n```\n\n```text\n<font-awesome-icon icon=\"['fab', 'facebook']\" style=\"font-size: 22px\"/>\n```\n\n```text\nnpm install --save @fortawesome/vue-fontawesome @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/free-brands-svg-icons\n```\n\n========================================\n\nComments:\n- Thank you for your answer! Just after I posted this question, I found that workaround. But it is not how the official page explained so I wanted to find a straightforward way but it seems I need to use plugin anyway. Thank you for your answer very much again!\n- No worries. If you're happy with the answer please mark it as correct.\n- Done. By the way, this didnt work. Instead, it needs to be like this. Just for the sake of ppl who see this page.\n- Yeah I copied mine but I was using a v-for with an array of icons and was binding them so I had the `:icon=` in it but thought it would be just `icon=` if not dynamic. Guess not. Anyway, glad you got it working. Cheers.\n- How do you add the pro icon packs? `npm i @fontawesome/fontawesome-pro --save-dev`. comes will all the files but i cannot figure out how to add the packages `fal`\n- @Jujubes I think you need to import the specific pro package like `npm i --save @fortawesome/pro-solid-svg-icons` then import that in your plugin `import { fal } from '@fortawesome/pro-solid-svg-icons'` (or whichever is the 'fal' one) then add that to the library: `library.add(fal)` Note Masa's comment above for usage but otherwise steps above should work. The docs might help.\n- @Andrew1325 it would seem you are correct and installing the pro version within the dev dependency for nuxt doesnt do much unless u just attach the css file globally","metadata":{"transformedAt":"2026-08-18T18:33:07.849Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":164,"estimatedTokens":1167}}218{"id":"stack-69206509","source":"stackoverflow","questionId":69206509,"title":"Nuxt: how can I get sourcemap files and where can I find them in production?","tags":["vue.js","nuxt.js"],"text":"Title: Nuxt: how can I get sourcemap files and where can I find them in production?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have tried alot of solutions (nuxt.config & change the devtool source-map) but nothing work..\nI need to get the real source code in production so I can get the real error's line like Sentry for example\nplease can anyone help me...\n\n========================================\n\nCode:\n```js\nexport default {\n build: {\n extend(config, { isClient }) {\n // Extend only webpack config for client-bundle\n if (isClient) {\n config.devtool = 'source-map'\n }\n }\n }\n}\n```\n\n```js\n//# sourceMappingURL=05439bf.js.map\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnpm run build\n```\n\n```text\n*.js.map\n```\n\n```text\n.nuxt/dist/\n```\n\n```text\n.nuxt/dist/client/05439bf.js\n```\n\n```text\n.nuxt/dist/client/05439bf.js.map\n```\n\n```text\nnpm run start\n```\n\n```text\n*.js.map\n```\n\n```text\n/.nuxt/dist/\n```\n\n========================================\n\nComments:\n- Since it will be bundled for production, I'm not sure that you can do that. Can't you find it without the exact line?\n- @kissu it's just showing the error line of complied files in Sentry it's showing the current error line when app in production mode","metadata":{"transformedAt":"2026-08-18T18:33:07.849Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":70,"estimatedTokens":312}}219{"id":"stack-58968237","source":"stackoverflow","questionId":58968237,"title":"NuxtJS i18n [vue-router] Route with name about_us___en does not exist","tags":["vue.js","nuxt.js","nuxt-i18n"],"text":"Title: NuxtJS i18n [vue-router] Route with name about_us___en does not exist\nTags: vue.js, nuxt.js, nuxt-i18n\nSource: Stack Overflow\n\nQuestion:\nIm using nuxtjs 2.10.x and i18n module. Nu custom middleware or anything like that. The routing is working fine.\n\nmy `nuxt.config.js` modules/i18n part:\n\n```\n...\nmodules: [\n'@nuxtjs/axios',\n'@nuxtjs/pwa',\n'@nuxtjs/auth',\n'@nuxtjs/dotenv',\n'nuxt-fontawesome',\n[\n 'nuxt-i18n',\n {\n locales: [\n {\n code: 'en',\n iso: 'en-US',\n file: 'en.json',\n name: 'English'\n },\n {\n code: 'zh',\n iso: 'zh-CN',\n file: 'zh.json',\n name: '简体中文'\n }\n ],\n lazy: true,\n langDir: 'locales/',\n defaultLocale: 'en',\n strategy: 'prefix_except_default',\n differentDomains: false,\n vueI18n: {\n fallbackLocale: 'en'\n },\n detectBrowserLanguage: {\n useCookie: true,\n cookieKey: 'lang'\n }\n }\n ]\n ],\n...\n```\n\npages folder structure:\n\n```\n'pages/'\n |--'contact_us.vue'\n |--'_lang/'\n |--'contact_us.vue'\n```\n\nBut I'm getting this crazy warning: `[vue-router] Route with name 'contact_us___en' does not exist`. Actually nuxt is giving similar warning for the all pages I have. And there is no any clue why it's like that. What is possibly wrong?\n\n========================================\n\nTop Answer:\n```\n\n Some text...\n \n```\n\nThis is how I configured mine.\n\n========================================\n\nCode:\n```text\n...\nmodules: [\n'@nuxtjs/axios',\n'@nuxtjs/pwa',\n'@nuxtjs/auth',\n'@nuxtjs/dotenv',\n'nuxt-fontawesome',\n[\n 'nuxt-i18n',\n {\n locales: [\n {\n code: 'en',\n iso: 'en-US',\n file: 'en.json',\n name: 'English'\n },\n {\n code: 'zh',\n iso: 'zh-CN',\n file: 'zh.json',\n name: '简体中文'\n }\n ],\n lazy: true,\n langDir: 'locales/',\n defaultLocale: 'en',\n strategy: 'prefix_except_default',\n differentDomains: false,\n vueI18n: {\n fallbackLocale: 'en'\n },\n detectBrowserLanguage: {\n useCookie: true,\n cookieKey: 'lang'\n }\n }\n ]\n ],\n...\n```\n\n```text\n'pages/'\n |--'contact_us.vue'\n |--'_lang/'\n |--'contact_us.vue'\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n[vue-router] Route with name 'contact_us___en' does not exist\n```\n\n```text\nlocalePath('index') >>> \"/\"\nlocalePath('login') >>> \"/login\"\nlocalePath('tech-test') >>> \"/tech/test\"\n```\n\n```text\nlocalePath('/') >>> \"/\"\nlocalePath('/login') >>> \"/\"\nlocalePath('tech/test') >>> \"/\"\n```\n\n```text\nlocalePath('/') >>> \"/\"\nlocalePath('/tech/test') >>> \"/tech/test\"\n```\n\n```text\nlocalePath()\n```\n\n```text\n<nuxt-link :to=\"localePath({ name: 'your-dynamic-path' })\">\n Some text...\n </nuxt-link>\n```\n\n========================================\n\nComments:\n- I got your point. And I see now in the documentation examples they use `localePath('index')`. Before I've seen somewhere `localePath('/')`\n- yes i wrote it right hte first time. but not in the samples.\n- i will try to submit a pull request, because this is not a nice way to write routes.\n- BTW can I do something like this ``?\n- Yes, but `localePath('index')` can result in `\"/\"` or `\"/fr\"`. Which means sometimes youll have to add a >`'/' + 'products/'` and sometimes not.\n- you could use , `(temp1.localePath('index') + '/products/').replace('//','/')`\n- Thank you. Will it affect the perfomance? currently I'm using `(this.localePath('index') == '/' ? '/': this.localePath('index') + '/') + ...`\n- considering how much more logic the localePath function has (200 lines), I would suggest calling it only once.","metadata":{"transformedAt":"2026-08-18T18:33:07.849Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":173,"estimatedTokens":890}}220{"id":"stack-58205450","source":"stackoverflow","questionId":58205450,"title":"Incomprehensible ESlint warning about self-closing HTML void element","tags":["vue.js","eslint","nuxt.js"],"text":"Title: Incomprehensible ESlint warning about self-closing HTML void element\nTags: vue.js, eslint, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn my Vue project I have the following element:\n\n```\n\n```\n\nIt is self-closing. Yet, ESlint throws this warning:\n\n```\nDisallow self-closing on HTML void elements () vue/html-self-closing\n```\n\nDoesn't make any sense to me, am I missing something? What's the problem?\n\n========================================\n\nCode:\n```text\n<img\n class=\"header__branding__logo\"\n src=\"@/assets/img/logo_desktop.svg\"\n/>\n```\n\n```text\nDisallow self-closing on HTML void elements (<img/>) vue/html-self-closing\n```\n\n```text\n/\n```\n\n```text\n/\n```\n\n========================================\n\nComments:\n- Change to: `` and your linter will be happy.","metadata":{"transformedAt":"2026-08-18T18:33:07.849Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":45,"estimatedTokens":191}}221{"id":"stack-76236369","source":"stackoverflow","questionId":76236369,"title":"What is the proper way to include chart.js with Nuxt 3.4?","tags":["charts","nuxt.js","nuxt3.js","vue-chartjs"],"text":"Title: What is the proper way to include chart.js with Nuxt 3.4?\nTags: charts, nuxt.js, nuxt3.js, vue-chartjs\nSource: Stack Overflow\n\nQuestion:\nThere are some tutorials out there (e.g. https://medium.com/geekculture/chart-js-in-nuxt-js-how-to-implement-c255a2657b02) that show how to integrate Chart.js with an earlier version of Nuxt 3 or even Nuxt 2. But they do not work for various reasons. This tutorial e.g.\nhttps://dev.to/anggakswr/chart-js-in-nuxt-js-4hjf\ncauses a 500 error:\n\n```\nCannot read properties of undefined (reading 'component')\n\nat ./plugins/charts.js:6:31\nat async ViteNodeRunner.directRequest (./node_modules/vite- \nnode/dist/client.mjs:331:5)\n```\n\nAlso, there are different approaches: one tutorial/example uses the \"Nuxt plugin\" way, another the \"Nuxt component\" way...\n\nI tried the plugin-way based on the docu here: https://nuxt.com/docs/guide/directory-structure/plugins#vue-plugins:\n\n```\n// plugins/charts.js\n\nimport { Bar } from \"vue-chartjs\"\n\nexport default defineNuxtPlugin((nuxtApp) => {\n nuxtApp.vueApp.use(Bar)\n})\n```\n\nBut as soon as I run `npm run dev`, I get this warning:\n\n[Vue warn]: A plugin must either be a function or an object with an \"install\" function.\n\nAnd later:\n\n```\n[Vue warn]: Failed to resolve component: BarChart\nIf this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. \nat ref=Ref >\n```\n\nHere is a codesandbox:\nhttps://codesandbox.io/p/sandbox/gracious-lumiere-88bw4j\n\nWhat do I have to do to get (vue-)chart.js working?\n\n========================================\n\nCode:\n```text\nCannot read properties of undefined (reading 'component')\n\nat ./plugins/charts.js:6:31\nat async ViteNodeRunner.directRequest (./node_modules/vite- \nnode/dist/client.mjs:331:5)\n```\n\n```text\n// plugins/charts.js\n\nimport { Bar } from \"vue-chartjs\"\n\nexport default defineNuxtPlugin((nuxtApp) => {\n nuxtApp.vueApp.use(Bar)\n})\n```\n\n```text\n[Vue warn]: Failed to resolve component: BarChart\nIf this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. \nat <Chart onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > >\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm i vue-chartjs chart.js\n```\n\n```js\nimport { Chart, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js'\nexport default defineNuxtPlugin(() => {\n Chart.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend)\n})\n```\n\n```js\n<script lang=\"ts\" setup>\nimport { Bar } from 'vue-chartjs'\nconst chartData = ref({\n labels: ['January', 'February', 'March', 'April', 'May'],\n datasets: [\n {\n label: 'Data One',\n backgroundColor: '#f87979',\n data: [40, 20, 12, 50, 10],\n },\n ],\n})\nconst chartOptions = ref({\n responsive: true,\n maintainAspectRatio: false,\n})\n</script>\n<template>\n <div>\n <Bar\n :data=\"chartData\"\n :options=\"chartOptions\"\n />\n </div>\n</template>\n```\n\n```js\n<script lang=\"ts\" setup>\nimport { Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js'\nimport { Bar } from 'vue-chartjs'\n\n// Register\nChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)\n\n\nconst chartData = ref({\n labels: ['January', 'February', 'March', 'April', 'May'],\n datasets: [\n {\n label: 'Data One',\n backgroundColor: '#f87979',\n data: [40, 20, 12, 50, 10],\n },\n ],\n})\nconst chartOptions = ref({\n responsive: true,\n maintainAspectRatio: false,\n})\n\n</script>\n<template>\n <div>\n <Bar\n :data=\"chartData\"\n :options=\"chartOptions\"\n />\n </div>\n</template>\n<style scoped lang=\"css\"></style>\n```\n\n```text\n~/plugins/chartjs.ts\n```\n\n========================================\n\nComments:\n- What are the pros and cons of each option?\n- The functionalities are the same but if you only have to use it in a single component, then manually registering it would be a great option","metadata":{"transformedAt":"2026-08-18T18:33:07.849Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":163,"estimatedTokens":989}}222{"id":"stack-65664635","source":"stackoverflow","questionId":65664635,"title":"`nuxt.js` alternative for vue3?","tags":["vue.js","nuxt.js","vuejs3"],"text":"Title: `nuxt.js` alternative for vue3?\nTags: vue.js, nuxt.js, vuejs3\nSource: Stack Overflow\n\nQuestion:\nI have a vue3 cli app, which needs to support SSR for SEO concerns.\nI want to use pages and layouts features of nuxt.js, but currently it doesn't support vue3.\n\nSo what to do now..? is there any framework like nuxt.js but supports vue3..?","metadata":{"transformedAt":"2026-08-18T18:33:07.849Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":9,"estimatedTokens":86}}223{"id":"stack-76341630","source":"stackoverflow","questionId":76341630,"title":"How to extend the H3Event context type in Nuxt 3","tags":["typescript","nuxt.js","nuxt3.js"],"text":"Title: How to extend the H3Event context type in Nuxt 3\nTags: typescript, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nIn the Nuxt 3 documentation, there's an example that shows using server middleware to annotate requests with additional information via `event.context`:\n\n```\nexport default defineEventHandler((event) => {\n event.context.auth = { user: 123 }\n})\n```\n\nHowever, there is no example of how to make the corresponding TypeScript typing for this. I'd prefer my `event.context.auth` not to be an `any` type.\n\nThe standard TypeScript library type extension method doesn't seem to work correctly here. I tried to make a `shims.d.ts` containing the following:\n\n```\ndeclare module 'h3' {\n interface H3EventContext {\n auth: AuthSession\n }\n}\n```\n\nHowever, this breaks the type inference on the `defineEventHandler` function, making all `event` parameters into implicit `any`s. How can I declare my event context type without breaking stuff?\n\n========================================\n\nTop Answer:\nI'm not sure why your event becomes typed as any. It shouldn't do that and to test this I created an example on StackBlitz that demonstrates that what you did should work as intended.\n\nhttps://stackblitz.com/edit/nuxt-starter-uhgayq?file=server%2Fapi%2Ftest.ts\n\nThe event is of type H3Event, event.context is H3EventContext and event.context.authenticatedUser is User. The User is defined in /server/user.ts\n\nMaybe I'm missing something, but as you can see it should work fine the way you did it.\n\n========================================\n\nCode:\n```text\nexport default defineEventHandler((event) => {\n event.context.auth = { user: 123 }\n})\n```\n\n```text\ndeclare module 'h3' {\n interface H3EventContext {\n auth: AuthSession\n }\n}\n```\n\n```text\nevent.context\n```\n\n```text\nevent.context.auth\n```\n\n```text\nany\n```\n\n```text\nshims.d.ts\n```\n\n```text\ndefineEventHandler\n```\n\n```text\nevent\n```\n\n```text\nany\n```\n\n```text\ntype MyFancyAuthType = {\n user: number\n}\n\ndeclare module 'h3' {\n interface H3EventContext {\n auth: MyFancyAuthType;\n // any other type\n }\n}\n\nexport default defineEventHandler((event) => {\n // Here you will be able to access .auth on context with proper intellisense\n event.context.auth = { user: 123 }\n})\n```\n\n```text\n{\n ...\n \"files\": [\"shim.d.ts\"]\n ...\n}\n```\n\n```text\n...\ndeclare module 'h3' {\n ...\n}\n\n// this is important\nexport default {};\n```\n\n```text\nh3\n```\n\n```text\nh3\n```\n\n```text\nshim.d.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\nexport default {}\n```\n\n```text\nshim.d.ts\n```\n\n========================================\n\nComments:\n- I tried this earlier, but sadly when placed in a separate declaration file, it causes all `defineEventHandler` functions to somehow lose their type inference entirely such that the `event` parameter becomes an `any`. Not sure what's happening there!\n- Doesn't seem to be giving correct types in your example.","metadata":{"transformedAt":"2026-08-18T18:33:07.849Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":148,"estimatedTokens":721}}224{"id":"stack-55090038","source":"stackoverflow","questionId":55090038,"title":"GET http://api:1337/games net::ERR_NAME_NOT_RESOLVED for nuxt.js pages using asyncData","tags":["docker","nuxt.js","traefik","strapi"],"text":"Title: GET http://api:1337/games net::ERR_NAME_NOT_RESOLVED for nuxt.js pages using asyncData\nTags: docker, nuxt.js, traefik, strapi\nSource: Stack Overflow\n\nQuestion:\nI have somewhat complicated setup with docker. Everything's working as expected except I have this weird problem. \nVisiting *index* page or */pages/_id* pages I have no errors. But when I try to open */other-page* it crashes. All are using the same API url.\n\nError found in the console when opening */other-page*:\n\nGET http://api:1337/games net::ERR_NAME_NOT_RESOLVED\n\nNot sure what to do, any suggestions?\n\nnuxt.config.js\n\n```\naxios: {\n baseURL: 'http://api:1337'\n },\n```\n\ndocker-compose.yml\n\n```\nversion: '3'\n\nservices:\n api:\n build: .\n image: strapi/strapi\n environment:\n - APP_NAME=strapi-app\n - DATABASE_CLIENT=mongo\n - DATABASE_HOST=db\n - DATABASE_PORT=27017\n - DATABASE_NAME=strapi\n - DATABASE_USERNAME=\n - DATABASE_PASSWORD=\n - DATABASE_SSL=false\n - DATABASE_AUTHENTICATION_DATABASE=strapi\n - HOST=api\n - NODE_ENV=production\n ports:\n - 1337:1337\n volumes:\n - ./strapi-app:/usr/src/api/strapi-app\n #- /usr/src/api/strapi-app/node_modules\n depends_on:\n - db\n restart: always\n links:\n - db\n\n nuxt:\n # build: ./app/\n image: \"registry.gitlab.com/username/package:latest\"\n container_name: nuxt\n restart: always\n ports:\n - \"3000:3000\"\n links:\n - api:api\n command:\n \"npm run start\"\n\n nginx:\n image: nginx:1.14.2\n expose:\n - 80\n container_name: nginx\n restart: always\n ports:\n - \"80:80\"\n volumes:\n - ./nginx:/etc/nginx/conf.d\n depends_on:\n - nuxt\n links:\n - nuxt\n```\n\nindex.vue\n\n```\n...\n async asyncData({ store, $axios }) {\n const games = await $axios.$get('/games')\n store.commit('games/emptyList')\n games.forEach(game => {\n store.commit('games/add', {\n id: game.id || game._id,\n ...game\n })\n })\n return { games }\n },\n...\n```\n\npage.vue\n\n```\n...\n async asyncData({ store, $axios }) {\n const games = await $axios.$get('/games')\n store.commit('games/emptyList')\n games.forEach(game => {\n store.commit('games/add', {\n id: game.id || game._id,\n ...game\n })\n })\n return { games }\n },\n...\n```\n\nNginx conf\n\n```\nupstream webserver {\n ip_hash;\n server nuxt:3000;\n}\n\nserver {\n listen 80;\n access_log off;\n connection_pool_size 512k;\n large_client_header_buffers 4 512k;\n\n location / {\n proxy_pass http://webserver;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection \"upgrade\";\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_max_temp_file_size 0;\n }\n```\n\nUPDATE:\n\nTried what Thomasleveil suggested. Now I'm receiving following error:\n\nnuxt | [2:09:35 PM] Error: connect ECONNREFUSED 127.0.0.1:80\n\nSo, it seems like now /api is being forwarded to 127.0.0.1:80. Not sure why ^^\n\nnuxt.config.js\n\n```\naxios: {\n baseURL: '/api'\n },\n server: {\n proxyTable: {\n '/api': {\n target: 'http://localhost:1337',\n changeOrigin: true,\n pathRewrite: {\n \"^/api\": \"\"\n }\n }\n }\n }\n```\n\ndocker-compose.yml\n\n```\nversion: '3'\n\nservices:\n reverse-proxy:\n image: traefik # The official Traefik docker image\n command: --api --docker # Enables the web UI and tells Traefik to listen to docker\n ports:\n - \"80:80\" # The HTTP port\n - \"8080:8080\" # The Web UI (enabled by --api)\n volumes:\n - /var/run/docker.sock:/var/run/docker.sock # listen to the Docker events\n networks:\n - mynet\n\n api:\n build: .\n image: strapi/strapi\n container_name: api\n environment:\n - APP_NAME=strapi-app\n - DATABASE_CLIENT=mongo\n - DATABASE_HOST=db\n - DATABASE_PORT=27017\n - DATABASE_NAME=strapi\n - DATABASE_USERNAME=\n - DATABASE_PASSWORD=\n - DATABASE_SSL=false\n - DATABASE_AUTHENTICATION_DATABASE=strapi\n - HOST=api\n - NODE_ENV=development\n ports:\n - 1337:1337\n volumes:\n - ./strapi-app:/usr/src/api/strapi-app\n #- /usr/src/api/strapi-app/node_modules\n depends_on:\n - db\n restart: always\n networks:\n - mynet\n labels:\n - \"traefik.backend=api\"\n - \"traefik.docker.network=mynet\"\n - \"traefik.frontend.rule=Host:example.com;PathPrefixStrip:/api\"\n - \"traefik.port=1337\"\n\n db:\n image: mongo\n environment:\n - MONGO_INITDB_DATABASE=strapi\n ports:\n - 27017:27017\n volumes:\n - ./db:/data/db\n restart: always\n networks:\n - mynet\n\n nuxt:\n # build: ./app/\n image: \"registry.gitlab.com/username/package:latest\"\n container_name: nuxt\n restart: always\n ports:\n - \"3000:3000\"\n command:\n \"npm run start\"\n networks:\n - mynet\n labels:\n - \"traefik.backend=nuxt\"\n - \"traefik.frontend.rule=Host:example.com;PathPrefixStrip:/\"\n - \"traefik.docker.network=web\"\n - \"traefik.port=3000\"\n\nnetworks:\n mynet:\n external: true\n```\n\n========================================\n\nCode:\n```text\naxios: {\n baseURL: 'http://api:1337'\n },\n```\n\n```text\nversion: '3'\n\nservices:\n api:\n build: .\n image: strapi/strapi\n environment:\n - APP_NAME=strapi-app\n - DATABASE_CLIENT=mongo\n - DATABASE_HOST=db\n - DATABASE_PORT=27017\n - DATABASE_NAME=strapi\n - DATABASE_USERNAME=\n - DATABASE_PASSWORD=\n - DATABASE_SSL=false\n - DATABASE_AUTHENTICATION_DATABASE=strapi\n - HOST=api\n - NODE_ENV=production\n ports:\n - 1337:1337\n volumes:\n - ./strapi-app:/usr/src/api/strapi-app\n #- /usr/src/api/strapi-app/node_modules\n depends_on:\n - db\n restart: always\n links:\n - db\n\n nuxt:\n # build: ./app/\n image: \"registry.gitlab.com/username/package:latest\"\n container_name: nuxt\n restart: always\n ports:\n - \"3000:3000\"\n links:\n - api:api\n command:\n \"npm run start\"\n\n\n nginx:\n image: nginx:1.14.2\n expose:\n - 80\n container_name: nginx\n restart: always\n ports:\n - \"80:80\"\n volumes:\n - ./nginx:/etc/nginx/conf.d\n depends_on:\n - nuxt\n links:\n - nuxt\n```\n\n```text\n...\n async asyncData({ store, $axios }) {\n const games = await $axios.$get('/games')\n store.commit('games/emptyList')\n games.forEach(game => {\n store.commit('games/add', {\n id: game.id || game._id,\n ...game\n })\n })\n return { games }\n },\n...\n```\n\n```text\n...\n async asyncData({ store, $axios }) {\n const games = await $axios.$get('/games')\n store.commit('games/emptyList')\n games.forEach(game => {\n store.commit('games/add', {\n id: game.id || game._id,\n ...game\n })\n })\n return { games }\n },\n...\n```\n\n```text\nupstream webserver {\n ip_hash;\n server nuxt:3000;\n}\n\nserver {\n listen 80;\n access_log off;\n connection_pool_size 512k;\n large_client_header_buffers 4 512k;\n\n location / {\n proxy_pass http://webserver;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection \"upgrade\";\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_max_temp_file_size 0;\n }\n```\n\n```text\naxios: {\n baseURL: '/api'\n },\n server: {\n proxyTable: {\n '/api': {\n target: 'http://localhost:1337',\n changeOrigin: true,\n pathRewrite: {\n \"^/api\": \"\"\n }\n }\n }\n }\n```\n\n```text\nversion: '3'\n\nservices:\n reverse-proxy:\n image: traefik # The official Traefik docker image\n command: --api --docker # Enables the web UI and tells Traefik to listen to docker\n ports:\n - \"80:80\" # The HTTP port\n - \"8080:8080\" # The Web UI (enabled by --api)\n volumes:\n - /var/run/docker.sock:/var/run/docker.sock # listen to the Docker events\n networks:\n - mynet\n\n api:\n build: .\n image: strapi/strapi\n container_name: api\n environment:\n - APP_NAME=strapi-app\n - DATABASE_CLIENT=mongo\n - DATABASE_HOST=db\n - DATABASE_PORT=27017\n - DATABASE_NAME=strapi\n - DATABASE_USERNAME=\n - DATABASE_PASSWORD=\n - DATABASE_SSL=false\n - DATABASE_AUTHENTICATION_DATABASE=strapi\n - HOST=api\n - NODE_ENV=development\n ports:\n - 1337:1337\n volumes:\n - ./strapi-app:/usr/src/api/strapi-app\n #- /usr/src/api/strapi-app/node_modules\n depends_on:\n - db\n restart: always\n networks:\n - mynet\n labels:\n - \"traefik.backend=api\"\n - \"traefik.docker.network=mynet\"\n - \"traefik.frontend.rule=Host:example.com;PathPrefixStrip:/api\"\n - \"traefik.port=1337\"\n\n db:\n image: mongo\n environment:\n - MONGO_INITDB_DATABASE=strapi\n ports:\n - 27017:27017\n volumes:\n - ./db:/data/db\n restart: always\n networks:\n - mynet\n\n nuxt:\n # build: ./app/\n image: \"registry.gitlab.com/username/package:latest\"\n container_name: nuxt\n restart: always\n ports:\n - \"3000:3000\"\n command:\n \"npm run start\"\n networks:\n - mynet\n labels:\n - \"traefik.backend=nuxt\"\n - \"traefik.frontend.rule=Host:example.com;PathPrefixStrip:/\"\n - \"traefik.docker.network=web\"\n - \"traefik.port=3000\"\n\nnetworks:\n mynet:\n external: true\n```\n\n```json\naxios: {\n prefix: '/api',\n proxy: true\n }, \n proxy: {\n '/api/': {\n target: 'http://localhost:1337',\n pathRewrite: {\n '^/api/': ''\n }\n }\n },\n```\n\n```json\naxios: {\n prefix: '/api',\n proxy: true\n }, \n proxy: {\n '/api/': {\n target: process.env.STRAPI_URL || 'http://localhost:1337',\n pathRewrite: {\n '^/api/': ''\n }\n }\n },\n```\n\n```yaml\nversion: '3'\n\nservices:\n reverseproxy: # see https://docs.traefik.io/#the-traefik-quickstart-using-docker\n image: traefik:1.7\n command: --docker\n ports:\n - \"80:80\"\n volumes:\n - /var/run/docker.sock:/var/run/docker.sock\n\n api:\n image: strapi/strapi\n environment:\n - ...\n expose:\n - 1337\n labels:\n traefik.frontend.rule: PathPrefixStrip:/api\n traefik.port: 1337\n\n nuxt:\n image: ...\n expose:\n - 3000\n command:\n \"npm run start\"\n labels:\n traefik.frontend.rule: PathPrefixStrip:/\n traefik.port: 3000\n```\n\n```json\naxios: {\n prefix: '/api',\n proxy: true\n }, \n proxy: {\n '/api/': {\n target: process.env.STRAPI_URL || 'http://localhost:1337',\n pathRewrite: {\n '^/api/': ''\n }\n }\n },\n```\n\n```yaml\nversion: '3'\n\nservices:\n reverseproxy: # see https://docs.traefik.io/#the-traefik-quickstart-using-docker\n image: traefik:1.7\n command: --docker\n ports:\n - \"80:80\"\n volumes:\n - /var/run/docker.sock:/var/run/docker.sock\n\n api:\n image: strapi/strapi\n environment:\n - ...\n expose:\n - 1337\n labels:\n traefik.frontend.rule: PathPrefixStrip:/api\n traefik.port: 1337\n\n nuxt:\n image: ...\n expose:\n - 3000\n command:\n \"npm run start\"\n environment:\n NUXT_HOST: 0.0.0.0\n STRAPI_URL: http://api:1337/\n API_URL_BROWSER: /api\n labels:\n traefik.frontend.rule: PathPrefixStrip:/\n traefik.port: 3000\n```\n\n```text\n/\n```\n\n```text\n/pages/_id\n```\n\n```text\n_id\n```\n\n```text\n/\n```\n\n```text\n/pages/_id\n```\n\n```text\n/\n```\n\n```text\n/pages/xxx\n```\n\n```text\nxxx\n```\n\n```text\nhttp://yourserver/pages/123\n```\n\n```text\nasyncData\n```\n\n```text\nhttp://api:1337/games/123\n```\n\n```text\nhttp://api:1337/games/123\n```\n\n```text\nhttp://yourserver/\n```\n\n```text\nhttp://api:1337/games\n```\n\n```text\nasyncData\n```\n\n```text\nserver-side\n```\n\n```text\nclient-side\n```\n\n```text\n1337\n```\n\n```text\nhttp://api:1337/\n```\n\n```text\nhttp://api:1337\n```\n\n```text\nnet::ERR_NAME_NOT_RESOLVED\n```\n\n```text\napi\n```\n\n```text\nhttp://yourserver/api/\n```\n\n```text\napi\n```\n\n```text\n1337\n```\n\n```text\nclient-side\n```\n\n```text\nhttp://yourserver/api\n```\n\n```text\nhttp://api:1337/\n```\n\n```text\nhttp://api:1337\n```\n\n```text\nserver-side\n```\n\n```text\nserver-side\n```\n\n```text\ntrue\n```\n\n```text\nhttp://localhost:1337\n```\n\n```text\nhttp://localhost:1337\n```\n\n```text\nhttp://api:1337\n```\n\n```text\nSTRAPI_URL\n```\n\n```text\nSTRAPI_URL\n```\n\n```text\nclient-side\n```\n\n```text\nhttp://yourserver\n```\n\n```text\ntraefik.\n```\n\n```text\nnuxt\n```\n\n```text\napi\n```\n\n```text\nserver-side\n```\n\n```text\nclient-side\n```\n\n```text\nhttp://api:1337/\n```\n\n```text\nSTRAPI_URL\n```\n\n```text\nhttp://yourserver/api\n```\n\n========================================\n\nComments:\n- Your api url only resolvable withing docker container. If u access it from browser it wont work\n- I'm not \"accessing\" it, axios is, from its own container.\n- you are accessing it. asyncData executed on client too when u go to that page in browser ( not first load )\n- Aah, so it's executed on the server when I'm visiting home page (index) and then it works, but then when I click on /other-page gets executed on the client too and therefore it fails?\n- yes, right, ssr executed only on initial page load. Then when u navigate within app everything happens on client\n- But if I use domain name instead of api causes the same error if you visit a page and then hit refresh button in the browser...\n- nuxt | [7:13:09 PM] Error: connect EHOSTUNREACH 51.75.xx.xx:1337 nuxt | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1083:14)\n- thanks, but before I dive in into this can it be done with nginx? I'm already using it as 4th container.\n- Added my nginx details to the docker-compose.yml part. Or would you recommend using traefik instead of nginx ?\n- It can be done with nginx, that was my way of implementing a reverse proxy before I encounter Traefik which is a real time saver on that matter. It will deal with HTTP/2, websockets, loadbalancing, header forwarding, circuit breakers, healthchecks, even set up SSL with Letsencrypt for you. If you were to come up with a nginx config that does all that you woud be going to ask many questions on StackOverflow ;)\n- :) Alright' I'll try that. One thing that's confusing to me is target: 'localhost:1337' Should I use api:1337 (container url) or example.com:1337 in Production?\n- `target: 'http://localhost:1337'` in the nuxt.config.js will never be used when you deploy you app to production. Because this bit of config is for webpack-dev-server only. Target should be the url where you can join your api when it runs from the `strapi start` command\n- Unfortunately it didn't work. Please see Update in the question.\n- @emirowski I had the chance to spend more time on your issue and was able to reproduce it. My answer was incomplete and is now edited to go into more details (hopefully clearly) and presents a new tested solution","metadata":{"transformedAt":"2026-08-18T18:33:07.849Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":59,"totalLines":798,"estimatedTokens":3597}}225{"id":"stack-70547375","source":"stackoverflow","questionId":70547375,"title":"Global Sass Import & Usage - Nuxt 3 Static Assets","tags":["vue.js","nuxt.js","vuejs3","vite","nuxt3.js"],"text":"Title: Global Sass Import & Usage - Nuxt 3 Static Assets\nTags: vue.js, nuxt.js, vuejs3, vite, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to import a global Sass stylesheet from the `/assets` directory and use stuff like variables and mixins defined there throughout the components. My `nuxt.config.ts` looks like this currently:\n\n```\nimport { defineNuxtConfig } from \"nuxt3\";\n\nexport default defineNuxtConfig({\n css: [\"@/assets/styles/main.sass\"],\n styleResources: {\n sass: [\"@/assets/styles/main.sass\"],\n },\n build: {\n extractCSS: true,\n styleResources: {\n sass: \"@/assets/styles/main.sass\",\n hoistUseStatements: true,\n },\n },\n // buildModules: [\"@nuxtjs/style-resources\"], // This throws error\n vite: {\n css: {\n loaderOptions: {\n sass: {\n additionalData: ` @import \"@/assets/styles/main.sass\"; `,\n },\n },\n },\n },\n});\n```\n\nWhen I try to use a variable now, I get `[plugin:vite:css] Undefined variable.` error. This used to work very well in Nuxt 2 with `@nuxtjs/style-resources` but I'm not sure how to make this work in Nuxt 3.\n\nHowever, classes and applied styles from that stylesheet are working, only varibles, mixins and maps are not accessible.\n\nCan someone please help?\n\n========================================\n\nTop Answer:\nI'm using Nuxt 3 with TS setup and today is February 16, 2023 in the US. After trying many different variations, it would not work for me without the semi-colon at end of _variables.scss although I do agree with Juan, that first line of import { defineNuxtConfig } from nuxt3 is not needed.\n\n```\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n app: {\n head: {\n htmlAttrs: { lang: \"en\" },\n },\n },\n css: [\"@/assets/styles/main.scss\"],\n vite: {\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: '@import \"@/assets/styles/_variables.scss\";',\n },\n },\n },\n },\n});\n```\n\nImage of my IDE and terminal messages\n\n========================================\n\nCode:\n```js\nimport { defineNuxtConfig } from \"nuxt3\";\n\nexport default defineNuxtConfig({\n css: [\"@/assets/styles/main.sass\"],\n styleResources: {\n sass: [\"@/assets/styles/main.sass\"],\n },\n build: {\n extractCSS: true,\n styleResources: {\n sass: \"@/assets/styles/main.sass\",\n hoistUseStatements: true,\n },\n },\n // buildModules: [\"@nuxtjs/style-resources\"], // This throws error\n vite: {\n css: {\n loaderOptions: {\n sass: {\n additionalData: ` @import \"@/assets/styles/main.sass\"; `,\n },\n },\n },\n },\n});\n```\n\n```text\n/assets\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n[plugin:vite:css] Undefined variable.\n```\n\n```text\n@nuxtjs/style-resources\n```\n\n```js\nimport { defineNuxtConfig } from \"nuxt3\";\n\nexport default defineNuxtConfig({\n css: [\"@/assets/styles/main.sass\"],\n vite: {\n css: {\n preprocessorOptions: {\n sass: {\n additionalData: '@import \"@/assets/styles/_variables.sass\"',\n },\n },\n },\n },\n});\n```\n\n```text\nmain.sass\n```\n\n```text\n_variables.sass\n```\n\n```text\n_variables.sass\n```\n\n```text\n// nuxt.config.ts\nexport default {\n css: ['@/static/assets/scss/base.scss'],\n vite: {\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: '@import \"@/assets/style/global.sass\";'\n }\n }\n }\n }\n};\n```\n\n```text\ndefineNuxtConfig\n```\n\n```text\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n app: {\n head: {\n htmlAttrs: { lang: \"en\" },\n },\n },\n css: [\"@/assets/styles/main.scss\"],\n vite: {\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: '@import \"@/assets/styles/_variables.scss\";',\n },\n },\n },\n },\n});\n```\n\n========================================\n\nComments:\n- As per the Docs, Nuxt loads preprocessor automatically. you might need to add the preprocessor.\n- I have `sass` and `sass-loader` installed in `package.json` and I'm using `` tag as well in the components. Still not working for some reason.\n- codesandbox.io/s/confident-saha-w4cpj\n- I'm not sure if I was able to set this up correctly, but let's try this. I think this is pretty the structure I've been working on.\n- In `app.vue`, we can try setting the `div` background to `$test` variable defined in the `main.sass`\n- This worked for me, but the problem is that I've just one Sass entry file (index.scss) wich is importing all the stuf (settings, utilities...) and it is not possible to add it in \"css\" and \"additionalData\" imports at the same time. I solved it adding an empty file called index.scss, importing it like so (css: [\"@/assets/styles/index.scss\"]), renaiming the file with all the imports to scssImports.scss and importing it like this (additionalData: '@import \"@/assets/styles/scssImports.scss\";'). There is any way to directly add the imports in the index.scss and get rid of the scssImports.scss?\n- The only difference between my answer and @bacon-delight 's answer is the semi-colon at the end of additionalData: '@import \"@/assets/styles/_variables.scss\";',\n- You can edit your answer, and It won't work without semicolon?\n- Compare your answer to the second answer written by Juan. He has semicolon too.\n- Thanks for bringing that to my attention @Mises. I missed that.","metadata":{"transformedAt":"2026-08-18T18:33:07.849Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":199,"estimatedTokens":1345}}226{"id":"stack-72493908","source":"stackoverflow","questionId":72493908,"title":"How to write unit test for components with vitest in Nuxt 3?","tags":["vue.js","unit-testing","nuxt.js","nuxt3.js","vitest"],"text":"Title: How to write unit test for components with vitest in Nuxt 3?\nTags: vue.js, unit-testing, nuxt.js, nuxt3.js, vitest\nSource: Stack Overflow\n\nQuestion:\nI'm trying to migrate from Vue 3 to **Nuxt 3**. I've written unit tests for my components using vitest which are *working fine* in my *Vue* app, but the same test in the Nuxt app give me the following error:\n\nError: Failed to parse source for import analysis because the content contains invalid JS syntax.\n\nInstall @vitejs/plugin-vue to handle .vue files.\n\nI've installed `@vitejs/plugin-vue` as a development dependency but nothing happened.\n\nHere is an example of my test files:\n\n```\nimport { describe, it, expect } from \"vitest\";\n\nimport { mount } from \"@vue/test-utils\";\nimport AtomsButton from \"./AtomsButton.vue\";\n\ndescribe(\"AtomsButton\", () => {\n it(\"button renders properly\", () => {\n const wrapper = mount(AtomsButton, { slots: { default: \"Button\" } });\n expect(wrapper.html()).toContain(\"Button\");\n });\n});\n```\n\nHere is my `package.json` file:\n\n```\n{\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\",\n \"test:unit\": \"vitest --environment jsdom\"\n },\n \"devDependencies\": {\n \"@nuxt/test-utils-edge\": \"^3.0.0-rc.3-27571095.9379606\",\n \"@vitejs/plugin-vue\": \"^2.3.3\",\n \"@vue/test-utils\": \"^2.0.0\",\n \"jsdom\": \"^19.0.0\",\n \"nuxt\": \"3.0.0-rc.3\",\n \"vitest\": \"^0.13.1\"\n }\n}\n```\n\nI have no idea what am I doing wrong. Any help would be appreciated.\n\nHere is the reproduction link\n\n========================================\n\nCode:\n```js\nimport { describe, it, expect } from \"vitest\";\n\nimport { mount } from \"@vue/test-utils\";\nimport AtomsButton from \"./AtomsButton.vue\";\n\ndescribe(\"AtomsButton\", () => {\n it(\"button renders properly\", () => {\n const wrapper = mount(AtomsButton, { slots: { default: \"Button\" } });\n expect(wrapper.html()).toContain(\"Button\");\n });\n});\n```\n\n```json\n{\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\",\n \"test:unit\": \"vitest --environment jsdom\"\n },\n \"devDependencies\": {\n \"@nuxt/test-utils-edge\": \"^3.0.0-rc.3-27571095.9379606\",\n \"@vitejs/plugin-vue\": \"^2.3.3\",\n \"@vue/test-utils\": \"^2.0.0\",\n \"jsdom\": \"^19.0.0\",\n \"nuxt\": \"3.0.0-rc.3\",\n \"vitest\": \"^0.13.1\"\n }\n}\n```\n\n```text\n@vitejs/plugin-vue\n```\n\n```text\npackage.json\n```\n\n```text\n{\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"test:unit\": \"vitest --config ./vitest.config.js\",\n \"preview\": \"nuxt preview\"\n },\n \"devDependencies\": {\n \"@nuxtjs/tailwindcss\": \"^5.1.2\",\n \"@vitejs/plugin-vue\": \"^2.3.3\",\n \"@vue/test-utils\": \"^2.0.0\",\n \"jsdom\": \"^19.0.0\",\n \"nuxt\": \"3.0.0-rc.4\",\n \"vitest\": \"^0.14.2\"\n }\n}\n```\n\n```text\nimport vue from '@vitejs/plugin-vue';\n\nexport default {\n plugins: [vue()],\n test: {\n globals: true,\n environment: 'jsdom',\n },\n}\n```\n\n```text\npackage.json\n```\n\n```text\nvitest.config.js\n```\n\n========================================\n\nComments:\n- @tony19 Here is the reproduction link: stackblitz.com/edit/…\n- And how to handle the Nuxt 3 auto imports? Because with this config I need to import all the components or Vue dependencies like ref or reactive.","metadata":{"transformedAt":"2026-08-18T18:33:07.850Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":147,"estimatedTokens":828}}227{"id":"stack-55389600","source":"stackoverflow","questionId":55389600,"title":"Nuxt.js: How to use the same page with different URLs and switch the components to be displayed according to the URL","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Nuxt.js: How to use the same page with different URLs and switch the components to be displayed according to the URL\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to implement the following in Nuxt.js:\n\n1.Use the same page with different URLs.\n\nSpecifically, I want to use `/pages/users/_userId.vue` with`/users/{userId}`, `/users/{userId}/` and `/users/{userId}/follower`.\n\nI examined this and there were the following issues.\n\n- https://github.com/nuxt/nuxt.js/issues/2693\n\nBut it was a little different from what I wanted to achieve.\n\nI want to use the pass parameter for the query parameter.\n\n**2.Identify the components to display by path parameters**\n\nIt would be quicker to have a look at the code here.\n\n・/pages/users/_userId.vue`\n\n```\n\n \n \n \n \n -> use if URL /users /{userId}\n -> use if URL /users/{userId}/\n -> use if URL /users/{userId}/follower\n \n \n \n\nimport UserInfo from '~/components/organisms/users/UserInfo'\nimport PostsSection from '~/components/organisms/users/PostsSection'\nimport FollowSection from '~/components/organisms/users/FollowSection'\nimport FollowerSection from '~/components/organisms/users/FollowerSection'\n```\n\n...\n\nWhat should I do to achieve these?\n\n========================================\n\nTop Answer:\nAll your paths have a common prefix `users/`. So you can use the `pages/users/_.vue` component to match any path starting with the `users/` that was not matched to any other component.\n\nIn this component you can examine `$nuxt.$route.params.pathMatch` to decide, which subcomponent to show. It will contain part of path after `users/`:\n\n```\n\n \n \n \n \n \n \n \n \n \n \n\nexport default {\n computed: {\n path() {\n return this.$nuxt.$route.params.pathMatch;\n },\n },\n ...\n};\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div class=\"user\">\n <div class=\"user__contents\">\n <div class=\"user__contents__main\">\n <UserInfo/>\n <PostSection/> -> use if URL /users /{userId}\n <FollowSection/> -> use if URL /users/{userId}/follow\n <FollowerSection/> -> use if URL /users/{userId}/follower\n </div>\n </div>\n </div>\n</template>\n\n<script>\nimport UserInfo from '~/components/organisms/users/UserInfo'\nimport PostsSection from '~/components/organisms/users/PostsSection'\nimport FollowSection from '~/components/organisms/users/FollowSection'\nimport FollowerSection from '~/components/organisms/users/FollowerSection'\n```\n\n```text\n/pages/users/_userId.vue\n```\n\n```text\n/users/{userId}\n```\n\n```text\n/users/{userId}/follow\n```\n\n```text\n/users/{userId}/follower\n```\n\n```text\npages/\n--| users/\n-----| _id/\n--------| follow.vue // contains FollowSection\n--------| follower.vue // contains FollowerSection\n--------| index.vue // contains UserProfile\n-----| _id.vue\n```\n\n```text\n// users/_id.vue\n<template>\n <div class=\"user\">\n <div class=\"user__contents\">\n <div class=\"user__contents__main\">\n <UserInfo>\n <NuxtChild \n :user=\"user\"\n @custom-event=\"customEventHandler\"\n />\n </div>\n </div>\n </div>\n<template>\n```\n\n```text\n// pages/users/_id/follower.vue\n\n<script>\n // don't create a template for the section\nimport FollowSection from '~/components/organisms/users/FollowSection'\nexport default FollowSection\n</script>\n```\n\n```text\n_id.vue\n```\n\n```text\npages/\n--| users/\n-----| _id/\n--------| follow.vue\n--------| follower.vue\n-----| _id.vue\n```\n\n```text\n<template>\n <div class=\"user\">\n <div class=\"user__contents\">\n <div class=\"user__contents__main\">\n <UserInfo />\n <PostSection v-if=\"/^\\d+$/.test(path)\" />\n <FollowSection v-else-if=\"/^\\d+\\/follow$/.test(path)\" />\n <FollowerSection v-else-if=\"/^\\d+\\/follower$/.test(path)\" />\n </div>\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n computed: {\n path() {\n return this.$nuxt.$route.params.pathMatch;\n },\n },\n ...\n};\n</script>\n```\n\n```text\nusers/\n```\n\n```text\npages/users/_.vue\n```\n\n```text\nusers/\n```\n\n```text\n$nuxt.$route.params.pathMatch\n```\n\n```text\nusers/\n```\n\n========================================\n\nComments:\n- That is not an optimal solution. Having the same .vue page twice is difficult to maintain.\n- I get a syntax error when trying to do this. Nuxt 2.14.6 `Syntax Error: Unexpected token, expected \"{\"`. Doesnt seem to like exporting the import.\n- It should be `export default FollowSection` instead of `export FollowSection`\n- Hello! I'm reusing pages but I still need to set a parameter, like a prop ou data before instance starts somethins like import index from \"~/pages/blog/_category/index.vue\" const a = index a.data().nome = \"Maralhiva\" export default a It didnt work but is there a way doing it?\n- @RobertoFonseca You can pass the data as a prop to ``. This will work on page component which accept the `nome` prop\n- Does this reload the page?","metadata":{"transformedAt":"2026-08-18T18:33:07.850Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":224,"estimatedTokens":1214}}228{"id":"stack-57959383","source":"stackoverflow","questionId":57959383,"title":"Nuxt: All pages show a warning \"Cannot stringify a function Object\", how do I find out where it is coming from?","tags":["nuxt.js"],"text":"Title: Nuxt: All pages show a warning \"Cannot stringify a function Object\", how do I find out where it is coming from?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a fairly large project everything works without any issues except for a warning. The warning shows \"Cannot stringify a function Object\" without any fnction name. So I am unable to figure out where it is coming from or what is causing it.\n\nI tried commenting out all the middlewares I have, plugins I have and even created a new page with base minimum skeleton code and yet this warning appears when I access it.\n\nWhat I am looking for is a way to find out the place or code where the warning is coming from?\n\nSorry, I can't my code. Its the whole project and I am not able to recreate the warning as well. So is it possible to figure it out?\n\n========================================\n\nTop Answer:\nTo clarify, Nuxt serializes state from server to client i.e. it passes state from asyncData, data, vuex store state from server to client. The package that throws this error is @nuxt/devalue used by Nuxt.\n\nTo resolve, make sure that state is plain object.\n\n========================================\n\nCode:\n```js\nexport const state = () => ({\nteacher: Object, // This was causing the warning\nprice: \"\",\n})\n```\n\n```js\ncyclical references (obj.self = obj)\nrepeated references ([value, value])\nundefined, Infinity, NaN, -0\nregular expressions\ndates\nMap and Set\n```\n\n```text\nJSON.stringify\n```\n\n```text\n@nuxt/devalue\n```\n\n```text\nJSON.stringify\n```\n\n```text\n@nuxt/devalue\n```\n\n```text\nObject\n```\n\n```text\nString\n```\n\n========================================\n\nComments:\n- its something that is data from server to client. So look at your data of components, asyncData, and store state. Somewhere in it you will have function instead of object or value.\n- @Aldarund thanks a lot. If you put this as an answer, I will mark it as solved. This was all I needed to figure out what was causing it. I was setting a state as an Object like `profileDetails: Object` as the default state.\n- what is this for a weird answer and why is it accepted? What needs to be checked?\n- @Denzorrr what weird? pretty clear. state should be plain objects. that's it\n- that explained is much better :)","metadata":{"transformedAt":"2026-08-18T18:33:07.850Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":71,"estimatedTokens":560}}229{"id":"stack-68663581","source":"stackoverflow","questionId":68663581,"title":"Latest Nuxt v2.15.7 install with babel \"loose\" option warnings","tags":["vue.js","nuxt.js","babeljs"],"text":"Title: Latest Nuxt v2.15.7 install with babel \"loose\" option warnings\nTags: vue.js, nuxt.js, babeljs\nSource: Stack Overflow\n\nQuestion:\nI've created a brand new project with `npx create-nuxt-app my-cool-project` but I do have some errors when running `yarn dev`.\n\nThough the \"loose\" option was set to \"false\" in your @babel/preset-env config, it will not be used for @babel/plugin-proposal-private-property-in-object since the \"loose\" mode option was set to \"true\" for @babel/plugin-proposal-private-methods.\nThe \"loose\" option must be the same for @babel/plugin-proposal-class-properties, @babel/plugin-proposal-private-methods and @babel/plugin-proposal-private-property-in-object (when they are enabled): you can silence this warning by explicitly adding\n[\"@babel/plugin-proposal-private-property-in-object\", { \"loose\": true }]\nto the \"plugins\" section of your Babel config.\n\nDo you have any idea about this one? It reminds me of this other issue: Nuxt js - Fresh install of nuxt 2.14.6 contains babel \"loose option\" warnings\n\n========================================\n\nTop Answer:\nAs for me helps this modification on answer above:\n\n```\nyarn add --dev @babel/plugin-proposal-class-properties @babel/plugin-proposal-private-methods @babel/plugin-proposal-private-property-in-object\n```\n\nThen change `nuxt.config.js`:\n\n```\nbuild: {\n babel:{\n plugins: [\n ['@babel/plugin-proposal-class-properties', { loose: true }],\n ['@babel/plugin-proposal-private-methods', { loose: true }],\n ['@babel/plugin-proposal-private-property-in-object', { loose: true }]\n ]\n }\n},\n```\n\n========================================\n\nCode:\n```text\nnpx create-nuxt-app my-cool-project\n```\n\n```text\nyarn dev\n```\n\n```js\nbuild: {\n babel: {\n plugins: [\n '@babel/plugin-proposal-class-properties',\n '@babel/plugin-proposal-private-methods',\n\n // or with JUST the line below \n ['@babel/plugin-proposal-private-property-in-object', { loose: true }]\n ],\n },\n}\n```\n\n```text\n2.15.5\n```\n\n```text\n2.15.7\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nyarn add --dev @babel/plugin-proposal-class-properties @babel/plugin-proposal-private-methods @babel/plugin-proposal-private-property-in-object\n```\n\n```js\nbuild: {\n babel:{\n plugins: [\n ['@babel/plugin-proposal-class-properties', { loose: true }],\n ['@babel/plugin-proposal-private-methods', { loose: true }],\n ['@babel/plugin-proposal-private-property-in-object', { loose: true }]\n ]\n }\n},\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- The issue might have been fixed for 3 years indeed. Anyway, you should use Nuxt3.","metadata":{"transformedAt":"2026-08-18T18:33:07.850Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":98,"estimatedTokens":654}}230{"id":"stack-57676974","source":"stackoverflow","questionId":57676974,"title":"How to create dynamic 'Breadcrumbs' in Nuxt.js","tags":["vue.js","vue-router","nuxt.js"],"text":"Title: How to create dynamic 'Breadcrumbs' in Nuxt.js\nTags: vue.js, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHello guys Im trying to create dynamic 'Breadcrumbs' in Nuxt.js, Does anyone have a working example how it should work\n\nI have tried creating a simple sample but it is not working as expected, does anyone have a working solution ??\n\n```\n\n \n \n \n Test\n \n \n \n\nexport default {\n computed: {\n breadcrumbs() {\n console.log( this.$route.matched);\n return this.$route.matched;\n },\n },\n};\n\n```\n\n========================================\n\nTop Answer:\nPerhaps someone will need my experience with breadcrumbs on nuxt.js + vuetify.js.\n\n```\n\n \n \n \n \n mdi-arrow-left\n \n \n Back\n \n\n \n \n\nexport default {\n computed: {\n crumbs() {\n const fullPath = this.$route.fullPath\n const params = fullPath.substring(1).split('/')\n params.pop()\n const crumbs = []\n let path = ''\n \n params.forEach((param, index, { length }) => {\n path = `${path}/${param}`\n const match = this.$router.match(path)\n console.log(path)\n if (match.name !== 'index') {\n if (index === length - 1) {\n crumbs.push({\n text: path.replace(/\\//g, '-').slice(1),\n disabled: true,\n })\n } else {\n crumbs.push({\n text: path.replace(/\\//g, '-').slice(1),\n disabled: false,\n href: path + '/',\n })\n }\n }\n })\n\n return crumbs\n },\n },\n}\n\n```\n\nOptionally, you can add nuxt-i18n here\n\n```\n\nexport default {\n computed: {\n crumbs() {\n const fullPath = this.$route.fullPath\n const params = fullPath.substring(1).split('/')\n params.pop()\n const crumbs = []\n let path = ''\n \n params.forEach((param, index, { length }) => {\n path = `${path}/${param}`\n const match = this.$router.match(path)\n console.log(path)\n if (match.name !== 'index') {\n if (index === length - 1) {\n crumbs.push({\n text: this.$i18n.t('breadcrumbs.' + path.replace(/\\//g, '_').slice(1)),\n disabled: true,\n })\n } else {\n crumbs.push({\n text: this.$i18n.t('breadcrumbs.' + path.replace(/\\//g, '_').slice(1)),\n disabled: false,\n href: path + '/',\n })\n }\n }\n })\n\n return crumbs\n },\n },\n}\n\n```\n\n========================================\n\nCode:\n```html\n<template>\n <div class=\"breadcrumbs-component-wrapper\">\n <b-breadcrumb class=\"breadcrumbs-holder\">\n <b-breadcrumb-item\n v-for=\"(item, i) in breadcrumbs\"\n :key=\"i\"\n :to=\"item.name\"\n >\n Test\n </b-breadcrumb-item>\n </b-breadcrumb>\n </div>\n</template>\n\n<script>\nexport default {\n computed: {\n breadcrumbs() {\n console.log( this.$route.matched);\n return this.$route.matched;\n },\n },\n};\n</script>\n```\n\n```html\n<template>\n <div class=\"level\">\n <div class=\"level-left\">\n <div class=\"level-item\">\n <a class=\"button is-white\" @click=\"$router.back()\">\n <b-icon icon=\"chevron-left\" size=\"is-medium\" />\n </a>\n </div>\n <div class=\"level-item\">\n <nav class=\"breadcrumb\" aria-label=\"breadcrumbs\">\n <ul>\n <li v-for=\"(item, i) in crumbs\" :key=\"i\" :class=\"item.classes\">\n <nuxt-link :to=\"item.path\">\n {{ item.name }}\n </nuxt-link>\n </li>\n </ul>\n </nav>\n </div>\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n computed: {\n crumbs() {\n const crumbs = []\n this.$route.matched.forEach((item, i, { length }) => {\n const crumb = {}\n crumb.path = item.path\n crumb.name = this.$i18n.t('route.' + (item.name || item.path))\n\n // is last item?\n if (i === length - 1) {\n // is param route? .../.../:id\n if (item.regex.keys.length > 0) {\n crumbs.push({\n path: item.path.replace(/\\/:[^/:]*$/, ''),\n name: this.$i18n.t('route.' + item.name.replace(/-[^-]*$/, ''))\n })\n crumb.path = this.$route.path\n crumb.name = this.$i18n.t('route.' + this.$route.name, [\n crumb.path.match(/[^/]*$/)[0]\n ])\n }\n crumb.classes = 'is-active'\n }\n\n crumbs.push(crumb)\n })\n\n return crumbs\n }\n }\n}\n</script>\n\n<style lang=\"scss\" scoped>\n/deep/ a {\n @include transition();\n}\n</style>\n```\n\n```html\n<template>\n <div class=\"d-inline-flex items-center\" v-if=\"crumbs.length != 0\">\n <v-tooltip bottom>\n <template v-slot:activator=\"{ on, attrs }\">\n <v-btn\n small\n text\n plain\n fab\n v-bind=\"attrs\"\n v-on=\"on\"\n @click=\"$router.back()\"\n >\n <v-icon>mdi-arrow-left</v-icon>\n </v-btn>\n </template>\n <span>Back</span>\n </v-tooltip>\n\n <v-breadcrumbs class=\"py-0\" :items=\"crumbs\"></v-breadcrumbs>\n </div>\n</template>\n\n<script>\nexport default {\n computed: {\n crumbs() {\n const fullPath = this.$route.fullPath\n const params = fullPath.substring(1).split('/')\n params.pop()\n const crumbs = []\n let path = ''\n \n params.forEach((param, index, { length }) => {\n path = `${path}/${param}`\n const match = this.$router.match(path)\n console.log(path)\n if (match.name !== 'index') {\n if (index === length - 1) {\n crumbs.push({\n text: path.replace(/\\//g, '-').slice(1),\n disabled: true,\n })\n } else {\n crumbs.push({\n text: path.replace(/\\//g, '-').slice(1),\n disabled: false,\n href: path + '/',\n })\n }\n }\n })\n\n return crumbs\n },\n },\n}\n</script>\n```\n\n```html\n<script>\nexport default {\n computed: {\n crumbs() {\n const fullPath = this.$route.fullPath\n const params = fullPath.substring(1).split('/')\n params.pop()\n const crumbs = []\n let path = ''\n \n params.forEach((param, index, { length }) => {\n path = `${path}/${param}`\n const match = this.$router.match(path)\n console.log(path)\n if (match.name !== 'index') {\n if (index === length - 1) {\n crumbs.push({\n text: this.$i18n.t('breadcrumbs.' + path.replace(/\\//g, '_').slice(1)),\n disabled: true,\n })\n } else {\n crumbs.push({\n text: this.$i18n.t('breadcrumbs.' + path.replace(/\\//g, '_').slice(1)),\n disabled: false,\n href: path + '/',\n })\n }\n }\n })\n\n return crumbs\n },\n },\n}\n</script>\n```\n\n```text\nconst getBreadcrumbs = () => {\n const route = useRoute()\n\n const pathArray = route.path.split('/')\n pathArray.shift()\n const breadcrumbs = pathArray.reduce((breadcrumbArray, path, idx) => {\n breadcrumbArray.push({\n to: !!breadcrumbArray[idx - 1]\n ? breadcrumbArray[idx - 1].to + '/' + path\n : '/' + path,\n title: path.toString().replace('-', ' '),\n })\n return breadcrumbArray\n }, [])\n return breadcrumbs\n}\n```\n\n```text\n<script setup>\nconst route = useRoute();\nconst router = useRouter();\n\nconst crumbsRoute = computed(() => {\n let fullPath = \"\";\n const routes = route.fullPath.substring(1).split(\"/\");\n return routes\n .map((route) => {\n if (route) {\n fullPath = `${fullPath}/${route}`;\n return router.resolve(fullPath);\n }\n })\n .filter(Boolean);\n});\n</script>\n```\n\n```text\n<template>\n <ul class=\"flex items-center\">\n <li\n v-for=\"(crumb, index) in crumbsRoute\"\n :key=\"crumb.name\"\n class=\"flex items-center gap-2\">\n <base-icon\n icon-path=\"Arrow\"\n svg-class=\"w-4\"\n class=\"stroke-beta-gray-100\"></base-icon>\n <nuxt-link\n :to=\"{ name: crumb.name }\"\n class=\"text-beta-gray-150\"\n :class=\"{ 'text-beta-gray-500': index === crumbsRoute.length - 1 }\"\n >{{ crumb.meta.breadcrumbs }}</nuxt-link\n >\n </li>\n </ul>\n</template>\n```\n\n```text\n// in this page => localhost:3000/about-us/ \ndefinePageMeta({\n name: \"aboutUs\",\n breadcrumbs: \"about us\",\n});\n```\n\n```text\ndefinePageMeta()\n```\n\n========================================\n\nComments:\n- see github.com/pratheekhegde/vue-dynamic-breadcrumbs/blob/master‌​/…\n- Thanx, but I already saw that and it is not working as expected in my case :(\n- единственный рабочий вариант для nuxt 3","metadata":{"transformedAt":"2026-08-18T18:33:07.850Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":400,"estimatedTokens":2075}}231{"id":"stack-59973709","source":"stackoverflow","questionId":59973709,"title":"Using Environment Variables in nuxt.config.js","tags":["node.js","axios","environment-variables","nuxt.js"],"text":"Title: Using Environment Variables in nuxt.config.js\nTags: node.js, axios, environment-variables, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt & Axios but having trouble using environment variables when **building** the application from my **local machine**. \n\nI have installed the @nuxtjs/dotenv module in an attempt to fix this issue but still having problems.\n\nNote: The environment variables work fine when building the app within my hosting providers environment. It is only building from my local machine that gives me trouble. My IDE is VS Code.\n\nHere is my axios setup inside nuxt.config.js:\n\n```\nmodule.exports = {\n ...\n buildModules: [\n '@nuxtjs/dotenv'\n ],\n modules: [\n // Doc: https://axios.nuxtjs.org/usage\n '@nuxtjs/axios'\n ],\n axios: {\n baseURL: process.env.BASE_URL\n },\n ...\n}\n```\n\nMy .env file has the following:\n\n```\nBASE_URL=\"https://some.api.com\"\n```\n\nThe .env variables are not being recognized when building the app:\n\n```\nnuxt build\n```\n\nInstead, it just sets the axios base url to the same host:port that the server runs on by default. Ex: localhost:4000\n\nI found the following documentation from @nuxtjs/dotenv module: https://github.com/nuxt-community/dotenv-module#using-env-file-in-nuxtconfigjs. This instructs you to add the following to the top of nuxt.config.js: \n\n```\nrequire('dotenv').config()\n```\n\nThis works for building locally; my variables from .env are recognized! However, because dotenv is a dev dependency, this causes the build to crash when deployed to my hosting provider because the module isn't recognized.\n\nI know that I can define the environment variables directly in the build command as follows but **I would prefer NOT to do so**:\n\n```\nNUXT_ENV_BASE_URL=some.api.com nuxt build\n```\n\nIs there an easy way to get environment variables to work locally inside of nuxt.config.js during the build process that also works well when deploying to production??\n\nThank you!\n\n========================================\n\nTop Answer:\nIn nuxt version v2.13.0, support for `Runtime Config` was added. This adds proper support to read environment variables at runtime. Previously they could be read but were compiled into the application.\n\nThe standard documentation is pretty good: https://nuxtjs.org/guide/runtime-config/ .\nThere is also a great blog post on how to migrate. You remove the use of `@nuxtjs/dotenv`.\n\nhttps://nuxtjs.org/blog/moving-from-nuxtjs-dotenv-to-runtime-config/\n\nFor example, in your nuxt.config.js, you define.\n\n```\n// Public env variables that are exposed on the frontend.\n publicRuntimeConfig: {\n someAccessKeyId: process.env.SOME_ACCESS_KEY_ID,\n },\n // Private env variables that are not be exposed on the frontend.\n privateRuntimeConfig: {},\n```\n\nThen in your vue code, you access it via.\n\n```\nconst { someAccessKeyId } = this.$config\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n ...\n buildModules: [\n '@nuxtjs/dotenv'\n ],\n modules: [\n // Doc: https://axios.nuxtjs.org/usage\n '@nuxtjs/axios'\n ],\n axios: {\n baseURL: process.env.BASE_URL\n },\n ...\n}\n```\n\n```text\nBASE_URL=\"https://some.api.com\"\n```\n\n```text\nnuxt build\n```\n\n```text\nrequire('dotenv').config()\n```\n\n```text\nNUXT_ENV_BASE_URL=some.api.com nuxt build\n```\n\n```text\nenv: {\n DB_HOST: process.env.DB_HOST\n},\n```\n\n```text\nDB_HOST=http://localhost:5001/\n```\n\n```text\nimport dotenv from \"dotenv\";\ndotenv.config();\n\nenv: {\n DB_HOST: process.env.DB_HOST\n},\n```\n\n```text\nDB_HOST=http://localhost:5001/\n```\n\n```text\n// Public env variables that are exposed on the frontend.\n publicRuntimeConfig: {\n someAccessKeyId: process.env.SOME_ACCESS_KEY_ID,\n },\n // Private env variables that are not be exposed on the frontend.\n privateRuntimeConfig: {},\n```\n\n```text\nconst { someAccessKeyId } = this.$config\n```\n\n```text\nRuntime Config\n```\n\n```text\n@nuxtjs/dotenv\n```\n\n========================================\n\nComments:\n- did you ever get this resolved? I am having the same problem.\n- Nope, not yet. Sorry\n- I found a working solution after asking this. I added it below.\n- I did the same exact thing yesterday and it didn't work. I did it today and now it works. Well. Thank you I guess. Not sure if it's crucial, but I also have following code in my `nuxt.config.js`: `buildModules: [ '@nuxtjs/dotenv' ]` The last one is `@nuxtjs/dotenv`. My version is ^2.15, but it does work and i dont wanna touch it\n- How are you supposed to use RuntimeConfig inside of the nuxt.config.js file?\n- Those are just top level keys in `nuxt.config.js`. As I mentioned, then you can just refer to them in code as I described using `this.$config`.\n- I don't think you understand @Derek, How do I want to access `someAccessKeyId` in another part of the `nuxt.config.js` file\n- Oh. I haven't tried that. I guess you can always just go back and use the `process.env` directly if you need access to an env variable.\n- @Derek I am having the same issue, those values are just empty if you refer to them as process.env in for example your modules object below\n- How can we access variables from privateRuntimeConfig in a plugin ?\n- @derek this is spot on. I removed @nuxtjs/dotenv and then modified my nuxt.config.js to removing `import dotenv from \"dotenv\";` and `dotenv.config();` while leaving `env: { DB_HOST: process.env.DB_HOST },` and everything else works exactly the same.\n- did you ever get a solution @AndreOdendaal?\n- I cannot remember unfortunately @richardwhatever\n- I'm no longer actively working with nuxt so it's been a while. If you need to access `someAccessKeyId` in some other place in `nuxt.config.js` you probably can't directly. You should be able to reference `process.env.SOME_ACCESS_KEY_ID` though.\n- this problem was driving me crazy: I have the .env file in the root directory but with process.env.XXX I got always \"undefined\". I finally solved using your solution, thank you!\n- @StephenVernyi `How are you supposed to use RuntimeConfig inside of the nuxt.config.js file?` you don't, just use process.env","metadata":{"transformedAt":"2026-08-18T18:33:07.850Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":188,"estimatedTokens":1501}}232{"id":"stack-54459438","source":"stackoverflow","questionId":54459438,"title":"Nuxt 404 error page should redirect to homepage","tags":["vue.js","seo","nuxt.js"],"text":"Title: Nuxt 404 error page should redirect to homepage\nTags: vue.js, seo, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am looking for a way to always redirect to homepage when a page doesn't exist using Nuxt.Js. \n\nOur sitemap generation had some problems a few days back and we submitted wrong urls that do not exist. Google Search Console shows a big number of 404 and we want to fix them with 301 redirect to homepage.\n\nI tried this \n\n```\ncreated() {\n this.$router.push(\n this.localePath({\n name: 'index',\n query: {\n e: 'er'\n }\n })\n )\n }\n```\n\nand although the page redirects to homepage successfully I think Google will have problems with this since the pages initially renders with 404.\n\nI also tried this \n\n```\nasync asyncData({ redirect }) {\n return redirect(301, '/el?e=rnf')\n },\n```\n\nbut didn't work (same with fetch)\n\nAny ideas on a solution to this?\n\n========================================\n\nTop Answer:\nNever redirect to home if page is not found as you can see in this Google's article: Create custom 404 pages\n\ninstead, redirect to 404 error page\n\nJust use `error`\n\n```\nasync asyncData({ params, $content, error }) {\n try {\n const post = await $content('blog', params.slug).fetch()\n return { post }\n } catch (e) {\n error({ statusCode: 404, message: 'Post not found' })\n }\n }\n```\n\ndo not forget to creat an error page in layout folder `error.vue`\n\n========================================\n\nCode:\n```text\ncreated() {\n this.$router.push(\n this.localePath({\n name: 'index',\n query: {\n e: 'er'\n }\n })\n )\n }\n```\n\n```text\nasync asyncData({ redirect }) {\n return redirect(301, '/el?e=rnf')\n },\n```\n\n```text\n// !!! not tested this code !!!\nmiddleware: [\n function({ redirect }) {\n return redirect(301, '/el?e=rnf')\n },\n],\n```\n\n```text\nerror.vue\n```\n\n```text\nlayouts folder\n```\n\n```text\ndomain.com/<userID>\n```\n\n```text\n_.vue\n```\n\n```text\n~/pages/\n```\n\n```text\n<script>\nexport default {\n asyncData ({ redirect }) {\n return redirect('/')\n }\n}\n</script>\n```\n\n```text\n_.vue\n```\n\n```text\npages\n```\n\n```js\nasync asyncData({ params, $content, error }) {\n try {\n const post = await $content('blog', params.slug).fetch()\n return { post }\n } catch (e) {\n error({ statusCode: 404, message: 'Post not found' })\n }\n }\n```\n\n```text\nerror\n```\n\n```text\nerror.vue\n```\n\n========================================\n\nComments:\n- Have you tried the middleware for 404 with redirect?\n- @gleam No, how would I check that?\n- add middleware to 404-page. This middleware will only do 301-redirect. nuxtjs.org/api/pages-middleware\n- @gleam How would I only target 404 pages thought? I am not sure if I have access to the error object inside the middleware.\n- hm... i'll try to write an answer :)\n- I am looking for a better solution that will also work for child pages such as .com/test/test/test. Would that work in this case? :/\n- _.vue is global 404-error-page. It will work on any route (ex: /asd/asd/as/das/e/zxvc/s/wde/gw => _.vue => middleware => 301)\n- _.vue is also useful to prevent user to access an intermediate route too. Imagine you have a route like `/categories/:categoryId/benefits/:benefitId/details` and you do not want user to access `/categories/:categoryId/benefits/:benefitId`. All you need to do is to create a `_.vue` file at the same directory level of the route you want to ignore, in this case `/categories/_categoryId/benefits`","metadata":{"transformedAt":"2026-08-18T18:33:07.850Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":159,"estimatedTokens":866}}233{"id":"stack-68654928","source":"stackoverflow","questionId":68654928,"title":"Which one should I use: SSR, SPA only or SSG for my Nuxt project?","tags":["laravel","vue.js","vuejs2","nuxt.js"],"text":"Title: Which one should I use: SSR, SPA only or SSG for my Nuxt project?\nTags: laravel, vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI need to develop a website using laravel and nuxtjs.\nTo my knowledege, SSR mode is one of the advanced feature of the nuxtjs but it requires to run the nuxt server. In other words, we need to deploy the laravel on the server like nginx and have to run the nuxt server by using `npm run start`. If we use SPA mode, nuxt generate static page into dist directory and we can simply merge it to laravel project and everything is done. We don't need to run the extra server.\n\nThis is my opinion so far. I am not sure whether or not it is true, so I can't decide which one to choose. First of all, I am not sure which one is really better. Second, I am not sure if SSR mode really requires to run the extra server.\n\nI want to get advice from experts and make a decision. I'd be really grateful if you give me advice about this. Thanks in advance.\n\n========================================\n\nCode:\n```text\nnpm run start\n```\n\n```text\ntarget: static\n```\n\n```text\nssr: true\n```\n\n========================================\n\nComments:\n- Your premise is incorrect. SSR and SPA are not mutually exclusive. SPA is Single-page application which means you use a client-side \"router\" to transition between pages without making requests in a server. SSR means there's a server that will pre-render the application HTML so it can be loaded by a browser on initial load and users (and web crawlers) won't have to wait for the JS to arrive before they see the page. You obviously can use both at the same time and both require some sort of server to run. SSR requires a server that can execute JS though while SPA needs a server to serve HTML\n- Thank you. Does it mean we need to run an extra server for SSR mode? Like `npm run start`?\n- You need a server in both cases. However yes, in the case you have SSR you probably need a node.js server specifically (so using npm run start) while in the case where you only have an SPA then you only need to \"compile\" your javascript once and then serve it with a more basic server like e.g. an apache webserver or even an AWS S3 bucket. Also when you use SSR there might be some extra things to consider when writing code such as the `window` global might not be always available i.e. when the code is being rendered server-side\n- Thank you. That was crystal clear. I need to merge the compiled content to laravel project(Laravel is deployed on the nginx server). Do I still need to run the node sever? For SSR mode?\n- That is an opinionated question, but I don't dare to flag it because I've been there and I know that's a very important decision to make which requires expertise.\n- Thank you. That's what I wanted to know. I wanted to use the SEO advantage of the SSR but did not want to run an extra server for that.\n- So can it merge with Laravel and just use LAMP stack?\n- @Fahmi not sure what you're asking here. Add Nuxt inside of a Laravel app? Feel free to post a new question with all the details!\n- @kissu: i'm using SSG, and my SEO is dead :( All dynamics METAS are empty...\n- @VinParker depends how you are doing those. Feel free to post a new question.\n- @kissu you right. Thanks for helping me ;) ;) stackoverflow.com/questions/72740872/dynamic-meta-seo-with-n‌​uxt","metadata":{"transformedAt":"2026-08-18T18:33:07.850Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":41,"estimatedTokens":839}}234{"id":"stack-75949400","source":"stackoverflow","questionId":75949400,"title":"Adding property 'css:[]' in Nuxt 3 resulting in Typescript error","tags":["typescript","nuxt.js","vuejs3","vue-composition-api","nuxt3.js"],"text":"Title: Adding property 'css:[]' in Nuxt 3 resulting in Typescript error\nTags: typescript, nuxt.js, vuejs3, vue-composition-api, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt3/Typescript/CompositionAPI..\nWhy does my `nuxt.config.ts` keep giving me errors when I want to use for example the 'css:'?\nRight now this is my `nuxt.config.ts`:\n\n```\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n css: [\n '~/assets/css/global.css',\n ],\n modules: [\n '@nuxtjs/tailwindcss',\n '@nuxtjs/google-fonts',\n '@formkit/nuxt',\n '@nuxtjs/eslint-module',\n // Pinia\n // i18n\n ],\n tailwindcss: {\n cssPath: '~/assets/css/tailwind.css',\n configPath: 'tailwind.config',\n },\n googleFonts: {\n families: {\n 'Plus+Jakarta+Sans': true,\n },\n },\n});\n```\n\nOnly the css:[] is giving the error:\n\n`TS2345: Argument of type '{ app: {}; modules: string[]; tailwindcss: { cssPath: string; configPath: string; }; googleFonts: { families: { 'Plus+Jakarta+Sans': true; }; }; }' is not assignable to parameter of type 'NuxtConfig'. Object literal may only specify known properties, and 'app' does not exist in type 'NuxtConfig'.`\n\nThis is my `package.json`:\n\n```\n\"devDependencies\": {\n \"@nuxtjs/eslint-module\": \"^4.0.2\",\n \"@nuxtjs/google-fonts\": \"^3.0.0\",\n \"@nuxtjs/tailwindcss\": \"^6.6.5\",\n \"eslint\": \"^8.37.0\",\n \"eslint-plugin-tailwindcss\": \"^3.10.3\",\n \"nuxt\": \"^3.3.3\"\n },\n \"dependencies\": {\n \"@formkit/addons\": \"^0.16.4\",\n \"@formkit/nuxt\": \"^0.16.4\",\n \"@formkit/themes\": \"^0.16.4\",\n \"@formkit/vue\": \"^0.16.4\",\n \"@nuxtjs/eslint-config-typescript\": \"^12.0.0\"\n }\n```\n\nGood to mention, this is working so no errors on the localhost. But its just returning the error in my IDE when I hover over it.\n\nThe docs: https://nuxt.com/docs/api/configuration/nuxt-config#css.\nI am kinda new to setting up new Nuxt projects. Please, let me know if you need anything else.\n\nThanks\n\n========================================\n\nTop Answer:\nI had a similar issue while using VS code, and fixed the problem by changing the typescript version to the Workspace version.\n\nhttps://i.sstatic.net/o8PNf.png\n\n========================================\n\nCode:\n```text\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n css: [\n '~/assets/css/global.css',\n ],\n modules: [\n '@nuxtjs/tailwindcss',\n '@nuxtjs/google-fonts',\n '@formkit/nuxt',\n '@nuxtjs/eslint-module',\n // Pinia\n // i18n\n ],\n tailwindcss: {\n cssPath: '~/assets/css/tailwind.css',\n configPath: 'tailwind.config',\n },\n googleFonts: {\n families: {\n 'Plus+Jakarta+Sans': true,\n },\n },\n});\n```\n\n```text\n\"devDependencies\": {\n \"@nuxtjs/eslint-module\": \"^4.0.2\",\n \"@nuxtjs/google-fonts\": \"^3.0.0\",\n \"@nuxtjs/tailwindcss\": \"^6.6.5\",\n \"eslint\": \"^8.37.0\",\n \"eslint-plugin-tailwindcss\": \"^3.10.3\",\n \"nuxt\": \"^3.3.3\"\n },\n \"dependencies\": {\n \"@formkit/addons\": \"^0.16.4\",\n \"@formkit/nuxt\": \"^0.16.4\",\n \"@formkit/themes\": \"^0.16.4\",\n \"@formkit/vue\": \"^0.16.4\",\n \"@nuxtjs/eslint-config-typescript\": \"^12.0.0\"\n }\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nTS2345: Argument of type '{ app: {}; modules: string[]; tailwindcss: { cssPath: string; configPath: string; }; googleFonts: { families: { 'Plus+Jakarta+Sans': true; }; }; }' is not assignable to parameter of type 'NuxtConfig'. Object literal may only specify known properties, and 'app' does not exist in type 'NuxtConfig'.\n```\n\n```text\npackage.json\n```\n\n```text\nnuxt dev\n```\n\n```text\nnuxt build\n```\n\n========================================\n\nComments:\n- try npx nuxi prepare to generate types\n- Didn't solve the problem unfortunately.. Output: `Nuxi 3.3.3 09:16:41 ℹ Using Tailwind CSS from ~/assets/css/tailwind.css nuxt:tailwindcss 09:16:42 ✔ Types generated in .nuxt`\n- I think the reason is that Nuxt is not aware of \"tailwindcss\" or \"googleFonts\" as part of the config. See config options: nuxt.com/docs/api/configuration/nuxt-config Maybe there's a way to tell \"defineNuxtConfig\" that there's extra properties. But something that should work is to move the tailwind specific infos into \"tailwind.config.js\", see: tailwindcss.nuxtjs.org/tailwind/config\n- As I mentioned only the `css:[]` is giving the error.. First the \"tailwindcss\" and \"googleFonts\" gave the error too but after I ran `npm i` for both packages and restarted the server, the error disappeared for them. So right now only the `css:[]` is giving the error. Or am I using the wrong way to import a css file? Because this is an option too I think: nuxt.com/docs/api/configuration/nuxt-config#head\n- Would you be able to repro the issue in codesandbox or similar?\n- Don't think I can. Maybe my `package.json` could be usefull? Edited my answer..\n- That was it, using Typescript@4.9.5 now\n- It's also working for Typescript ^5, thanks for the suggestion!\n- ChatGPT, please pay attention to this one lol\n- That's what I was looking for....finally fixed after hours","metadata":{"transformedAt":"2026-08-18T18:33:07.850Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":157,"estimatedTokens":1243}}235{"id":"stack-69730244","source":"stackoverflow","questionId":69730244,"title":"How to get route parameters from Nuxt 3 server","tags":["typescript","server","nuxt.js","nuxt3.js"],"text":"Title: How to get route parameters from Nuxt 3 server\nTags: typescript, server, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI have one of the following API URLs. At the end of the day for my use case, it doesn't matter which of these URLs I would have to use, but currently neither work.\n\n```\nhttp://localhost:3000/api/track/TRACKID\n```\n\nor\n\n```\nhttp://localhost:3000/api/track?id=TRACKID\n```\n\nHow would I get `TRACKID` in the APIs code? The following code results in `undefined`.\n\n```\nexport default async (req: IncomingMessage, res: ServerResponse) => {\n console.log(req.id);\n};\n```\n\nI tried to set up the file for the first URL in the following way, but that was unsuccessful as well. It just resulted in the URL being `http://localhost:3000/api/track/[id]`\n\n```\nPROJECT/server/api/track/[id].ts\n```\n\nFor the second URL I used the following set up.\n\n```\nPROJECT/server/api/track.ts\n```\n\n========================================\n\nTop Answer:\nEdit: Updated my answer now that Nuxt 3 has released.\n\n```\nexport default defineEventListener(event => {\n const query = getQuery(event)\n})\n```\n\nhttps://github.com/unjs/h3 is the server putting the api together.\n\n========================================\n\nCode:\n```text\nhttp://localhost:3000/api/track/TRACKID\n```\n\n```text\nhttp://localhost:3000/api/track?id=TRACKID\n```\n\n```text\nexport default async (req: IncomingMessage, res: ServerResponse) => {\n console.log(req.id);\n};\n```\n\n```text\nPROJECT/server/api/track/[id].ts\n```\n\n```text\nPROJECT/server/api/track.ts\n```\n\n```text\nTRACKID\n```\n\n```text\nundefined\n```\n\n```text\nhttp://localhost:3000/api/track/[id]\n```\n\n```text\nimport * as url from \"url\";\n\nconst params = url.parse(req.url as string, true).query;\nconst {id} = params\n```\n\n```text\nexport default defineEventListener(event => {\n const query = getQuery(event)\n})\n```\n\n```text\nexport default defineEventHandler(async (event) => {\n const id = event.context.params.id;\n\n // Use the id here\n});\n```\n\n```js\nexport default defineEventListener(event => {\n const TRACKID = getRouterParam(event, 'TRACKID')\n})\n```\n\n```js\nexport default defineEventListener(event => {\n const { id } = getQuery(event)\n})\n```\n\n```text\nhttp://localhost:3000/api/track/:TRACKID\n```\n\n```text\nhttp://localhost:3000/api/track?id=TRACKID\n```\n\n========================================\n\nComments:\n- You should try with custom endpoint via Express : nuxtjs.org/docs/configuration-glossary/…\n- also check this: dev.to/dabit3/creating-api-routes-in-a-nuxt-app-1kg1\n- Does t his work with Nuxt 3? The stuff you linked seems to focus on Nuxt 2.\n- it does. give it a try.\n- Welcome to Stack Overflow, and thank you for contributing an answer. Would you kindly edit your answer to include an explanation of your code? That will help future readers better understand what is going on, and especially those members of the community who are new to the language and struggling to understand the concepts.\n- Is this the \"standard\" way to do this in nuxt 3? I couldn't find anything on the official docs\n- @cub33 check Curtis Rabon's answer.","metadata":{"transformedAt":"2026-08-18T18:33:07.850Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":138,"estimatedTokens":767}}236{"id":"stack-61934264","source":"stackoverflow","questionId":61934264,"title":"How to disable modal-ok slot of b-modal in vue bootstrap?","tags":["vue.js","nuxt.js","bootstrap-vue"],"text":"Title: How to disable modal-ok slot of b-modal in vue bootstrap?\nTags: vue.js, nuxt.js, bootstrap-vue\nSource: Stack Overflow\n\nQuestion:\nI have used `modal-ok` slot available in b-modal slots to render the OK button of b-modal. I want to conditionally disable the OK button. I have tried 2 methods with no luck. Any suggestion is welcome on how to disable the OK button rendered using the slot.\n\nDisabled prop\n\n```\n\n Upload\n \n```\n\nok-disabled prop of b-modal\n\n```\n\n Upload\n \n```\n\n========================================\n\nTop Answer:\nJust add hide-footer if you want to get rid of the buttons\n\n```\n\n \n\n```\n\n========================================\n\nCode:\n```text\n<div\n slot=\"modal-ok\"\n :disabled=\"true\"\n @click.stop=\"uploadFile(item.id)\"\n >\n Upload\n </div>\n```\n\n```text\n<div\n slot=\"modal-ok\"\n :ok-disabled=\"true\"\n @click.stop=\"uploadFile(item.id)\"\n >\n Upload\n </div>\n```\n\n```text\nmodal-ok\n```\n\n```text\nmodal-footer\n```\n\n```html\n<b-modal :ok-disabled=\"true\">\n <!-- Content -->\n</b-modal>\n```\n\n```text\nok-disabled\n```\n\n```text\n<b-modal>\n```\n\n```text\nok\n```\n\n```text\n<b-modal hide-footer>\n <!-- Content -->\n</b-modal>\n```\n\n========================================\n\nComments:\n- I haven't used the default ok-button of the b-modal. I have used modal-ok slot to render a custom ok-button. This answer is not relevant to that.\n- I'd argue that it is. Since the slot you're using only controls the content of the `ok` button. So this will still disable the button. What i don't quite understand though is *why* you're doing what you're doing. At least based on your code in the question, nothing there requires you to use the slot and could be done through the normal props.","metadata":{"transformedAt":"2026-08-18T18:33:07.851Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":94,"estimatedTokens":424}}237{"id":"stack-57568660","source":"stackoverflow","questionId":57568660,"title":"Using i18n in nuxt plugin","tags":["vue.js","plugins","translation","vuetify.js","nuxt.js"],"text":"Title: Using i18n in nuxt plugin\nTags: vue.js, plugins, translation, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using nuxt with vuetify and I defined all my validations rules (for text inputs) in a single file like this:\n\n```\n// @/plugins/form_validations.js\n\nexport default Object.freeze({\n VALIDATIONS: {\n\n FIRSTNAME: [\n v => !!v || 'Firstname is required',\n v => (v && v.length >= 3) || 'Firstname must be at least 3 characters'\n ],\n\n // ...\n})\n```\n\nI use them in my components like this:\n\n```\nimport FormValidations from '@/plugins/form_validations.js'\n\nexport default {\n data() {\n firstnameRules: FormValidations.VALIDATIONS.FIRSTNAME\n }\n}\n```\n\n```\n\n```\n\nI want now to translate the text of this rules depending of the locale. \n\nI have installed i18n following this example and can use it well in my components, for example like this:\n\n```\n\n```\n\nHowever, I'm not able to use the translation plugin directly in my file where I grouped all the rules. I have seen that with nuxt you can access the context in plugins as :\n\n```\nexport default ({ app, store }) => {\n}\n```\n\nBut I'm not able to define my constants using Object.freeze in that format. \n\nI tried also this:\n\n```\nimport i18n from '@/plugins/i18n.js'\n\nexport default Object.freeze({\n VALIDATIONS: {\n FIRSTNAME: [\n v => !!v || i18n.t('firstname_required'),\n ],\n}\n```\n\nBut I got an error that function *t* is not defined. How can I access the translation plugin in my rules?\n\n========================================\n\nTop Answer:\n2023 update: Nuxt 3, Vee-Validate 4.x, Nuxti18n 8.0.rc-5 version:\n\n```\nimport { configure, defineRule } from 'vee-validate'\nimport { localize } from '@vee-validate/i18n';\nimport * as AllRules from '@vee-validate/rules';\n\nimport en from '@vee-validate/i18n/dist/locale/en.json';\nimport ru from '@vee-validate/i18n/dist/locale/ru.json';\n\nexport default defineNuxtPlugin(nuxtApp => {\n const $t = nuxtApp.$i18n.t;\n Object.entries(AllRules).forEach(([id, validator]) => {\n defineRule(id, validator);\n });\n\n defineRule('ip', value => {\n if (!/((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}/g.test(value)) {\n return $t('errors.ip_invalid');\n }\n return true;\n });\n\n configure({\n generateMessage: localize({\n en,\n ru,\n }),\n });\n\n})\n```\n\nNote: i18n module should be installed and enabled in your `nuxt.config.ts`:\n\n```\nmodules: [\n '@nuxtjs/i18n',\n '@pinia/nuxt',\n ],\n```\n\n========================================\n\nCode:\n```js\n// @/plugins/form_validations.js\n\nexport default Object.freeze({\n VALIDATIONS: {\n\n FIRSTNAME: [\n v => !!v || 'Firstname is required',\n v => (v && v.length >= 3) || 'Firstname must be at least 3 characters'\n ],\n\n // ...\n})\n```\n\n```js\nimport FormValidations from '@/plugins/form_validations.js'\n\nexport default {\n data() {\n firstnameRules: FormValidations.VALIDATIONS.FIRSTNAME\n }\n}\n```\n\n```html\n<v-text-field\n v-model=\"firstname\"\n :rules=\"firstnameRules\"\n/>\n```\n\n```html\n<v-text-field\n ref=\"firstname\"\n v-model=\"firstname\"\n :label=\"$t('firstname')\"\n :rules=\"firstnameRules\"\n required />\n```\n\n```js\nexport default ({ app, store }) => {\n}\n```\n\n```js\nimport i18n from '@/plugins/i18n.js'\n\nexport default Object.freeze({\n VALIDATIONS: {\n FIRSTNAME: [\n v => !!v || i18n.t('firstname_required'),\n ],\n}\n```\n\n```js\n// @/plugins/validation-rules.js\n\nexport default ({app}) => {\n\n let i18n = app.i18n\n\n // You can use `this.$rules` anywhere in the Nuxt app.\n Vue.prototype.$rules = {\n required: [v => !!v || i18n.t('required')]\n }\n}\n```\n\n```html\n<v-text-field\n v-model=\"email\"\n :rules=\"this.$rules.required\"\n label=\"E-mail\"\n required\n ref=\"emailField\"\n></v-text-field>\n```\n\n```text\nVue.prototype\n```\n\n```text\nimport { configure, defineRule } from 'vee-validate'\nimport { localize } from '@vee-validate/i18n';\nimport * as AllRules from '@vee-validate/rules';\n\n\nimport en from '@vee-validate/i18n/dist/locale/en.json';\nimport ru from '@vee-validate/i18n/dist/locale/ru.json';\n\n\nexport default defineNuxtPlugin(nuxtApp => {\n const $t = nuxtApp.$i18n.t;\n Object.entries(AllRules).forEach(([id, validator]) => {\n defineRule(id, validator);\n });\n\n defineRule('ip', value => {\n if (!/((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}/g.test(value)) {\n return $t('errors.ip_invalid');\n }\n return true;\n });\n\n configure({\n generateMessage: localize({\n en,\n ru,\n }),\n });\n\n})\n```\n\n```text\nmodules: [\n '@nuxtjs/i18n',\n '@pinia/nuxt',\n ],\n```\n\n```text\nnuxt.config.ts\n```\n\n========================================\n\nComments:\n- When I try this I get the error `Cannot read properties of undefined (reading 't')`\n- Added a note about required i18n module for Nuxt.","metadata":{"transformedAt":"2026-08-18T18:33:07.851Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":252,"estimatedTokens":1187}}238{"id":"stack-54570522","source":"stackoverflow","questionId":54570522,"title":"How to use `$axios` in utility function in Vuex of Nuxt.js","tags":["javascript","vue.js","axios","vuex","nuxt.js"],"text":"Title: How to use `$axios` in utility function in Vuex of Nuxt.js\nTags: javascript, vue.js, axios, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am configuring VUEX of Nuxt.js as follows.\n\n```\nstore\n├── README.md\n├── posts\n│ ├── actions.js\n│ ├── getters.js\n│ ├── index.js\n│ ├── mutations.js\n│ └── utils\n│ └── getPostById.js\n└── index.js\n```\n\nI added `@nuxtjs/axios` to modules in nuxt.config.js and make it possible to use `this.$axios.$get` in actions.\n\nHowever, you can not use A in store/posts/utils/getPostById.js.\n\nAn error of `Cannot read property '$axios' of undefined` will occur.\n\nEach code is described as follows.\n\n・ store/index.js\n\n```\nimport Vuex from 'vuex'\nimport postsModule from './posts'\n\nnew Vuex.Store({\n modules: {\n posts: postsModule\n }\n})\n```\n\n・store/posts/index.js\n\n```\nimport actions from './actions'\nimport getters from './getters'\nimport mutations from './mutations'\n\nexport const state = () => ({\n posts: [],\n post: {}\n})\n\nexport default {\n namespaced: true,\n state,\n actions,\n getters,\n mutations\n}\n```\n\n・ store/posts/actions.js\n\n```\nimport getPostById from './utils/getPostById'\n\nexport default {\n async fetchPost({ commit }, count = 10) {\n const params = { count: count }\n // Here `$axios` can be used normally\n const result = await this.$axios.$get(\"ApiUrl\")\n commit('setPosts', result)\n },\n async fetchPostById({ commit }, category_ids, count = 10) {\n const topCommunities = {}\n const result = await getPostById(id)\n commit('setPost', result)\n }\n}\n```\n\n・ store/posts/utils/getPostById.js\n\n```\nexport default async function(post_id) {\n // Here `$axios` can not use\n const result = await this.$axios.$get(`${ApiUrl}/${post_id}`)\n return result\n}\n```\n\nHow can I use `this.$axios.$get` inside `getPostById.js`?\n\n========================================\n\nTop Answer:\nQuite a few things have changed since the question was posted. You can now access the `$axios` utility in the store via `this.$axios`. The nuxt plugin uses `inject` to make the `$axios` object available in the store as described here.\n\nAs an example:\n\n```\nexport const actions = {\n async fetchUser () {\n let user = await this.$axios.$get('/me');\n }\n}\n```\n\n========================================\n\nCode:\n```text\nstore\n├── README.md\n├── posts\n│ ├── actions.js\n│ ├── getters.js\n│ ├── index.js\n│ ├── mutations.js\n│ └── utils\n│ └── getPostById.js\n└── index.js\n```\n\n```text\nimport Vuex from 'vuex'\nimport postsModule from './posts'\n\nnew Vuex.Store({\n modules: {\n posts: postsModule\n }\n})\n```\n\n```text\nimport actions from './actions'\nimport getters from './getters'\nimport mutations from './mutations'\n\nexport const state = () => ({\n posts: [],\n post: {}\n})\n\nexport default {\n namespaced: true,\n state,\n actions,\n getters,\n mutations\n}\n```\n\n```text\nimport getPostById from './utils/getPostById'\n\nexport default {\n async fetchPost({ commit }, count = 10) {\n const params = { count: count }\n // Here `$axios` can be used normally\n const result = await this.$axios.$get(\"ApiUrl\")\n commit('setPosts', result)\n },\n async fetchPostById({ commit }, category_ids, count = 10) {\n const topCommunities = {}\n const result = await getPostById(id)\n commit('setPost', result)\n }\n}\n```\n\n```text\nexport default async function(post_id) {\n // Here `$axios` can not use\n const result = await this.$axios.$get(`${ApiUrl}/${post_id}`)\n return result\n}\n```\n\n```text\n@nuxtjs/axios\n```\n\n```text\nthis.$axios.$get\n```\n\n```text\nCannot read property '$axios' of undefined\n```\n\n```text\nthis.$axios.$get\n```\n\n```text\ngetPostById.js\n```\n\n```text\nasync nuxtServerInit ({ commit }, { $axios }) {\n const ip = await $axios.$get('http://icanhazip.com')\n commit('SET_IP', ip)\n}\n```\n\n```text\nexport const actions = {\n async fetchUser () {\n let user = await this.$axios.$get('/me');\n }\n}\n```\n\n```text\n$axios\n```\n\n```text\nthis.$axios\n```\n\n```text\ninject\n```\n\n```text\n$axios\n```\n\n```js\nasync asyncData({ $axios }) {\n const ip = await $axios.$get('http://icanhazip.com')\n ....\n}\n```\n\n```js\nmethods: {\n async fetchSomething() {\n const ip = await this.$axios.$get('http://icanhazip.com')\n ....\n }\n}\n```\n\n```js\n{\n actions: {\n async getIP ({ commit }) {\n const ip = await this.$axios.$get('http://icanhazip.com')\n .......\n }\n }\n}\n```\n\n```js\n// Normal usage with axios\nlet data = (await $axios.get('...')).data\n\n// Fetch Style\nlet data = await $axios.$get('...')\n```\n\n```text\naxios\n```\n\n```text\nnuxt.js\n```\n\n```text\nnuxt.js\n```\n\n```text\n$axios\n```\n\n```text\nv5.12.3\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.851Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":286,"estimatedTokens":1132}}239{"id":"stack-67817006","source":"stackoverflow","questionId":67817006,"title":"How to listen for a page $emit in a nuxt layout?","tags":["javascript","vue.js","nuxt.js","dom-events"],"text":"Title: How to listen for a page $emit in a nuxt layout?\nTags: javascript, vue.js, nuxt.js, dom-events\nSource: Stack Overflow\n\nQuestion:\n*Nuxt 2.15.6;* I want to switch the layout of my menu component by dynamically switching menu components in my root layout.\n\n`default.vue`\n\n```\n\n \n \n\n```\n\n```\ndata() {\n return {\n navLayout: \"default\"\n };\n},\n```\n\nIn the \"child\" components of , my pages eg. *login.vue* *(/login)* I `$emit` an event;\n\n```\n...\nimport nav2 from \"@/layouts/nav2\";\n...\ncreated() {\n this.$emit(\"navLayout\", nav2);\n},\n```\n\nNow it seems to be the `` component is not able to catch the event. I also tried calling a `` method.\n\nHow can I avoid `this.$root.$emit(...);` in my `login.vue` and\n\n```\nthis.$root.$on(\"navLayout\", navLayout => {\n this.navLayout = navLayout;\n});\n```\n\nin `default.vue`?\n\n========================================\n\nTop Answer:\nMaybe I don't understand your question correctly, but it seems to me that you are trying to do yourself what layouts are meant to do. This would mean that you would create a layout with the menu component for login, a default layout etc. like this:\n\nlogin.vue\n\n```\n\n \n \n\n```\n\ndefault.vue\n\n```\n\n \n \n\n```\n\nOn your page you would do:\n\n```\nexport default {\n layout: login\n}\n```\n\nAnd then that would load the layout with the login menu component. On all other pages it would load the default menu.\n\nMore info here: https://nuxtjs.org/examples/layouts/\n\n========================================\n\nCode:\n```html\n<template>\n <component :is=\"navLayout\"></component>\n <Nuxt :navLayout=\"navLayout = $event\" />\n</template>\n```\n\n```js\ndata() {\n return {\n navLayout: \"default\"\n };\n},\n```\n\n```js\n...\nimport nav2 from \"@/layouts/nav2\";\n...\ncreated() {\n this.$emit(\"navLayout\", nav2);\n},\n```\n\n```js\nthis.$root.$on(\"navLayout\", navLayout => {\n this.navLayout = navLayout;\n});\n```\n\n```text\ndefault.vue\n```\n\n```text\n$emit\n```\n\n```text\n<Nuxt>\n```\n\n```text\n<Nuxt @navLayout=\"test()\" />\n```\n\n```text\nthis.$root.$emit(...);\n```\n\n```text\nlogin.vue\n```\n\n```text\ndefault.vue\n```\n\n```html\n<button @click=\"$nuxt.$emit('eventName', 'nice payload')\">nice</button>\n```\n\n```html\n<script>\nexport default {\n created() {\n this.$nuxt.$on('eventName', ($event) => this.test($event))\n },\n methods: {\n test(e) {\n console.log('test ok >>', e)\n },\n },\n}\n</script>\n```\n\n```html\n<Nuxt @navLayout=\"navLayout = $event\" :navLayout=\"navLayout\" />\n```\n\n```text\nNuxt\n```\n\n```text\n<nuxt></nuxt>\n```\n\n```text\n<nuxt-child></nuxt-child>\n```\n\n```text\n<template>\n <LoginMenu>\n <Nuxt/>\n</template>\n```\n\n```text\n<template>\n <DefaultMenu>\n <Nuxt/>\n</template>\n```\n\n```text\nexport default {\n layout: login\n}\n```\n\n========================================\n\nComments:\n- I am aware of layouts. But this would limit me to the use of different layouts for switching the menu. What if I want to switch the main content in to a different layout later. I would also have to change all menu layouts - for example if I add a changing footer. With a nested layout the nested layout would not be changable by using the \"layout\" annotation in the components. Am I getting this right?\n- Looks like you have an answer to your problem. Just to respond. It is difficult for me to see what you are trying to accomplish, but in general I would separate the application in pages. Both pages and layouts can import components. Whatever needs to be on multiple pages becomes a layout and the rest is a page. Looking at it this way the framework works for most cases. Trying to do it differently is always possible, but I think the key is to let the framework work for you, not work against it. Again, I don't understand your situation fully, so apologies if I'm off base.\n- Yeah, in the end I choose your way and created multiple layouts for the different menus. Thanks you your advice! I I marked the other answer as the answer because it fits the needs for the initial question\n- Yeah, I saw the same Gh post ;D and somehow it seems not to be possible with the component. This would be the legit way to do it then but I also see that using layouts like Imre suggested is an approach. I will mark this as solved as your answer supports the inital question. Thank you!!\n- I guess that the team did not bother fixing this because of the way Nuxt3 may handle things in a different manner (maybe, I'm not part of the core team). Thanks for the upvote!","metadata":{"transformedAt":"2026-08-18T18:33:07.851Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":206,"estimatedTokens":1090}}240{"id":"stack-62543010","source":"stackoverflow","questionId":62543010,"title":"What is the advantage of using nuxt-link over router-link?","tags":["vue.js","routes","nuxt.js","nuxt-link"],"text":"Title: What is the advantage of using nuxt-link over router-link?\nTags: vue.js, routes, nuxt.js, nuxt-link\nSource: Stack Overflow\n\nQuestion:\nIn `Nuxt`, we can use `router-link` as well as `nuxt-link`. What is the advantage of using `nuxt-link` over `router-link`?\n\n```\nAbout\n```\n\ninstead of\n\n```\nAbout\n```\n\n========================================\n\nCode:\n```text\n<nuxt-link to=\"/about\">About</nuxt-link>\n```\n\n```text\n<router-link to=\"/about\">About</router-link>\n```\n\n```text\nNuxt\n```\n\n```text\nrouter-link\n```\n\n```text\nnuxt-link\n```\n\n```text\nnuxt-link\n```\n\n```text\nrouter-link\n```\n\n```text\n<nuxt-link>\n```\n\n```text\n<nuxt-link>\n```\n\n```text\n<router-link>\n```\n\n```text\n<nuxt-link>\n```\n\n========================================\n\nComments:\n- For anyone interested: According to this article, `If you’re using Vue CLI 3 every lazily loaded resource is prefetched by default!`\n- Bad if you want to your base components between a Nuxt and a non-nuxt project\n- Good if you want your Nuxt app to be SEO optimized","metadata":{"transformedAt":"2026-08-18T18:33:07.851Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":70,"estimatedTokens":251}}241{"id":"stack-72977133","source":"stackoverflow","questionId":72977133,"title":"Nuxt 3 How to add Cache Control to generated static files","tags":["vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: Nuxt 3 How to add Cache Control to generated static files\nTags: vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am creating SSR project with Nuxt 3.\nI am thinking to add `Cache-Control` Header to generated static files in `.output/_nuxt` directory.\n\nI tried below code `server/middleware/cache-control.ts`\n\n```\nexport default defineEventHandler((event) => {\n let res = event.res\n const year = 31536000\n const tenmin = 600\n const url = event.req.url\n const maxage = url.match(/(.+)\\.(jpg|jpeg|gif|css|png|js|ico|svg|mjs)/) ? year : tenmin\n res.setHeader('Cache-Control', `max-age=${maxage} s-maxage=${maxage}`);\n})\n```\n\nBut, it does not work.\n\nhttps://i.sstatic.net/i7Prb.png\n\nHow to add `Cache-Control` to the generated static files?\n\n========================================\n\nTop Answer:\nFor Nuxt3 I have used this as server middleware `server/middleware/cache-control.js`\n\n```\nexport default defineEventHandler((event) => {\n if (process.env.NODE_ENV == \"production\") {\n const url = event.node.req.url;\n const maxage = url.match(/(.+)\\.(jpg|jpeg|gif|png|ico|svg|css|js|mjs)/)\n ? 60 * 60 * 12 * 30\n : 60 * 60;\n appendHeader(\n event,\n \"Cache-Control\",\n `max-age=${maxage} s-maxage=${maxage}`\n );\n } else {\n appendHeader(event, \"Cache-Control\", `max-age=${60} s-maxage=${60}`);\n }\n});\n```\n\n========================================\n\nCode:\n```js\nexport default defineEventHandler((event) => {\n let res = event.res\n const year = 31536000\n const tenmin = 600\n const url = event.req.url\n const maxage = url.match(/(.+)\\.(jpg|jpeg|gif|css|png|js|ico|svg|mjs)/) ? year : tenmin\n res.setHeader('Cache-Control', `max-age=${maxage} s-maxage=${maxage}`);\n})\n```\n\n```text\nCache-Control\n```\n\n```text\n.output/_nuxt\n```\n\n```text\nserver/middleware/cache-control.ts\n```\n\n```text\nCache-Control\n```\n\n```js\nexport default defineNuxtConfig({\n nitro: {\n routeRules: {\n \"/img/**\": { headers: { 'cache-control': `public,max-age=${year},s-maxage=${year}` } },\n \"/_nuxt/**\": { headers: { 'cache-control': `public,max-age=${year},s-maxage=${year}` } },\n }\n }\n})\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nappendHeader(res, name, value)\n```\n\n```js\nexport default defineNuxtPlugin((nuxtApp) => {\n nuxtApp.hook('app:rendered', ctx => {\n ctx.ssrContext?.event.node.res.setHeader('cache-control', `max-age=${60*60*24*365}`)\n })\n})\n```\n\n```js\nimport { RenderResponse } from \"nitropack\"\n\nexport default defineNitroPlugin((nitroApp) => {\n nitroApp.hooks.hook('render:response', (res: RenderResponse) => {\n res.headers['cache-control'] = `max-age=${60*60*24*365}`\n })\n})\n```\n\n```text\nplugins/cache.server.ts\n```\n\n```text\nserver/plugins/cache.ts\n```\n\n```text\nexport default defineEventHandler((event) => {\n if (process.env.NODE_ENV == \"production\") {\n const url = event.node.req.url;\n const maxage = url.match(/(.+)\\.(jpg|jpeg|gif|png|ico|svg|css|js|mjs)/)\n ? 60 * 60 * 12 * 30\n : 60 * 60;\n appendHeader(\n event,\n \"Cache-Control\",\n `max-age=${maxage} s-maxage=${maxage}`\n );\n } else {\n appendHeader(event, \"Cache-Control\", `max-age=${60} s-maxage=${60}`);\n }\n});\n```\n\n```text\nserver/middleware/cache-control.js\n```\n\n```text\nexport default defineNuxtConfig({\n ....\n nitro: {\n publicAssets: [\n {\n baseURL: \"video\",\n dir: \"public/video\",\n maxAge: 60 * 60 * 24 * 365,\n },\n {\n baseURL: \"images\",\n dir: \"public/images\",\n maxAge: 60 * 60 * 24 * 365,\n },\n {\n baseURL: \"animations\",\n dir: \"public/animations\",\n maxAge: 60 * 60 * 24 * 365,\n },\n ],\n compressPublicAssets: {\n brotli: true,\n gzip: true,\n },\n },\n ....\n})\n```\n\n```text\npublicAssets\n```\n\n```text\nbaseURL\n```\n\n```text\npublic\n```\n\n```text\ndir\n```\n\n```text\nmaxAge\n```\n\n```text\npublicAssets\n```\n\n```text\nnitro\n```\n\n```text\n$production\n```\n\n```text\nnuxt.config.ts\n```\n\n========================================\n\nComments:\n- Files don't respond to request. Server has to set headers.\n- `console.log` tells that network does not go through Nuxt3 server. I think I need to configure Vite server.\n- I add below code to `nuxt.config.js`. But still does not wok... ``` js export default defineNuxtConfig({ vite: { server: { headers: { \"Cache-Control\": \"max-age=11111, s-maxage=11111\" } } } }) ```\n- Nuxt 3 uses Nitro server by default. Where do you host your application ? Universal app can get just once files from server and then get others from other static files host. If it does like that, you have to set headers in both server and host server.\n- I was miss understanding what default server is... I have to add some settings to Nitro. I am currently testing with in Docker. I do not need to set host server headers for now.\n- It's experimental but you could try the new Route Rules: v3.nuxtjs.org/guide/concepts/rendering#route-rules but instead if you host you App on Vercel you can do it in the vercel.config file: vercel.com/guides/… I guess Netlify has something similar.\n- I was not able to make it works, maybe something change recently ?\n- For whom are struggling in dev mode nuxt: I was able to check cache header when I build nuxt using: npm run build export NUXT_API_HOST='[YOUR SERVER URL]' export PORT='8080' node .output/server/index.mjs\n- Hey @JillAndMe I tried this approach and it didn't work. Infact I get no cache-control header at all in my network tab after running build. What could be the problem?\n- Edit. I use nuxt image which generates the images using ipx. So I had to cache the ipx folder too, then run on build test the network tab give it some time and it shows the cache correctly. `'/_ipx/**': { headers: { 'cache-control':`public,max-age=31536000,s-maxage=31536000` } },`","metadata":{"transformedAt":"2026-08-18T18:33:07.851Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":226,"estimatedTokens":1477}}242{"id":"stack-69363649","source":"stackoverflow","questionId":69363649,"title":"How to autoimport types at TypeScript Nuxt.js app?","tags":["typescript","nuxt.js"],"text":"Title: How to autoimport types at TypeScript Nuxt.js app?\nTags: typescript, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to use my custom types at Nuxt.js app and want them to autoimport for every component I making. I edited tsconfig.js with `\"include\": [\"**/*.ts\", \"**/*.vue\", \"**/*.tsx\"]` and put my types to `types/index.d.ts`:\n\n```\nexport interface IUser {\nname: string\naddress: string\n}\n```\n\nBut when I compiling app it says `Cannot find name 'IUser'` at `let users: IUser[] = []`\nI just don't want to import type `IUser` to every component. How can I make Nuxt.js import type definition everywhere itself?\n\n========================================\n\nCode:\n```text\nexport interface IUser {\nname: string\naddress: string\n}\n```\n\n```text\n\"include\": [\"**/*.ts\", \"**/*.vue\", \"**/*.tsx\"]\n```\n\n```text\ntypes/index.d.ts\n```\n\n```text\nCannot find name 'IUser'\n```\n\n```text\nlet users: IUser[] = []\n```\n\n```text\nIUser\n```\n\n```text\n// types/index.d.ts\ndeclare global {\n interface IUser {\n name: string\n address: string\n }\n}\n\nexport {};\n```\n\n```text\n// components/whatever.vue\n<script setup lang=\"ts\">\nconst props = defineProps<{ user: IUser }>();\n</script>\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.851Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":65,"estimatedTokens":291}}243{"id":"stack-58688604","source":"stackoverflow","questionId":58688604,"title":"How to remove trailing slash from url in nuxt.js?","tags":["nuxt.js"],"text":"Title: How to remove trailing slash from url in nuxt.js?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am looking for a way to redirect all my URLs so that they all do not have a slash in the end. \nI have tried with https://www.npmjs.com/package/@nuxtjs/redirect-module, but it does not redirect correctly.\n\n```\nredirect: [\n {\n from: '\\/$',\n to: (from, req) => req.url.replace(/\\/$/, '')\n }\n ],\n```\n\nFor example, to change such a url http://localhost:8080/item/test-slug/\nThis module redirects me to http://localhost:8080/item/test-slug/item/test-slug\n\nAny insight will be welcome. Thanks!\n\n========================================\n\nTop Answer:\nI've solved this problem using custom middleware. It redirects to url which don't have a slash in the end.\n\nCreate **`src/middleware/trailingSlashRedirect.js`**\n\n```\nexport default function ({ route, redirect }) {\n if (route.path !== '/' && route.path.endsWith('/')) {\n const { path, query, hash } = route;\n const nextPath = path.replace(/\\/+$/, '') || '/';\n const nextRoute = { path: nextPath, query, hash };\n\n redirect(nextRoute);\n }\n}\n```\n\nRegister it in **`nuxt.config.js`**:\n\n```\nexport default {\n ...\n router: {\n middleware: 'trailingSlashRedirect',\n },\n}\n```\n\nSo you should not use any module to solve this problem. I think it's much better than using third party libs.\n\n========================================\n\nCode:\n```text\nredirect: [\n {\n from: '\\/$',\n to: (from, req) => req.url.replace(/\\/$/, '')\n }\n ],\n```\n\n```text\ntrailingSlash : Type: Boolean or undefined\nDefault: undefined\nAvailable since: v2.10\nex:\nrouter: {\n trailingSlash: false\n}\n```\n\n```text\nnpm i nuxt-trailingslash-module\n```\n\n```text\n{\n // eslint-disable-next-line\n from: '(?!^\\/$|^\\/[?].*$)(.*\\/[?](.*)$|.*\\/$)',\n to: (from, req) => {\n const base = req._parsedUrl.pathname.replace(/\\/$/, '');\n const search = req._parsedUrl.search;\n return base + (search != null ? search : '');\n }\n},\n```\n\n```text\nrouter: {\n trailingSlash: false\n},\n```\n\n```text\n'(?!^\\/$|^\\/[?].*$)(.*\\/[?](.*)$|.*\\/$)'\n```\n\n```text\n'/'\n```\n\n```text\n'/'\n```\n\n```text\n'/blog/'\n```\n\n```text\n'/blog'\n```\n\n```text\n'/blog/?a=b'\n```\n\n```text\n'/blog?a=b'\n```\n\n```text\n'/blog/foo/'\n```\n\n```text\n'/blog/foo'\n```\n\n```text\n'/blog/foo/?a=b'\n```\n\n```text\n'/blog/foo?a=b'\n```\n\n```text\n'/'\n```\n\n```text\n'/'\n```\n\n```text\n'/?a=b'\n```\n\n```text\n'/?a=b'\n```\n\n```text\n(?!^\\/$|^\\/[?].*$)\n```\n\n```text\n/\n```\n\n```text\n/?foo=bar\n```\n\n```text\n(.*\\/[?](.*)$|.*\\/$)\n```\n\n```text\n/blog/\n```\n\n```text\n/blog/?foo=bar\n```\n\n```text\nexport default function ({ route, redirect }) {\n if (route.path !== '/' && route.path.endsWith('/')) {\n const { path, query, hash } = route;\n const nextPath = path.replace(/\\/+$/, '') || '/';\n const nextRoute = { path: nextPath, query, hash };\n\n redirect(nextRoute);\n }\n}\n```\n\n```text\nexport default {\n ...\n router: {\n middleware: 'trailingSlashRedirect',\n },\n}\n```\n\n```text\nsrc/middleware/trailingSlashRedirect.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nrouter: {\n trailingSlash: false\n},\n```\n\n```text\n// Result: /foo\nwithoutTrailingSlash('/foo/')\n// Result: /path?query=true\nwithoutTrailingSlash('/path/?query=true', true)\n```\n\n```text\n// Result: /foo/\nwithTrailingSlash('/foo')\n// Result: /path/?query=true\nwithTrailingSlash('/path?query=true', true)\n```\n\n```text\nexport default defineNuxtRouteMiddleware((to) => {\n if (to.path.slice(-1) === '/') {\n return navigateTo({...to,\n path: to.path.slice(0, -1)\n })\n }\n});\n```\n\n```text\ntrailingSlash.global.js\n```\n\n```text\nmiddleware\n```\n\n========================================\n\nComments:\n- looking for the same with ?fbclid=, no result yet ...\n- this is great! i think the regex could be simplified to: `from: '.{1,}\\/([?].*)?$'`. this matches any path that has at least 1 character before a trailing slash at the end - with an optional querystring.\n- Ive tried. `trailingSlash: false` just does not work. no matter the version\n- This does not remove the trailing slash, it makes the route with the trailing slash not work (or the opposite). You still have to handle the redirect.\n- Seemed to only work when adding `trailingSlash: false` to the router as well. Otherwise an error occurred (about duplicate redirection)\n- @tmarois you don't need to add `trailingSlash: false`, duplicate redirections will not occur due to custom middleware I mentioned above\n- thank you for this, works perfectly with my current set up that uses trailingSlash: false\n- Does anyone know why the trailing slash is added in the first place? Strangely, it only adds it to 3 pages on the site I am working on. I used `trailingSlash: false` and it does work when using the internal router but not on initial page load or reload.\n- I'm getting duplicate redirect errors as well with this middleware\n- Why do you need first condition in your 'if'? I removed it and left only second condition and it seems to work perfect (with trailingSlash: undefined).\n- What's the point of this? Trailing slashes are being removed automatically in Nuxt 3.\n- It doesn't, I have three project running on Nuxt 3 and none of them removes the trailing slash automatically.. Could be because I use the \"pages:extend\" hook, I don't really know..\n- 500 Infinite redirect in navigation guard\n- For Nuxt 3 with SSR on Apache, the solution is in your `.htaccess` file as described here stackoverflow.com/a/77699881/1454622 . The trick is that we want to display no trailing slash BUT ALSO serve that directory's `index.html` file.","metadata":{"transformedAt":"2026-08-18T18:33:07.851Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":266,"estimatedTokens":1373}}244{"id":"stack-73274434","source":"stackoverflow","questionId":73274434,"title":"Why does output whatever follows twice when using Nuxt v3 static generation?","tags":["vue.js","nuxt.js","font-awesome","nuxt3.js"],"text":"Title: Why does output whatever follows twice when using Nuxt v3 static generation?\nTags: vue.js, nuxt.js, font-awesome, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am using vue-fontawesome with Nuxt 3 as described here and I'm seeing this weird behaviour. Say I have something like this\n\n```\nExample\n```\n\nif I run the dev server, everything is fine, but if I run `generate` and serve the output through a static HTTP server, I get \"Example\" printed twice. If I wrap the text in a tag, I get the tag and text twice (i.e. `ExampleExample`). Weirdly enough, though, the generated HTML does not contain the repetition, so I suspect something weird is going on in the browser.\n\nYou can grab the generated site from here as a reproducible test case. https://andreafranceschini.org/files/afnuxt.tgz\n\nI hear `vue-fontawesome` isn't super happy with SSR and static generation, but I also see others using it just fine in the same way so I wonder what I may be doing wrong?\n\n**EDIT** I also posted this as a \"bug\" here.\n\n**EDIT 2** A workaround is to enclose the icon alone in something else, like a `span` tag.\n\n========================================\n\nTop Answer:\nTry adding the following to your `nuxt.config.ts` file:\n\n```\nbuild: {\n transpile: [\n '@fortawesome/fontawesome-svg-core',\n '@fortawesome/free-solid-svg-icons',\n '@fortawesome/free-regular-svg-icons',\n '@fortawesome/free-brands-svg-icons',\n '@fortawesome/vue-fontawesome'\n ]\n}\n```\n\n(Adjust the specific icon package imports as required.)\n\nI can only find this solution mentioned online in two places [1] [2], neither of which mention this duplication issue. It is also notably absent from all official documentation.\n\nThat said, for me at least, this fixes both this issue and the issue of `Could not find one or more icon(s)` error messages in the console.\n\n========================================\n\nCode:\n```text\n<a href=\"https://example.com\"><font-awesome-icon icon=\"fa-brands fa-twitter\" />Example</a>\n```\n\n```text\ngenerate\n```\n\n```text\n<span>Example</span><span>Example</span>\n```\n\n```text\nvue-fontawesome\n```\n\n```text\nspan\n```\n\n```text\nspan\n```\n\n```js\nbuild: {\n transpile: [\n '@fortawesome/fontawesome-svg-core',\n '@fortawesome/free-solid-svg-icons',\n '@fortawesome/free-regular-svg-icons',\n '@fortawesome/free-brands-svg-icons',\n '@fortawesome/vue-fontawesome'\n ]\n}\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nCould not find one or more icon(s)\n```\n\n========================================\n\nComments:\n- I… dont? There are two tags, one is `a`, the other is `font-awesome-icon`.\n- Have you tried closing the tag ``?\n- @IgorMoraru No difference from the self-closing tag ` />`.\n- experienced this, thanks for detailing the workaround!!","metadata":{"transformedAt":"2026-08-18T18:33:07.851Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":98,"estimatedTokens":679}}245{"id":"stack-59738496","source":"stackoverflow","questionId":59738496,"title":"GraphQL to query something other than ID","tags":["graphql","nuxt.js","apollo","strapi"],"text":"Title: GraphQL to query something other than ID\nTags: graphql, nuxt.js, apollo, strapi\nSource: Stack Overflow\n\nQuestion:\nI am using Strapi with Nuxt.js to implement my first Headless CMS. I am using Apollo and GraphQL.\n\nI am running into the current error and I've had no luck to figure this out for days.\n\nIf I write:\n\n```\nquery Page($id: ID!) {\n page(id: $id) {\n id\n slug\n title\n }\n}\n```\n\nAnd pass the following variable:\n\n```\n{\n \"id\" : \"1\"\n}\n```\n\nI received the correct expected result:\n\n```\n{\n \"data\": {\n \"page\": {\n \"id\": \"1\",\n \"slug\": \"/\",\n \"title\": \"Homepage\"\n }\n }\n}\n```\n\nHOWEVER, I would like to get the content not via ID, but via a field that I created in Strapi, called \"slug\".\nLooking around, it seems like I should be able to do something like:\n\n```\nquery Page($slug: String!) {\n page(slug: $slug) {\n id\n slug\n title\n }\n}\n```\n\nWith variable:\n\n```\n{\n \"slug\" : \"/\"\n}\n```\n\nbut I receive this error:\n\n```\n{\n \"error\": {\n \"errors\": [\n {\n \"message\": \"Unknown argument \\\"slug\\\" on field \\\"page\\\" of type \\\"Query\\\".\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 8\n }\n ],\n \"extensions\": {\n \"code\": \"GRAPHQL_VALIDATION_FAILED\",\n \"exception\": {\n \"stacktrace\": [\n```\n\n... the error continues....\n\n[UPDATE] After Italo replied, I changed it into:\n\n```\nquery Pages($slug: String!) {\n page(where: {slug: $slug}) {\n id\n slug\n title\n }\n}\n```\n\nBut I now get the following error:\n\n```\n{\n \"error\": {\n \"errors\": [\n {\n \"message\": \"Unknown argument \\\"where\\\" on field \\\"page\\\" of type \\\"Query\\\".\",\n```\n\nI also noticed that I get a query if I change \"page\" into \"pages\", but it shows all of the pages...\n\nWhat am I missing?\nThanks!\n\n========================================\n\nTop Answer:\nThis seem to work for me using slug\n\ncreate new file schema.graphql.js in\napi/blog-post/config/schema.graphql.js\n\n```\nmodule.exports = {\n query: \"blogPostBySlug(slug: String!): BlogPost\",\n resolver: {\n Query: {\n blogPostBySlug: {\n description: \"Return blog post with a given slug\",\n resolver: \"application::blog-post.blog-post.findOne\",\n },\n },\n },\n};\n```\n\nchange routes.json in api/blog-post/config/routes.json, from \"path\": \"/blog-posts/:id\" to \"path\": \"/blog-posts/:slug:\n\n```\n{\n \"method\": \"GET\",\n \"path\": \"/blog-posts/:slug\",\n \"handler\": \"blog-post.findOne\",\n \"config\": {\n \"policies\": []\n }\n},\n```\n\nhttps://i.sstatic.net/pKHHS.png\n\n========================================\n\nCode:\n```text\nquery Page($id: ID!) {\n page(id: $id) {\n id\n slug\n title\n }\n}\n```\n\n```text\n{\n \"id\" : \"1\"\n}\n```\n\n```text\n{\n \"data\": {\n \"page\": {\n \"id\": \"1\",\n \"slug\": \"/\",\n \"title\": \"Homepage\"\n }\n }\n}\n```\n\n```text\nquery Page($slug: String!) {\n page(slug: $slug) {\n id\n slug\n title\n }\n}\n```\n\n```text\n{\n \"slug\" : \"/\"\n}\n```\n\n```text\n{\n \"error\": {\n \"errors\": [\n {\n \"message\": \"Unknown argument \\\"slug\\\" on field \\\"page\\\" of type \\\"Query\\\".\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 8\n }\n ],\n \"extensions\": {\n \"code\": \"GRAPHQL_VALIDATION_FAILED\",\n \"exception\": {\n \"stacktrace\": [\n```\n\n```text\nquery Pages($slug: String!) {\n page(where: {slug: $slug}) {\n id\n slug\n title\n }\n}\n```\n\n```text\n{\n \"error\": {\n \"errors\": [\n {\n \"message\": \"Unknown argument \\\"where\\\" on field \\\"page\\\" of type \\\"Query\\\".\",\n```\n\n```text\nquery Pages($slug: String!) {\n pages(where: {slug: $slug}) {\n id\n slug\n title\n }\n}\n```\n\n```text\nmodule.exports = {\n query: \"blogPostBySlug(slug: String!): BlogPost\",\n resolver: {\n Query: {\n blogPostBySlug: {\n description: \"Return blog post with a given slug\",\n resolver: \"application::blog-post.blog-post.findOne\",\n },\n },\n },\n};\n```\n\n```text\n{\n \"method\": \"GET\",\n \"path\": \"/blog-posts/:slug\",\n \"handler\": \"blog-post.findOne\",\n \"config\": {\n \"policies\": []\n }\n},\n```\n\n========================================\n\nComments:\n- Hi Italo, thanks for your reply. Yes, I am using localhost:1337/graphql for testing, and making your changes, I now get the following error: \"message\": \"Unknown argument \\\"where\\\" on field \\\"page\\\" of type \\\"Query\\\".\",\n- Yeah, my mistake. Just try changing `page(where:)` to `pages(where:)` (to be clear, you're supposed to use the query that find all pages instead of the one that returns just one item)\n- Just go to the graphql interface and use the autocompletition (ctrl+space) to check if the where field is avaiable.@Saro\n- Yeah, it works this way. However, I have to reference to it as pages[0].id or I get nothing. I do get the correct one by slug. It kind of feel wrong to me to have to use the [0], so I wonder if there's a better way to do it.\n- It's ok using this way and getting the record using pages[0], nothing wrong with it at all. But if you want to have something better, the only way is creating a custom endpoint on graphql schema It's not so hard and it's a good way to start tweeking strapi.","metadata":{"transformedAt":"2026-08-18T18:33:07.851Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":276,"estimatedTokens":1230}}246{"id":"stack-66960906","source":"stackoverflow","questionId":66960906,"title":"Access Nuxt `$config` within Vuex State","tags":["nuxt.js","vuex"],"text":"Title: Access Nuxt `$config` within Vuex State\nTags: nuxt.js, vuex\nSource: Stack Overflow\n\nQuestion:\nAccording to the Nuxt docs, I should be able to access `$config` from within my vuex store:\n\n\"Using your config values:\nYou can then access these values anywhere by using the context in your pages, **store**, components and plugins by using `this.$config` or `context.$config`.\" (emphasis added, from https://nuxtjs.org/docs/2.x/directory-structure/nuxt-config#runtimeconfig)\n\nWhen I try to access `$config` in my store like this:\n\n```\nexport const state = () => (\n {\n // App vital details\n app: {\n name: 'MyApp',\n appVersion: this.$config.appVersion,\n copyright: helpers.getCurrentYear()\n },\n }\n)\n```\n\nI get an error message in the console: \"Cannot read property '$config' of undefined\"\nIf I try with `context.$config` I get error: \"context is not defined\"\n\nI know `$config` is \"working\" otherwise because I can access it in my templates with `$config.appVersion`, but how can I properly access it within my store?\n\n========================================\n\nCode:\n```text\nexport const state = () => (\n {\n // App vital details\n app: {\n name: 'MyApp',\n appVersion: this.$config.appVersion,\n copyright: helpers.getCurrentYear()\n },\n }\n)\n```\n\n```text\n$config\n```\n\n```text\nthis.$config\n```\n\n```text\ncontext.$config\n```\n\n```text\n$config\n```\n\n```text\ncontext.$config\n```\n\n```text\n$config\n```\n\n```text\n$config.appVersion\n```\n\n```text\nactions: {\n nuxtServerInit (vuexContext, { $config }) {\n // your code...\n }\n}\n```\n\n```text\npage-example.vue\n\nasyncData(context) {\n context.store.dispatch('loadInActionExample', { data: 'test', context: context })\n}\n```\n\n```text\nYour store (index.js or action module)\n\nexport const actions = {\n loadInActionExample(context, payload) {\n // payload.context.$config is accessible...\n \n // execute your action and set data\n context.commit('setData', payload.data)\n }\n}\n```\n\n========================================\n\nComments:\n- How would one handle typing errors associated with accessing instance properties in this case? Eg `Property '$config' does not exist on type 'Vue'.` Thanks.\n- $config is a property of context, which is defined in @nuxt/types.Context. So when you pass in the context as an argument, import {Context} from \"@nuxt/types\" and use Context as the argument type.\n- Yup, augmented Vue class with extra `$config` field and using that as a type definition for context, works as expected. Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:07.851Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":109,"estimatedTokens":629}}247{"id":"stack-56921964","source":"stackoverflow","questionId":56921964,"title":"Access root state from module getters in vuex","tags":["vue.js","vuex","nuxt.js"],"text":"Title: Access root state from module getters in vuex\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have root state which contains auth data from nuxt/auth..\n\nInside store/modules/messages/ I have also state and getters etc..\n\nInside getters I need to get auth data from root state but I dont know how..\n\nI tried adding rootState to index.js from module:\n\n```\nimport state from './state'\nimport rootState from '../../state'\nimport * as actions from './actions'\nimport * as mutations from './mutations'\nimport * as getters from './getters'\n\nexport default {\n namespaced: true,\n state,\n rootState,\n getters,\n mutations,\n actions\n}\n\nexport const avatar = (rootState) => rootState.auth.user.avatar\n```\n\nBut this still returns module state..\n\n========================================\n\nCode:\n```text\nimport state from './state'\nimport rootState from '../../state'\nimport * as actions from './actions'\nimport * as mutations from './mutations'\nimport * as getters from './getters'\n\nexport default {\n namespaced: true,\n state,\n rootState,\n getters,\n mutations,\n actions\n}\n\nexport const avatar = (rootState) => rootState.auth.user.avatar\n```\n\n```text\n// messages/getters.js\n\nexport function avatar (state, getters, rootState, rootGetters) {\n return rootState.auth.user.avatar\n}\n```\n\n========================================\n\nComments:\n- Yeah I found out that, so I need to add state, getters, rootState to get rootState or can I get only rootState?\n- It's always the third argument. Afaik only in actions you can just destructure the first argument. There's always the arguments object of course, but I hate that.","metadata":{"transformedAt":"2026-08-18T18:33:07.851Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":69,"estimatedTokens":407}}248{"id":"stack-49478991","source":"stackoverflow","questionId":49478991,"title":"POST file along with form data Vue + axios","tags":["php","vue.js","vue-component","axios","nuxt.js"],"text":"Title: POST file along with form data Vue + axios\nTags: php, vue.js, vue-component, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a method for Vuejs component:\n\n```\nasync submit () {\n if (this.$refs.form.validate()) {\n let formData = new FormData()\n formData.append('userImage', this.avatarFile, this.avatarFile.name)\n this.avatarFile = formData\n try {\n let response = await this.$axios.post('http://localhost:3003/api/test.php', {\n avatar: this.avatarFile,\n name: this.name,\n gender: this.gender,\n dob: this.DOB,\n }, {\n headers: {\n 'Content-Type': 'multipart/form-data; boundary=' + formData._boundary\n }\n })\n if (response.status === 200 && response.data.status === 'success') {\n console.log(this.response)\n }\n } catch (e) {\n console.log(e)\n }\n }\n }\n```\n\nAnd in `test.php`, I'm using `json_decode(file_get_contents(\"php://input\"), TRUE);` to read data as `$_POST` variables.\n\nWhile I am able to read `name`, `gender` and `dob` correctly, I can't fetch `avatar` properly.\n\nAny solutions for the same?\n\nNote: I don't to append every variable as `formData.append(.., ..)` as I am planning to handle over 14 variables.\n\nNote for moderators: I didn't find any question where formData was being used along with other data objects.\n\n========================================\n\nTop Answer:\n**PHP** ( process.php )\n\n```\n $_POST,\n \"files\" => $_FILES\n );\n\n echo json_encode($data);\n?>\n```\n\n**Vue and form HTML**\n\n\r\n\r\n\n```\nlet vm = new Vue({\r\n el: \"#myApp\",\r\n data: {\r\n form: {}\r\n },\r\n methods: {\r\n submit: async function (e) {\r\n e.preventDefault();\r\n\r\n /* formData */\r\n var formData = new FormData( this.$refs.formHTML );\r\n\r\n /* AJAX request */\r\n await axios({\r\n method: \"post\",\r\n url: \"process.php\",\r\n\r\n data: formData,\r\n\r\n config: { headers: { \"Content-Type\": \"multipart/form-data\" } }\r\n })\r\n\r\n /* handle success */\r\n .then( response => { console.log(response.data); } )\r\n\r\n /* handle error */\r\n .catch( response => { console.log(response) } );\r\n }\r\n }\r\n});\n```\n\n\r\n\n```\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n Name: \n\r\n\r\n Gender:\r\n Male\r\n Female \n\r\n\r\n File: \r\n\r\n \r\n\r\n \r\n\r\n\n```\n\n========================================\n\nCode:\n```text\nasync submit () {\n if (this.$refs.form.validate()) {\n let formData = new FormData()\n formData.append('userImage', this.avatarFile, this.avatarFile.name)\n this.avatarFile = formData\n try {\n let response = await this.$axios.post('http://localhost:3003/api/test.php', {\n avatar: this.avatarFile,\n name: this.name,\n gender: this.gender,\n dob: this.DOB,\n }, {\n headers: {\n 'Content-Type': 'multipart/form-data; boundary=' + formData._boundary\n }\n })\n if (response.status === 200 && response.data.status === 'success') {\n console.log(this.response)\n }\n } catch (e) {\n console.log(e)\n }\n }\n }\n```\n\n```text\ntest.php\n```\n\n```text\njson_decode(file_get_contents(\"php://input\"), TRUE);\n```\n\n```text\n$_POST\n```\n\n```text\nname\n```\n\n```text\ngender\n```\n\n```text\ndob\n```\n\n```text\navatar\n```\n\n```text\nformData.append(.., ..)\n```\n\n```text\nlet rawData = {\n name: this.name,\n gender: this.gender,\n dob: this.dob\n }\n rawData = JSON.stringify(rawData)\n let formData = new FormData()\n formData.append('avatar', this.avatarFile, this.avatarFile.name)\n formData.append('data', rawData)\n try {\n let response = await this.$axios.post('http://localhost:3003/api/test.php', formData, {\n headers: {\n 'Content-Type': 'multipart/form-data'\n }\n })\n```\n\n```text\n$_POST = json_decode($_POST['data'],true);\n```\n\n```text\nObject.keys(rawData).map(e => {\n formData.append(e, rawData[e])\n })\n```\n\n```text\n(name: { first: '', last: ''} )\n```\n\n```text\n<?php\n $data = array(\n \"post\" => $_POST,\n \"files\" => $_FILES\n );\n\n echo json_encode($data);\n?>\n```\n\n```js\nlet vm = new Vue({\n el: \"#myApp\",\n data: {\n form: {}\n },\n methods: {\n submit: async function (e) {\n e.preventDefault();\n\n /* formData */\n var formData = new FormData( this.$refs.formHTML );\n\n /* AJAX request */\n await axios({\n method: \"post\",\n url: \"process.php\",\n\n data: formData,\n\n config: { headers: { \"Content-Type\": \"multipart/form-data\" } }\n })\n\n /* handle success */\n .then( response => { console.log(response.data); } )\n\n /* handle error */\n .catch( response => { console.log(response) } );\n }\n }\n});\n```\n\n```html\n<script src=\"https://cdn.jsdelivr.net/npm/vue\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js\"></script>\n\n<div id=\"myApp\" >\n\n <form @submit=\"submit\" ref=\"formHTML\" >\n\n Name: <input type=\"text\" name=\"name\" v-model=\"form.name\" /><br />\n\n Gender:\n <input type=\"radio\" name=\"gender\" value=\"male\" v-model=\"form.gender\" /> Male\n <input type=\"radio\" name=\"gender\" value=\"female\" v-model=\"form.gender\" /> Female <br />\n\n File: <input type=\"file\" name=\"upload\" v-model=\"form.upload\" /><hr />\n\n <input type=\"submit\" name=\"submit\" value=\"Submit\" />\n\n </form>\n\n</div>\n```\n\n========================================\n\nComments:\n- I believe you'll have to call `formData.append()` on every variable. Why is it such a problem? Aren't you declaring them inside the axios call anyway? You'll just do it elsewhere.\n- @acdcjunior Thanks for the tip\n- After hours of test this is the only way it seems to work for me with an PHP script on the other end.","metadata":{"transformedAt":"2026-08-18T18:33:07.852Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":290,"estimatedTokens":1453}}249{"id":"stack-50919644","source":"stackoverflow","questionId":50919644,"title":"Extract CSS in NUXTjs generate","tags":["css","webpack","nuxt.js","generate"],"text":"Title: Extract CSS in NUXTjs generate\nTags: css, webpack, nuxt.js, generate\nSource: Stack Overflow\n\nQuestion:\nWhen using `nuxt generate` I am generating various HTML pages that happen to be about 300 kB in size. Majority of the file is CSS style placed inline to it. Is it a way to put it in an external file and reduce size of HTML ?\n\n========================================\n\nCode:\n```text\nnuxt generate\n```\n\n```text\nmodule.exports = {\n build: {\n extractCSS: true\n }\n}\n```\n\n```text\nmodule.exports = {\n css: [\n // Load a Node.js module directly (here it's a Sass file)\n 'bulma',\n // CSS file in the project\n '@/assets/css/main.css',\n // SCSS file in the project\n '@/assets/css/main.scss'\n ]\n}\n```\n\n========================================\n\nComments:\n- Define what you mean by *placed inline to it*, do you mean in the .vue files in the `` tag? Or do you mean inline in the traditional sense? Google, `extractCSS: true` which is most likely the option your after.","metadata":{"transformedAt":"2026-08-18T18:33:07.852Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":39,"estimatedTokens":247}}250{"id":"stack-60242552","source":"stackoverflow","questionId":60242552,"title":"VueJS: $router.push not working with query parameters","tags":["vue.js","vue-router","nuxt.js","query-string"],"text":"Title: VueJS: $router.push not working with query parameters\nTags: vue.js, vue-router, nuxt.js, query-string\nSource: Stack Overflow\n\nQuestion:\nIn my NuxtJS(v. 2.10.2) application, I have a URL like below where `pid` is a post's id.\n\n /post?pid=5e4844e34202d6075e593062\n\nThis URL works fine and loads the post as per the value passed to the `pid` query parameter. However, user can add new post by clicking `Add Post` button on the application bar that opens a dialog. Once the user clicks add, a request to back-end server is made to save the request. And once successful, user is redirected to the new post using vue router `push` like below\n\n```\n.then(data => {\n if (data) {\n this.$router.push({ path: `/post?pid=${data.id}` });\n }\n})\n```\n\nThe problem is, user is not redirected to the new post, only the query parameter `pid` is updated. I suspect VueJS does not acknowledge this as a different URL and hence does nothing.\n\nHow to fix this?\n\nUpdate: As an alternative tried the syntax below but getting the same behavior.\n\n```\nthis.$router.push({ path: \"post\", query: { pid: data.id } });\n```\n\n========================================\n\nTop Answer:\nSay you have a component `post.vue` which is mapped with `/post` URL. \n\nNow if you redirect the user to `/post?pid=13`, the `post.vue` **component won't mount again if it's already mounted** ie. when you are already at `/post` or `/post?pid=12`. \n\n[1] In this case, you can put a `watch` on the `route` to know if the route has been changed.\n\n```\nwatch: {\n '$route.path': {\n handler (oldUrl, newUrl) {\n let PID = this.$route.query.pid\n // fetch data for this PID from the server.\n // ...\n }\n }\n}\n```\n\nOR\n\n[2] If the component `post.vue` is mapped with some route say `/post`.\n\nYou can also use the lifecycle -> `beforeRouteUpdate` provided by `vue-router`\n\n```\nbeforeRouteUpdate (to, from, next) {\n let PID = to.query.pid\n // fetch data for this PID from the server.\n // ...\n next()\n}\n```\n\n========================================\n\nCode:\n```text\n.then(data => {\n if (data) {\n this.$router.push({ path: `/post?pid=${data.id}` });\n }\n})\n```\n\n```text\nthis.$router.push({ path: \"post\", query: { pid: data.id } });\n```\n\n```text\npid\n```\n\n```text\npid\n```\n\n```text\nAdd Post\n```\n\n```text\npush\n```\n\n```text\npid\n```\n\n```text\n.then(data => {\n if (data) {\n this.$router.push({ name: 'post', query: { pid: data.id } });\n }\n})\n```\n\n```text\nwatchQuery: [\"pid\"],\nasync asyncData(context) {\n let response = await context.$axios.$get(\n `http://localhost:8080/find/id/${context.route.query.pid}`\n );\n return { postData: response };\n},\ndata: () => ({\n postData: null\n})\n```\n\n```text\npid\n```\n\n```text\nwatchQuery\n```\n\n```text\nwatchQuery\n```\n\n```text\nwatchQuery\n```\n\n```text\npid\n```\n\n```text\nasyncData\n```\n\n```text\n.then(data => {\n if (data) {\n this.$router.push({ name: 'post', query: { pid: data.id } });\n }\n})\n```\n\n```text\n// with query, resulting in /register?plan=private\nrouter.push({ path: 'register', query: { plan: 'private' } })\n```\n\n```text\n.then(data => {\n if (data) {\n this.$router.push('/post?pid=' + data.id);\n }\n})\n```\n\n```text\nwatch: {\n '$route.path': {\n handler (oldUrl, newUrl) {\n let PID = this.$route.query.pid\n // fetch data for this PID from the server.\n // ...\n }\n }\n}\n```\n\n```text\nbeforeRouteUpdate (to, from, next) {\n let PID = to.query.pid\n // fetch data for this PID from the server.\n // ...\n next()\n}\n```\n\n```text\npost.vue\n```\n\n```text\n/post\n```\n\n```text\n/post?pid=13\n```\n\n```text\npost.vue\n```\n\n```text\n/post\n```\n\n```text\n/post?pid=12\n```\n\n```text\nwatch\n```\n\n```text\nroute\n```\n\n```text\npost.vue\n```\n\n```text\n/post\n```\n\n```text\nbeforeRouteUpdate\n```\n\n```text\nvue-router\n```\n\n```text\nexport default {\n watchQuery: true,\n data: () => ...\n}\n```\n\n```text\npath\n```\n\n```text\nrouter.push({path: 'route?query=params'})\n```\n\n```text\nrouter.push('route?query=params')\n```\n\n========================================\n\nComments:\n- that isn't the way to pass params, try with this\n- @ChristianCarrillo i tried `this.$router.push({ path: \"post\", query: { pid: data.id } });`. But getting the same behavior only the query parameter is updated, page is not redirected. Is it working for you?\n- try with `name` instead of `path`, previously set `name` property in your routes config\n- Please don't post only code as an answer, but include an explanation what your code does and how it solves the problem of the question. Answers with an explanation are generally of higher quality, and are more likely to attract upvotes.\n- This is actually what I was looking for!\n- This worked for me. Want to add here that if you open an email component (say) from clicking on notification bell icon header comp (sey) clicking on a different notification will not refresh the already open email component. Hence used watch as you suggested with a difference. In my case as the method to refresh is in a different component, with its corresponding html etc, used an eventBus to emit a flag which then reached the mounted of email component and refreshed API.\n- @shivam is it okay to just call router.go () ?\n- this is very simple put like in routes array { path: \"/add-party\", name: \"add-party\", component:AddParty }, and navigate using this this.$router.push({ name: 'add-party', query: { id: Id } });","metadata":{"transformedAt":"2026-08-18T18:33:07.852Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":265,"estimatedTokens":1318}}251{"id":"stack-58076195","source":"stackoverflow","questionId":58076195,"title":"Vue/Nuxt: How to make a component be truly dynamic?","tags":["vue.js","dynamic","nuxt.js","vue-dynamic-components"],"text":"Title: Vue/Nuxt: How to make a component be truly dynamic?\nTags: vue.js, dynamic, nuxt.js, vue-dynamic-components\nSource: Stack Overflow\n\nQuestion:\nIn order to use a dynamically-defined single page component, we use the `component` tag, thusly:\n\n```\n\n...\n\nimport DynamicComponent from '@/components/DynamicComponent.vue';\n\n...\ncomponents: {\n DynamicComponent\n},\n\nprops: {\n componentName: String,\n someProperty: null,\n}\n```\n\nThe problem is, this isn't really very dynamic at all, since every component we could ever possibly want to use here needs to be not only imported statically, but also registered in `components`.\n\nWe tried doing this, in order at least to avoid the need to import everything:\n\n```\ncreated() {\n import(`@/components/${this.componentName}.vue`);\n},\n```\n\nbut of course this fails, as it seems that `DynamicComponent` must be defined before reaching `created()`.\n\nHow can we use a component that is truly dynamic, i.e. imported and registered at runtime, given only its name?\n\n========================================\n\nTop Answer:\n**Solution for Nuxt only**\n\nAs of now its possible to auto-import components in Nuxt (`nuxt/components`). If you do so, you have a bunch of components ready to be registered whenever you use them in your vue template e.g.:\n\n```\n\n```\n\nIf you want to have truly dynamic components combined with `nuxt/components` you can make use of the way Nuxt prepares the components automagically. I created a package which enables dynamic components for auto-imported components (you can check it out here: `@blokwise/dynamic`).\n\nLong story short: with the package you are able to dynamically import your components like this:\n\n```\n\n```\n\nWhere `componentName` might be `'MyComponent'`. The name can either be statically stored in a variable or even be dynamically created through some API call to your backend / CMS.\n\nIf you are interested in how the underlying magic works you can checkout this article: Crank up auto import for dynamic Nuxt.js components\n\n========================================\n\nCode:\n```text\n<component v-bind:is=\"componentName\" :prop=\"someProperty\"/>\n\n...\n\nimport DynamicComponent from '@/components/DynamicComponent.vue';\n\n...\ncomponents: {\n DynamicComponent\n},\n\nprops: {\n componentName: String,\n someProperty: null,\n}\n```\n\n```text\ncreated() {\n import(`@/components/${this.componentName}.vue`);\n},\n```\n\n```text\ncomponent\n```\n\n```text\ncomponents\n```\n\n```text\nDynamicComponent\n```\n\n```text\ncreated()\n```\n\n```text\n<!-- Component changes when currentTabComponent changes -->\n<component v-bind:is=\"currentTabComponent\"></component>\n```\n\n```text\n<component :is=\"dynamic\" />\n```\n\n```text\nsetComponentName() {\n this.dynamic = () => import(`@/components/${this.componentName}.vue`);\n},\n```\n\n```text\ncurrentTabComponent\n```\n\n```text\ncurrentTabComponent\n```\n\n```text\nVue.component('componentName', function (resolve, reject) {\n requestTemplate().then(function (response) {\n // Pass the component definition to the resolve callback\n resolve({\n template: response\n })\n });\n})\n```\n\n```text\n<MyComponent some-property=\"some-value\" />\n```\n\n```text\n<NuxtDynamic :name=\"componentName\" some-property=\"some-value\" />\n```\n\n```text\nnuxt/components\n```\n\n```text\nnuxt/components\n```\n\n```text\n@blokwise/dynamic\n```\n\n```text\ncomponentName\n```\n\n```text\n'MyComponent'\n```\n\n```text\n// nuxt.config.js\nexport default {\n components: [{ path: \"~/components\", global: true }]\n}\n```\n\n```text\n<template>\n <div>\n <h2>Nuxt Dynamic Components</h2>\n <div v-for=\"name in ['test1', 'test2']\" :key=\"name\">\n <component :is=\"name\"></component>\n </div>\n </div>\n</template>\n```\n\n```text\n@nuxt/components\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- requestTemplate is not defined. We are using Nuxt, by the way. What is requestTemplate? Quick google search found nothing.\n- Also: I'm assuming this code should sit in created()? Is that correct?\n- no. it is just the component definition. you can write it in an external file and import it or just write it at the top. but the real template is in another file and is only loaded when needed. you simply use it in any template with v-bind:is and as soon as the component is needed, vue will start an ajax request and initialise the component.\n- if you use vue-cli you can use different syntax mentioned in the article I send, which will automatically compile to a version, where the component is loaded async. Otherwise you need to define your own api (requestTemplate function) to return the component. It is your own function, which requests the desired template from your own api.\n- Sorry, I'm not seeing any reference to any vue CLI command there. Oh, and one more thing: We render SSR. Does that change anything?\n- Wait... are you suggesting that this bit that says \" template: 'I am async!'\" here should be loading the contents of DynamicComponent.vue? In other words, we need to write code to read the file and put its contents here?\n- We just tested passing an actual .vue component into template, like \"template: 'do do do'\"... which fails. So it seems all we can do here is pass HTML, not an actual component. Or... I missing something here?\n- I guess I should also mention that we are using single page components (as defined by DynamicComponent.vue in the question), so this hard-coded HTML doesn't help us much. We would need a way to render a component to HTML given its name and prop values. Do you know of any such facility?\n- wow that just worked! we even see the async component being loaded dynamically from the server. so simple, when you know how! I'll just edit your answer to include the magic bit from your example.\n- this should be the accepted answer! great job with this package, works like a charm\n- Does it work with Nuxt 3?","metadata":{"transformedAt":"2026-08-18T18:33:07.852Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":206,"estimatedTokens":1452}}252{"id":"stack-55654115","source":"stackoverflow","questionId":55654115,"title":"How to disable Nuxt.js automatic file based route generation in favor of a manually generated routes.js file?","tags":["vue.js","router","nuxt.js"],"text":"Title: How to disable Nuxt.js automatic file based route generation in favor of a manually generated routes.js file?\nTags: vue.js, router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nAs we may know, **Nuxt.js** generates its routes by default based on the file structure of the **pages** folder.\n\nWhat I want to know is, how to use a file and put my routes by myself, manually, instead of have Nuxt.js generating them for me?\n\nWhy?\n\nI want more control of my routes, more explicit code and less files on the project.\n\nI think its more easy to setup route params defining them explicit into a **routes.js** file rather then setting them by adding files into the project.\n\nAny idea of how to do that, like on a normal Vue App? Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:07.852Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":16,"estimatedTokens":183}}253{"id":"stack-70464990","source":"stackoverflow","questionId":70464990,"title":"Nuxt3 useAsyncData not working onMounted lifecycle hook","tags":["nuxt.js","nuxt3.js"],"text":"Title: Nuxt3 useAsyncData not working onMounted lifecycle hook\nTags: nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm still a bit confused on what I'm doing wrong here. Essentially I have a vue component in which I want to load some data in async after element is mounted.\n\nI'm using NUXT 3 and composition API.\n\n```\n\nlet directories = useState('directories', () => null);\n\nonMounted( async () => {\nconst { data: response } = await useAsyncData('directories', () => $fetch('/api/s3-get-directories'));\ndirectories.value = response;\n});\n\n```\n\nIt seems like onMounted triggers before render and is not receiving data correctly. If I wrap on mounted into setTimeout and give 100ms delay it works fine.\n\nI would appreciate an example of how I should load in data without blocking after client is ready. Or any explanation on what I'm doing wrong here.\n\n========================================\n\nCode:\n```text\n<script setup>\n\nlet directories = useState('directories', () => null);\n\nonMounted( async () => {\nconst { data: response } = await useAsyncData('directories', () => $fetch('/api/s3-get-directories'));\ndirectories.value = response;\n});\n\n</script>\n```\n\n```js\nawait useLazyAsyncData('directories', () => $fetch('/api/s3-get-directories'), { server: false });\n```\n\n```text\n{ server: false }\n```\n\n========================================\n\nComments:\n- why are you using useAsyncData inside onMounted hook it's kind of strange if you want get data in client side you can just fetch that data inside onMounted without asyncData or if you really need it you can just call it with `server:false` option\n- So why is it not working? I have the same question\n- @MaxFlex `onMounted` is a life-cycle hook. `asyncData` is too. Mixing those 2 is counter-intuitive and makes no sense. It's like calling a `beforeMount` and `updated` in Vue, makes no sense use one or the other.\n- @kissu Konstantin, thanks for the response. Is `useFetch` a life-cycle hook too? I'm having this issue with `useFetch`, I just want to load data `onMounted` – which seems totally intuitive\n- @MaxFlex hm, it's maybe not exactly a lifecycle actually but still behaving not like people think it is. Check this video from Alex Lichter to see how to use it properly: youtu.be/njsGVmcWviY?si=S-ShGN8mRTLz0wK8\n- if you need prerender data and SEO , it's totally wrong and your data will fetch in client side it's almost equal to fetch data in onMounted\n- @zia can you give the solution on how to do it properly? I have been stuck with this problem too.\n- `const { pending, data }=await useLazyAsyncData('directories', () => $fetch('/api/s3-get-directories'));` you should not pass server:false if you need prerender and seo","metadata":{"transformedAt":"2026-08-18T18:33:07.852Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":59,"estimatedTokens":675}}254{"id":"stack-74025876","source":"stackoverflow","questionId":74025876,"title":"Vue 3 / Nuxt 3 Scoped slot with generic data type inferred from props","tags":["typescript","vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: Vue 3 / Nuxt 3 Scoped slot with generic data type inferred from props\nTags: typescript, vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI want to implement a carousel component in Nuxt v3. The component receives an array of items. The component only implements the logic, not the styling or structuring.\n\nHere is my component now:\n\n`components/tdx/carousel.vue`\n\n```\n\n \n \n \n \n \n \n \n\nconst props = defineProps({\n items: {\n type: [],\n required: true,\n },\n spotlight: {\n type: Number,\n default: 1,\n validator(value: number) {\n return value > 0;\n },\n },\n});\n\n```\n\nThe logic of the carousel here is not important.\n\nIn the parent component I then can use the component like this:\n\n```\n\n \n \n \n {{ title }}\n\n \n {{ description }}\n\n \n \n \n\nconst exampleArray = ref([\n {\n title: 'Item 1',\n description: 'Desc of item 1',\n },\n {\n title: 'Item 2',\n description: 'Desc of item 2',\n },\n]);\n\n```\n\nThis works fine. What I want in addition to this is typings. The types of `title` and `description` are of course any since in the props of `carousel.vue` the type of the items is `unknown[]`.\n\nI found this article that show how to make a generic component but I don't want this since I would have to mess with the auto import system from nuxt.\n\nHow can I achieve type inference from the given items in the `carousel.vue` props?\n\n========================================\n\nCode:\n```html\n<template>\n <div>\n <slot name=\"last\"></slot>\n <div v-for=\"item in items\">\n <slot\n name=\"item\"\n v-bind=\"item\"\n ></slot>\n </div>\n <slot name=\"next\"></slot>\n </div>\n</template>\n\n<script setup lang=\"ts\">\nconst props = defineProps({\n items: {\n type: [],\n required: true,\n },\n spotlight: {\n type: Number,\n default: 1,\n validator(value: number) {\n return value > 0;\n },\n },\n});\n</script>\n```\n\n```html\n<template>\n <div class=\"container\">\n <TdxCarousel :items=\"exampleArray\">\n <template #item=\"{ title, description }\">\n <p class=\"font-semibold text-2xl\">{{ title }}</p>\n <hr />\n <p>{{ description }}</p>\n </template>\n </TdxCarousel>\n </div>\n</template>\n\n<script setup lang=\"ts\">\nconst exampleArray = ref([\n {\n title: 'Item 1',\n description: 'Desc of item 1',\n },\n {\n title: 'Item 2',\n description: 'Desc of item 2',\n },\n]);\n</script>\n```\n\n```text\ncomponents/tdx/carousel.vue\n```\n\n```text\ntitle\n```\n\n```text\ndescription\n```\n\n```text\ncarousel.vue\n```\n\n```text\nunknown[]\n```\n\n```text\ncarousel.vue\n```\n\n```html\n<script setup lang=\"ts\" generic=\"T extends any\">\nwithDefaults(\n defineProps<{ items: T[]; spotlight?: number }>(), {\n spotlight: 1,\n});\n</script>\n<template>\n <div>\n <slot name=\"last\"></slot>\n <div v-for=\"item in items\">\n <slot\n name=\"item\"\n v-bind=\"item\">\n </slot>\n </div>\n <slot name=\"next\"></slot>\n </div>\n</template>\n```\n\n```json\n// tsconfig.json\n{\n // ...\n \"vueCompilerOptions\": {\n \"experimentalRfc436\": true\n }\n}\n```\n\n```text\ncarousel.vue\n```\n\n```text\ngeneric\n```\n\n```text\n<script setup>\n```\n\n```text\ndefineProps\n```\n\n```text\nexperimentalRfc436\n```\n\n```text\nvueCompilerOptions\n```\n\n========================================\n\nComments:\n- I have no idea on how to help you with this question but wanted to say that your question is well written (not common here). Good luck!\n- Well thanks I guess xD\n- @kissu he wants something like in this tip, this is not achievable easily in template/script setup syntax, but he can do that with TSX syntax\n- Your use case is exactly the same as mentioned here\n- This would have solved my problem perfectly but I didn't bring this to work with nuxt. I suspect this is because of the autoimport feature of nuxt, since there I cannot declare the type :(\n- You can define the type of the `props.items` to `any[]` and cast the type of your variables when using like that: `#item=\"{ title, description }: { title: string, description: string}\"` This approach is not the solution but at least it helps on typing\n- @Duannx for now this is a good workaround, thanks\n- Thanks for the answer. I have already tried that. I suppose this works with vue3. With nuxt3 this does not work because of the auto imports. This is a great answer but I am not going to accept it. I think this is a problem for a lot of people. We will probably see a more worked out solution to this problem in the next few months (atleast I believe it) where I hope that nuxt also supports this :)\n- In the latest vue release this is now officially supported. blog.vuejs.org/posts/vue-3-3#generic-components Do you wan't to update your answer? Will accept it once updated. If not I can provide an updated answer\n- @GionRubitschung I've updated the answer to explain official support.\n- It doesn't work for event listener props: stackoverflow.com/questions/78730081/…","metadata":{"transformedAt":"2026-08-18T18:33:07.852Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":228,"estimatedTokens":1208}}255{"id":"stack-44976159","source":"stackoverflow","questionId":44976159,"title":"How to include static assets dynamically with nuxt generate?","tags":["vuejs2","nuxt.js"],"text":"Title: How to include static assets dynamically with nuxt generate?\nTags: vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm working on a static site using Nuxt.js (I target to publish just the result of `nuxt generate`).\n\nThe content is generated based on `asyncData` by calling a json API.\n\n*I want to grab some files and include them as if they were in the `/static` directory, depending on the API response. How could that be achieved?*\n\nTo better illustrate the problem: Let's say there is a list of invoices coming from the API, so in the resulting page I show the invoice info, but I also want to include a download link to it's corresponding file (which I can resolve after knowing the API response).\n\nMaybe this task should be done outside of nuxt.js, after the site generation?\n\n========================================\n\nCode:\n```text\nnuxt generate\n```\n\n```text\nasyncData\n```\n\n```text\n/static\n```\n\n```text\nstatic\n```\n\n```text\ndist\n```\n\n```text\nstatic\n```\n\n```text\nstatic\n```\n\n```text\nnuxt generate\n```\n\n========================================\n\nComments:\n- I don't get ready-to-go solution, but I think you should take a look on nuxt module to do that. nuxtjs.org/guide/modules\n- I don't really understand the problem. If you have a list of invoices,why can't this list not already include a link to a file,which is situated in the `/static` folder? That would mean you could generate normally and the pages include links to your files. All good... Or do I misunderstand?\n- @Merc The list of invoices is dynamic, I call a 3rd party API in the àsyncData` method in order to build it. That list includes the file location (in this case it's a shared drive accessible from the vpn), so the file is not in `/static` yet, I would need to copy it first. The problem is that copy step. Hope it clarify what was the problem\n- Puh, if you need to copy your files dynamically from a VPN protected shared drive on each generate, this is gonna require some special tasks, that have nothing to with nuxt. Where do you publish you app? For example on netlify you could run `nuxt generate && npm run copy` your `copy` task you then have to start a node script which does all the copying and within your nuxt component, you just provide links to the files you are going to copy to `/dist`. I think this would probably be it, but it seems quite tedious and a difficult task. Maybe there are simpler solutions.\n- Will those files change all the time over time? If so I would rather try to make that drive folder public and link directly to those files. Or if they stay the same, I would download the manually into the static folder. Messing around with node copying your files from a vpn protected shared drive folder into your `/dist` folder seems a bit overkill.\n- Thanks for your help! I agree that this scenario is too specific for my needs, and I don't expect nuxt to address all these requeriments. The `nuxt generate && npm run copy` approach is good enough. Reading the docs now, I guess another alternative is to write a custom `buildModule`. I am not working on this project anymore, but I will fiddle with custom modules if I have some spare time. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:07.852Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":59,"estimatedTokens":796}}256{"id":"stack-72252942","source":"stackoverflow","questionId":72252942,"title":"How to get current domain at Nuxt 3 middleware?","tags":["nuxt.js","nuxt3.js"],"text":"Title: How to get current domain at Nuxt 3 middleware?\nTags: nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI can't use window.location here because it's SSR app.\nuseRouter, useRoute, and useNuxtApp don't have domain name too.\nnuxtApp.ssrContext is undefined.\n\n```\nexport default defineNuxtRouteMiddleware((to: any, from: any) => {\n console.log(\"GET HOST HERE\")\n})\n```\n\n========================================\n\nTop Answer:\nI just missed to check process.server before getting nuxtApp.ssrContext. This is the answer to my question:\n\n```\nexport default defineNuxtRouteMiddleware((to: any, from: any) => {\n const nuxtApp = useNuxtApp()\n let host = ''\n if(process.server) {\n // for 3.0.0.rc_vercions: host = nuxtApp.ssrContext.req.headers.host\n // UPD 27.01.23:\n host = nuxtApp.ssrContext?.event.node.req.headers.host\n } else {\n host = window.location.host\n }\n})\n```\n\n========================================\n\nCode:\n```js\nexport default defineNuxtRouteMiddleware((to: any, from: any) => {\n console.log(\"GET HOST HERE\")\n})\n```\n\n```js\nconst url = useRequestURL()\n\nconst currentUrl = url.href // https://example.com:3000/hello-world \nconst protocol = url.protocol // https:\nconst host = url.host // example.com:3000\nconst hostname = url.hostname // example.com\nconst pathname = url.pathname // /hello-world\n```\n\n```js\nconst hostname = useRequestURL().hostname\n```\n\n```text\nuseRequestURL()\n```\n\n```text\nuseRequestURL()\n```\n\n```text\nprocess.server\n```\n\n```js\nexport default defineNuxtRouteMiddleware((to: any, from: any) => {\n const nuxtApp = useNuxtApp()\n let host = ''\n if(process.server) {\n // for 3.0.0.rc_vercions: host = nuxtApp.ssrContext.req.headers.host\n // UPD 27.01.23:\n host = nuxtApp.ssrContext?.event.node.req.headers.host\n } else {\n host = window.location.host\n }\n})\n```\n\n```js\nuseNuxtApp().ssrContext.event.node.req.headers.host\n```\n\n```js\nuseNuxtApp().ssrContext.req.headers.host\n```\n\n```text\nuseRequestHeaders()?.host\n```\n\n========================================\n\nComments:\n- Couldn't you use an env variable? Otherwise, making an express endpoint and getting `request.headers.host` I guess.\n- @kissu I have to know host dynamically because I have many subdomains in my app. Can I get host without sending request to express?\n- If your app is SSR, what is the issue of sending a call to a local route? What is the actual idea?\n- Yeah, Nuxt runs on both server and client (isomorphic). Feel free to accept your own question when you'll be able to.\n- This no longer works in Nuxt 3 after production release.\n- You have to change it to `nuxtApp.ssrContext?.event.node.req.headers.host` to make it work in Nuxt 3, but it still works.","metadata":{"transformedAt":"2026-08-18T18:33:07.852Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":104,"estimatedTokens":672}}257{"id":"stack-69953025","source":"stackoverflow","questionId":69953025,"title":"Nuxt 3 - resolver.resolveModule is not a function","tags":["javascript","nuxt.js","nuxt3.js"],"text":"Title: Nuxt 3 - resolver.resolveModule is not a function\nTags: javascript, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI want to configure `style-resources` and use some variables globally in fresh Nuxt 3 project but when I am passing some options to nuxt.config file I am getting this error:\n\n`Cannot start nuxt: resolver.resolveModule is not a function`\n\nMy dependencies:\n\n```\n\"devDependencies\": {\n \"nuxt3\": \"latest\",\n \"prettier\": \"^2.4.1\"\n },\n \"dependencies\": {\n \"@nuxtjs/style-resources\": \"^1.2.1\",\n \"sass\": \"^1.43.4\"\n }\n```\n\nnuxt.config.js\n\n```\nexport default defineNuxtConfig({\n css: ['~/assets/main.scss'],\n buildModules: ['@nuxtjs/style-resources'],\n styleResources: {\n scss: ['./assets/variables.scss'],\n },\n});\n```\n\nI am using this library:\nhttps://github.com/nuxt-community/style-resources-module\n\nI know Nuxt 3 is still in Beta release but maybe someone faced this issue already or knows different way to apply global resources\n\n========================================\n\nCode:\n```text\n\"devDependencies\": {\n \"nuxt3\": \"latest\",\n \"prettier\": \"^2.4.1\"\n },\n \"dependencies\": {\n \"@nuxtjs/style-resources\": \"^1.2.1\",\n \"sass\": \"^1.43.4\"\n }\n```\n\n```text\nexport default defineNuxtConfig({\n css: ['~/assets/main.scss'],\n buildModules: ['@nuxtjs/style-resources'],\n styleResources: {\n scss: ['./assets/variables.scss'],\n },\n});\n```\n\n```text\nstyle-resources\n```\n\n```text\nCannot start nuxt: resolver.resolveModule is not a function\n```\n\n```text\nvite: {\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: '@import \"@/assets/scss/variables.scss\";',\n },\n },\n },\n }\n```\n\n========================================\n\nComments:\n- Thanks for posting this! This fixed it for me.\n- Thank you! I can't seem to find anything about this in their documentation. I've spent the last hour trying to get this to work\n- Can u show, how to do it for stylus?\n- any way to do this with Nitro?","metadata":{"transformedAt":"2026-08-18T18:33:07.852Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":90,"estimatedTokens":498}}258{"id":"stack-49919863","source":"stackoverflow","questionId":49919863,"title":"get v-id-xx value for scoped css on Vue Single File Component","tags":["javascript","vue.js","nuxt.js"],"text":"Title: get v-id-xx value for scoped css on Vue Single File Component\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhen adding elements via pure js on Vue Single File Component, the added elements don't have v-id-xx attribute for scoped css.\n\nHow can I get THE component's v-id-hash value by pure js?\n\n========================================\n\nTop Answer:\nIn a Vue 3 directive, we can get the component's scope ID using the `binding` parameter available in directive lifecycle hooks.\n\nExample:\n\nIn mounted hooks:\n\n```\nmounted(el, binding, vnode, prevVnode) {\n const span = document.createElement(\"span\");\n console.log(\"scope_id\", binding.instance.$options.__scopeId);\n span.setAttribute(binding.instance.$options.__scopeId, \"\");\n el.appendChild(span);\n},\n```\n\nIn the DOM, the element we will have the scope ID attached. Now we don’t need to use `:deep()` or `/deep/` anymore for the directive-created element.\n\n```\n\n```\n\n========================================\n\nCode:\n```js\nthis.$options._scopeId // returns something like 'data-v-763db97b'\n```\n\n```js\nsomElement.setAttribute(this.$options._scopeId, \"\");\n```\n\n```js\nmounted(el, binding, vnode, prevVnode) {\n const span = document.createElement(\"span\");\n console.log(\"scope_id\", binding.instance.$options.__scopeId);\n span.setAttribute(binding.instance.$options.__scopeId, \"\");\n el.appendChild(span);\n},\n```\n\n```html\n<span data-v-0fb92912=\"\"></span>\n```\n\n```text\nbinding\n```\n\n```text\n:deep()\n```\n\n```text\n/deep/\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.852Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":68,"estimatedTokens":373}}259{"id":"stack-59918278","source":"stackoverflow","questionId":59918278,"title":"Fetch query string value from URL with NuxtJS and AsyncData method","tags":["typescript","nuxt.js","asyncdata"],"text":"Title: Fetch query string value from URL with NuxtJS and AsyncData method\nTags: typescript, nuxt.js, asyncdata\nSource: Stack Overflow\n\nQuestion:\nI try to fetch value of the name parameter in URL: http://fakelocalhost:3000/page?name=test\n\nI'm using **NuxtJS** (v2.11.0) and **TypeScript**, with *nuxt-property-decorator* package (v2.5.0).\n\nBut, I get an undefined result with `console.log(params.name)`.\n\nHere, my full TS code:\n\n```\n\n import {\n Component,\n Vue\n } from \"nuxt-property-decorator\";\n\n @Component({\n asyncData({ params }) {\n console.log(params.name);\n }\n })\n export default class extends Vue {}\n\n```\n\n========================================\n\nTop Answer:\nYou can also use the context parameter: query\nhttps://nuxtjs.org/docs/2.x/internals-glossary/context#query\n\n```\nasyncData({ query }) {\n console.log(query.name);\n}\n```\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n import {\n Component,\n Vue\n } from \"nuxt-property-decorator\";\n\n @Component({\n asyncData({ params }) {\n console.log(params.name);\n }\n })\n export default class extends Vue {}\n</script>\n```\n\n```text\nconsole.log(params.name)\n```\n\n```text\nasyncData({ route }) {\n console.log(route.query.name);\n}\n```\n\n```text\nasyncData({ query }) {\n console.log(query.name);\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.852Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":75,"estimatedTokens":324}}260{"id":"stack-60336236","source":"stackoverflow","questionId":60336236,"title":"NuxtJS set Cookie in Middleware","tags":["javascript","cookies","nuxt.js"],"text":"Title: NuxtJS set Cookie in Middleware\nTags: javascript, cookies, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a nuxtjs app and try to set a cookie from a global middleware. I found this contribution on GitHub which shows a method to do this.\n\nSo I implemented my middleware like this\n\n```\nexport default function ({ isServer, res, query }) {\n if (query.lang) {\n if (isServer) {\n res.setHeader(\"Set Cookie\", [`lang=${query.lang}`]);\n } else {\n document.cookie = `lang=${query.lang}`;\n }\n }\n}\n```\n\nMy problem is that when I visit my app with `?lang=xxx` as a parameter, I'm always running into the else block of my if condition. So I get the error\n\n```\ndocument is not defined\n```\n\nHas anyone a idea what is wrong with my code. I can't see a difference to the code published on github.\n\n========================================\n\nTop Answer:\nIn Nuxt 3 and Nuxt 2 Bridge you can use `useCookie`\n\nNuxt provides an SSR-friendly composable to read and write cookies.\n\n```\nconst lang = useCookie('lang')\nlang.value = ''\n```\n\n========================================\n\nCode:\n```text\nexport default function ({ isServer, res, query }) {\n if (query.lang) {\n if (isServer) {\n res.setHeader(\"Set Cookie\", [`lang=${query.lang}`]);\n } else {\n document.cookie = `lang=${query.lang}`;\n }\n }\n}\n```\n\n```text\ndocument is not defined\n```\n\n```text\n?lang=xxx\n```\n\n```js\nasync nuxtServerInit({ commit, state, dispatch },\n { app, store, route, req, res, error, redirect }\n) {\n app.$cookiz.set('lang', route.query.lang)\n})\n```\n\n```js\nexport default function ({ app, res, query }) {\n if (query.lang) {\n app.$cookiz.set('lang', query.lang)\n }\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n['cookie-universal-nuxt', { alias: 'cookiz' }],\n```\n\n```text\nnuxtServerInit\n```\n\n```js\nexport default function (req, res, next) {\n let cookie = getCookie(req, '_id') || 'random_value'\n setCookie(res, '_id', cookie)\n\n// Don't forget to call next at the end if your middleware is not an endpoint\n next()\n}\n```\n\n```js\nexport default defineNextConfig({\n // ...\n router: {\n middleware: [\"cookies\"],\n }\n})\n```\n\n```text\nmiddlewares/cookies.ts\n```\n\n```text\nnuxt.config.ts\n```\n\n```js\nconst lang = useCookie('lang')\nlang.value = ''\n```\n\n```text\nuseCookie\n```\n\n```js\nexport function getCookie(name, stringCookie) {\n const matches = stringCookie.match(\n new RegExp(\n `(?:^|; )${name.replace(/([.$?*|{}()[\\]\\\\/+^])/g, '\\\\$1')}=([^;]*)`,\n ),\n );\n return matches ? decodeURIComponent(matches[1]) : undefined;\n}\n```\n\n========================================\n\nComments:\n- i have faced an issue with nuxt production build, it simply won't set any cookies from a page or component\n- This does not set cookies on the server side, only client-side, there is any way to set cookies on the server side?\n- Consider Writing some text, explaining your answer.","metadata":{"transformedAt":"2026-08-18T18:33:07.852Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":145,"estimatedTokens":713}}261{"id":"stack-74261193","source":"stackoverflow","questionId":74261193,"title":"Nuxt 3 - how to remove trailing slash?","tags":["nuxt.js","nuxt3.js"],"text":"Title: Nuxt 3 - how to remove trailing slash?\nTags: nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nIn Nuxt 3, how to remove trailing slash from urls?\n\nIn Nuxt 2, it was done by adding these lines to `nuxt.config.js`:\n\n```\nrouter: {\n trailingSlash: false\n }\n```\n\nWhat is the equivalent in Nuxt 3?\n\n========================================\n\nTop Answer:\nBased on @evg_ny's answer, I created this version which will work with Nuxt3 to redirect routes with the trailing slash to the non-trailing slash variant:\n\n```\nexport default defineNuxtRouteMiddleware((to, from) => {\n if (to.path !== '/' && to.path.endsWith('/')) {\n const { path, query, hash } = to;\n const nextPath = path.replace(/\\/+$/, '') || '/';\n const nextRoute = { path: nextPath, query, hash };\n return navigateTo(nextRoute, { redirectCode: 301 });\n }\n})\n```\n\nSave it in `./middleware/redirect-trailing-slash.global.js` and it'll work globally\n\n========================================\n\nCode:\n```text\nrouter: {\n trailingSlash: false\n }\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ntrailingSlash\n```\n\n```text\nstrict\n```\n\n```text\nfalse\n```\n\n```js\nexport default function ({ route, redirect }) {\n if (route.path !== '/' && route.path.endsWith('/')) {\n const { path, query, hash } = route;\n const nextPath = path.replace(/\\/+$/, '') || '/';\n const nextRoute = { path: nextPath, query, hash };\n\n return navigateTo(nextRoute, { redirectCode: 301 });\n }\n}\n```\n\n```js\nexport default defineNuxtRouteMiddleware((to, from) => {\n if (to.path !== '/' && to.path.endsWith('/')) {\n const { path, query, hash } = to;\n const nextPath = path.replace(/\\/+$/, '') || '/';\n const nextRoute = { path: nextPath, query, hash };\n return navigateTo(nextRoute, { redirectCode: 301 });\n }\n})\n```\n\n```text\n./middleware/redirect-trailing-slash.global.js\n```\n\n```text\n# BEFORE\n#RewriteEngine On\n#RewriteBase /\n#RewriteRule ^index\\.html$ - [L]\n#RewriteCond %{REQUEST_FILENAME} !-f\n#RewriteCond %{REQUEST_FILENAME} !-d\n#RewriteRule . /index.html [L] # For non-SSR, serve the root index.html\n\n\n# AFTER, WITH SSR\nDirectorySlash Off # Turn off trailing slash\n\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.html$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\n#RewriteCond %{REQUEST_FILENAME} !-d # Omit for SSR because there is a physical directory\nRewriteRule ^(.*)$ $1/index.html [L]\n#RewriteRule . /index.html [L] # Omit for SSR because the served file is the requested dir's index.html (rather than the root index.html)\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\nhttps://mynuxtproject.com//evil.example.com/\n```\n\n```text\n//evil.example.com\n```\n\n========================================\n\nComments:\n- Just to make it easier for anyone, the replacement code in nuxt.config is {router:{options:{strict: true}}}\n- This does not do anything basically. Your routes are just not going to render on a trailing slash request. So you can still visit `/page/` it will just display empty. Check github.com/nuxt/nuxt/issues/15462#issuecomment-1407374859\n- For the sake of clarity: this option is for when you want to disable trailing slashes completely (and trigger a 404 not found for URLs with a trailing slash), not for redirecting from an URL with trailing slash to one without.\n- Thanks, I mentioned it in github.com/nuxt/nuxt/issues/15462#issuecomment-1407374859\n- Awesome. I wish Nuxt shipped with a bunch of default middleware like Laravel\n- This works correctly, and is the right way to redirect an URL with trailing slash to an URL without it.\n- This creates an infinite redirect if you refresh the page.\n- This has been my challenge for a long time. I appreciate your contribution.","metadata":{"transformedAt":"2026-08-18T18:33:07.853Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":140,"estimatedTokens":923}}262{"id":"stack-72016669","source":"stackoverflow","questionId":72016669,"title":"How to config vite HMR port in Nuxt3 config?","tags":["nuxt.js","vite"],"text":"Title: How to config vite HMR port in Nuxt3 config?\nTags: nuxt.js, vite\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt3 within a Docker compose setup where port 8001 is the accessible port for the node container running Nuxt3 channeled via an nginx reverse proxy.\n\nMy nuxt.config.ts looks like this:\n\n```\nimport { defineNuxtConfig } from 'nuxt'\n\n// https://v3.nuxtjs.org/api/configuration/nuxt.config\nexport default defineNuxtConfig({\n vite: {\n server: {\n hmr: {\n clientPort: 8001,\n }\n }\n }\n})\n```\n\nSomehow it seems the clientPort setting for the HMR of vite is not picked up by Nuxt3. The page is constantly reloading in the dev setup.\n\nAny idea whether I've misconfigured this or this is not yet possible in Nuxt3?\n\nIn a similar setup with Vue this setting in the vite.config.js is working properly?\n\n========================================\n\nTop Answer:\nyou need to add this port beside the main port like in your docker-compose.yaml\n\n```\nports:\n - \"3000:3000\"\n - \"24678:24678\"\n```\n\nalso be sure the vite config is like\n\n```\n//nuxt.config.{js,ts}\nexport default defineNuxtConfig({\n vite: {\n server: {\n hmr: {\n protocol: \"ws\",\n host: \"0.0.0.0\",\n },\n },\n },\n});\n```\n\n========================================\n\nCode:\n```js\nimport { defineNuxtConfig } from 'nuxt'\n\n// https://v3.nuxtjs.org/api/configuration/nuxt.config\nexport default defineNuxtConfig({\n vite: {\n server: {\n hmr: {\n clientPort: 8001,\n }\n }\n }\n})\n```\n\n```text\n# Your Nuxt 3 service\n\n ports:\n - \"24678:24678\" # or in your case: - \"8001:8001\"\n```\n\n```text\nexport default {\n server: {\n hmr: {\n protocol: 'ws',\n host: '0.0.0.0',\n }\n }\n}\n```\n\n```text\n:24678\n```\n\n```text\nvite.config.js\n```\n\n```text\nports:\n - \"3000:3000\"\n - \"24678:24678\"\n```\n\n```text\n//nuxt.config.{js,ts}\nexport default defineNuxtConfig({\n vite: {\n server: {\n hmr: {\n protocol: \"ws\",\n host: \"0.0.0.0\",\n },\n },\n },\n});\n```\n\n```bash\nexport default defineNuxtConfig({\n devtools: { enabled: true },\n vite: {\n server: {\n hmr: {\n protocol: 'ws',\n host: '0.0.0.0', \n }\n }\n }});\n```\n\n```bash\nports:\n - 3000:3000\n - 24678:24678\n```\n\n```bash\nexport default defineNuxtConfig({\n devtools: { enabled: true },\ndevServer: {\n host: \"0.0.0.0\",\n port: 8000, // you can replace this port with any port\n }});\n```\n\n```bash\nports:\n - 8000:8000\n```\n\n```text\nhooks: {\n 'vite:extendConfig': (config) => {\n if (typeof config.server!.hmr === 'object') {\n config.server!.hmr.protocol = 'wss';\n }\n },\n },\n```\n\n```text\nnuxt.config\n```\n\n```text\nvite: {\n server: {\n watch: {\n usePolling: true\n }\n }\n }\n```\n\n```text\nCMD npm run dev -- --host 0.0.0.0\n```\n\n```text\n24678\n```\n\n```text\ndocker-compose\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nDockerfile\n```\n\n========================================\n\nComments:\n- Thank you! Adding a vite.config.js with these settings did not work, but opening port 24678 to the node container did work!\n- Man, opening port 24678 was absolute nugget! Was looking for that whole day. Thank you!\n- With Nuxt 3.2.3 seems to not working.. I get GET localhost:3010/_nuxt net::ERR_EMPTY_RESPONSE error every time. Where actualy the _nuxt folder should be? I can't find it.\n- Working like a charm. I used in nuxt 3.x configuration. Be aware that nuxt documentation says no all vite configuration can be used within nuxt 3.x Maybe it will change in the future version. I don`t know","metadata":{"transformedAt":"2026-08-18T18:33:07.853Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":205,"estimatedTokens":879}}263{"id":"stack-56350912","source":"stackoverflow","questionId":56350912,"title":"Nuxt application taking more than 4 minutes to compile","tags":["nuxt.js"],"text":"Title: Nuxt application taking more than 4 minutes to compile\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a Nuxt application. I've done some research but found no definitive solution.\n\nI've found a GitHub issue with something similar (https://github.com/nuxt/nuxt.js/issues/3486) but wasn't able to find a definitive solution:\n\nhttps://i.sstatic.net/v4fsE.png\n\nIt was compiling \"normally\", not taking more than 1 minute. I've just added around 300 lines of html to a Vue component. Suddenly went extremely low.\n\nThere are no explicit errors, alerts or warning messages, only the performance went extremely low. How to track this performance decrease?\n\nSo this is the nuxt.config.js file \n\n```\nconst pkg = require('./package')\nconst webpack = require(\"webpack\")\n\nmodule.exports = {\n mode: 'universal',\n debug: true,\n prettify: false,\n /*\n ** Headers of the page\n */\n head: {\n title: pkg.name,\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: pkg.description }\n ],\n script: [\n { src: \"https://cdn.jsdelivr.net/npm/sweetalert2@8\" },\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n\n /*\n ** Customize the progress-bar color\n */\n loading: { color: '#fff' },\n\n buildDir: '../functions/nuxt',\n\n build:{\n publicPath: '/',\n vendor: ['axios','firebase', \"jquery\", 'popper', \"bootstrap\", 'bootbox'],\n extractCSS: true,\n babel: {\n presets: [\n 'es2015',\n 'stage-0'\n ],\n plugins: [\n\n [\n \"transform-runtime\",\n {\n \"polyfill\":true,\n \"regenerator\":true\n },\n \"~/plugins/firebase.js\",\n \"~/plugins/bootboxPlugin.js\"\n ],\n new webpack.ProvidePlugin({\n jQuery: 'jquery',\n $: 'jquery',\n jquery: 'jquery'\n })\n ]\n\n },\n prettify: false\n },\n /*\n ** Global CSS\n */\n css: [\n 'bootstrap/dist/css/bootstrap.css'\n ],\n\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n\n ],\n\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://bootstrap-vue.js.org/docs/\n 'bootstrap-vue/nuxt',\n '@nuxtjs/pwa',\n ],\n\n /*\n ** Build configuration\n */\n\n build: {\n prettify: false,\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n config.devtool = ctx.isClient ? 'eval-source-map' : 'inline-source-map'\n prettify = false\n }\n }\n}\n```\n\nI'm not sure where the prettify : false directive should go, so I've tried in many places, because I'm not sure where the vueLoader is happening.\n\nAlso in the Nuxt documentation says\n\n Note: This config has been removed since Nuxt 2.0, please use build.loaders.vue instead.\n\nSo this made me more confused. Where this build.loaders.vue is happening?\n\n========================================\n\nTop Answer:\n*(Posted on behalf of the question author, to move it to the answer space)*.\n\nSo the final solution is this\n\n### nuxt.config.js\n\n```\nmodule.exports { //or export default {\n\nbuild: {\n publicPath: '/',\n vendor: ['axios','firebase', \"jquery\", 'popper', \"bootstrap\", 'bootbox'],\n extractCSS: true,\n babel: {\n presets: [\n 'es2015',\n 'stage-0'\n ],\n plugins: [\n\n [\n \"transform-runtime\",\n {\n \"polyfill\":true,\n \"regenerator\":true\n },\n \"~/plugins/firebase.js\",\n \n new webpack.ProvidePlugin({\n jQuery: 'jquery',\n $: 'jquery',\n jquery: 'jquery'\n })\n ],\n \n ]\n\n },\n // adding the below object made the compilation time go up again to \n //\"normal\" \n loaders: {\n vue: {\n prettify: false\n }\n },\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n config.devtool = ctx.isClient ? 'eval-source-map' : 'inline-source-map'\n \n }\n }\n\n}\n```\n\nThanks for @Aldarund for the support.\n\n========================================\n\nCode:\n```text\nconst pkg = require('./package')\nconst webpack = require(\"webpack\")\n\nmodule.exports = {\n mode: 'universal',\n debug: true,\n prettify: false,\n /*\n ** Headers of the page\n */\n head: {\n title: pkg.name,\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: pkg.description }\n ],\n script: [\n { src: \"https://cdn.jsdelivr.net/npm/sweetalert2@8\" },\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n\n /*\n ** Customize the progress-bar color\n */\n loading: { color: '#fff' },\n\n buildDir: '../functions/nuxt',\n\n build:{\n publicPath: '/',\n vendor: ['axios','firebase', \"jquery\", 'popper', \"bootstrap\", 'bootbox'],\n extractCSS: true,\n babel: {\n presets: [\n 'es2015',\n 'stage-0'\n ],\n plugins: [\n\n [\n \"transform-runtime\",\n {\n \"polyfill\":true,\n \"regenerator\":true\n },\n \"~/plugins/firebase.js\",\n \"~/plugins/bootboxPlugin.js\"\n ],\n new webpack.ProvidePlugin({\n jQuery: 'jquery',\n $: 'jquery',\n jquery: 'jquery'\n })\n ]\n\n },\n prettify: false\n },\n /*\n ** Global CSS\n */\n css: [\n 'bootstrap/dist/css/bootstrap.css'\n ],\n\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n\n ],\n\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://bootstrap-vue.js.org/docs/\n 'bootstrap-vue/nuxt',\n '@nuxtjs/pwa',\n ],\n\n /*\n ** Build configuration\n */\n\n build: {\n prettify: false,\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n config.devtool = ctx.isClient ? 'eval-source-map' : 'inline-source-map'\n prettify = false\n }\n }\n}\n```\n\n```text\nexport default {\n build: {\n loaders: {\n vue: {\n prettify: false\n }\n }\n\n }\n}\n```\n\n```text\nprettify: false\n```\n\n```text\nloaders\n```\n\n```text\nmodule.exports { //or export default {\n\nbuild: {\n publicPath: '/',\n vendor: ['axios','firebase', \"jquery\", 'popper', \"bootstrap\", 'bootbox'],\n extractCSS: true,\n babel: {\n presets: [\n 'es2015',\n 'stage-0'\n ],\n plugins: [\n\n [\n \"transform-runtime\",\n {\n \"polyfill\":true,\n \"regenerator\":true\n },\n \"~/plugins/firebase.js\",\n \n new webpack.ProvidePlugin({\n jQuery: 'jquery',\n $: 'jquery',\n jquery: 'jquery'\n })\n ],\n \n ]\n\n },\n // adding the below object made the compilation time go up again to \n //\"normal\" \n loaders: {\n vue: {\n prettify: false\n }\n },\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n config.devtool = ctx.isClient ? 'eval-source-map' : 'inline-source-map'\n \n }\n }\n\n}\n```\n\n========================================\n\nComments:\n- Hello there @Aldarun, where in the nuxt.config.js file should prettify: false should go? I´ve edited my question to show the nuxt.config.js file. I´ve put the prettify false in all places I could find, but still the build time is extremely slow...\n- @AdrielWerlich if u read the linked nuxt doc u should see where it should go... I have updated my answer. But i strongly suggest to go way 1. Also using jquery in nuxt porject is a bad idea too\n- @Aldarund - if using Jquery in Nuxt is a bad idea, the answer shouldn't be \"don't use jquery\", it should be \"Nuxt should integrate jquery.\" From all the frameworks I've built production grade web apps, up until today NO SOUL came to create a plugin so powerful as jquery.\n- What exactly does setting `prettify: false` do?","metadata":{"transformedAt":"2026-08-18T18:33:07.853Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":375,"estimatedTokens":1855}}264{"id":"stack-61747371","source":"stackoverflow","questionId":61747371,"title":"NuxtJS/VueJS: How to know if page was rendered on client-side only?","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: NuxtJS/VueJS: How to know if page was rendered on client-side only?\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nCurrently I create a html5 video player component for an universal nuxtjs/vuejs app.\nThere is an autoplay attribute for the video tag to start videos after navigate to them.\nUsually browsers don't do that directly after page load, it's prohibited.\nI need a variable in my component to know if autoplay will be possible to style elements based on this information.\nIn other words: The variable should be true if the current page was only rendered on client-side, but false if it was rendered on server-side first.\n\nIt's not possible to work with \"window.history.length\" because the autoplay will also not be possible after refresh, although this would not have an effect on the history length.\n\nAlso it's not possible to set a variable in the \"created\" method since it will be called on server- and client-side too.\n\n========================================\n\nTop Answer:\nIn nuxt - there is the `` component that renders components only on the client side\n\n```\n\n \n \n \n \n \n \n \n\n```\n\nIn nuxt, there are is `asyncData` which is run `beforeCreate()`, i.e. you can retrieve data from the server side in `asyncData` before the component is mounted.\n\nhttps://i.sstatic.net/sKpVI.png\n\nAlternatively, you can check on the `created()` for the process, e.g.\n\n```\ncreated() {\n if (process.client) {\n // handle client side\n }\n}\n```\n\n**edit**\n\nhttps://stackoverflow.com/a/53058870/2312051\n\n Audio.play() returns a Promise which is resolved when playback has been successfully started. Failure to begin playback for any reason, such as permission issues, result in the promise being rejected.\n\n```\nconst playedPromise = video.play();\nif (playedPromise) {\n playedPromise.catch((e) => {\n if (e.name === 'NotAllowedError' ||\n e.name === 'NotSupportedError') {\n //console.log(e.name);\n }\n });\n}\n```\n\n In your case, looks like your browser/os does not allow automatic playing of audio. The user agent (browser) or operating system doesn't allow playback of media in the current context or situation. This may happen, for example, if the browser requires the user to explicitly start media playback by clicking a \"play\" button. Here is the reference.\n\n========================================\n\nCode:\n```text\nwatch: {\n $route () {\n Vue.prototype.$navigated = true\n }\n}\n```\n\n```text\n<template>\n <div>\n <sidebar />\n <client-only placeholder=\"Loading...\">\n <!-- this component will only be rendered on client-side -->\n <comments />\n </client-only>\n </div>\n</template>\n```\n\n```text\ncreated() {\n if (process.client) {\n // handle client side\n }\n}\n```\n\n```text\nconst playedPromise = video.play();\nif (playedPromise) {\n playedPromise.catch((e) => {\n if (e.name === 'NotAllowedError' ||\n e.name === 'NotSupportedError') {\n //console.log(e.name);\n }\n });\n}\n```\n\n```text\n<client-only>\n```\n\n```text\nasyncData\n```\n\n```text\nbeforeCreate()\n```\n\n```text\nasyncData\n```\n\n```text\ncreated()\n```\n\n========================================\n\nComments:\n- perhaps we should see a codesandbox minimal example before proceeding?\n- An example is really simple. It's just an default nuxtjs project with a video tag and autoplay attribute. codesandbox.io/s/great-frog-ue5j8?file=/pages/index.vue If you load the page with firefox, you get this error in the console: \"NotAllowedError: The play method is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.\" The goal is to have a variable to know if it will be possible or not so I can apply the initial styling.\n- Lemme check it later\n- added explaination of the above error - Firefox requires users to \"select play\" to play. its to prevent spam websites to autoplay videos\n- Yes, obviously. Sorry but the answer is useless. Please comment if you know how to get the information whether the media is playable on initial rendering of the current route.\n- Yes you're right, I didn't think of asyncData. There it should be possible to set the value of process.client in component data. So I can use the state already for the initial rendering. The problem is that I am on component level and there is no asyncData method. I want to prevent to cascade the value from page component down to the video component.\n- JT2809 lets talk over chat chat.stackoverflow.com/rooms/213701/61747371\n- Referring to your edit: It's not possible to wait for the promise. I need the information before. And I could get it like this way: \"The variable should be true if the current page was only render on client-side, but false if it was rendered on server-side first.\"\n- What if it's a node module?\n- Use `import.meta.client` instead. This may be removed in Nuxt v5 or a future major version. github.com/nuxt/nuxt/pull/26611\n- Nice solution, thanks. Shame about needing to copy paste this to all my layouts (that are potential landing pages for the rest of the site). I have the same issue with an Audio element and autoplay!","metadata":{"transformedAt":"2026-08-18T18:33:07.853Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":143,"estimatedTokens":1264}}265{"id":"stack-72534527","source":"stackoverflow","questionId":72534527,"title":"How do I start websocket server (socketIO or otherwise) in Nuxt 3? Does not work the same as in Nuxt 2","tags":["javascript","sockets","websocket","socket.io","nuxt.js"],"text":"Title: How do I start websocket server (socketIO or otherwise) in Nuxt 3? Does not work the same as in Nuxt 2\nTags: javascript, sockets, websocket, socket.io, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to convert my code from Nuxt 2 to Nuxt 3, and I have run into an issue with creating a websocket server in Nuxt 3.\n\nIt works perfectly fine in Nuxt 2 using this code:\n\n```\n// Nuxt 2: modules/socket.js\nimport http from 'http'\nimport socketIO from 'socket.io'\n\nexport default function () {\n this.nuxt.hook('render:before', () => {\n const server = http.createServer(this.nuxt.renderer.app)\n const io = socketIO(server)\n\n this.nuxt.server.listen = (port, host) => new Promise(resolve => server.listen(port || 3000, host || 'localhost', resolve))\n this.nuxt.hook('close', () => new Promise(server.close))\n\n io.on('connection', (socket) => {\n console.log(\"CONNECTED\")\n })\n })\n}\n```\n\n```\n// Nuxt 2: plugins/socket.client.js\nimport io from 'socket.io-client'\nconst socket = io('http://localhost:3000')\n\nexport default ({}, inject) => {\n inject('socket', socket)\n}\n```\n\n```\n\n Check socket status in Vue devtools...\n\nexport default {\n computed: {\n socket() {\n return this.$socket ? this.$socket : {};\n }\n }\n}\n\n```\n\nHowever, in Nuxt 3 I cannot access `this.nuxt.renderer.app` in the `modules/socket.js` file (for `http.createServer(...)`), and I cannot figure out how to access the correct `renderer.app` elsewhere in a Nuxt3 module. My Nuxt 3 code looks like this:\n\n```\n// Nuxt 3: modules/socket.js\nimport http from 'http'\nimport socketIO from 'socket.io'\n\nexport default (_, nuxt) => {\n // Note that I use the 'ready' hook here - render:before is apparently not included in Nuxt3.\n nuxt.hook('ready', renderer => {\n // nuxt.renderer is undefined, so I've tried with renderer.app instead, with no luck.\n const server = http.createServer(renderer.app)\n const io = socketIO(server)\n\n nuxt.server.listen = (port, host) => new Promise(resolve => server.listen(port || 3000, host || 'localhost', resolve))\n nuxt.hook('close', () => new Promise(server.close))\n \n io.on('connection', () => {\n console.log(\"CONNECTION\")\n })\n })\n}\n```\n\n```\n// Nuxt 3: plugins/socket.client.js\nimport io from 'socket.io-client'\n\nexport default defineNuxtPlugin(() => {\n const socket = io('http://localhost:3000')\n\n return {\n provide: {\n socket: socket\n }\n }\n})\n```\n\n```\n\n \n Check socket status in Vue devtools...\n\n \n\n const { $socket } = useNuxtApp() \n\n```\n\nI would make a codesandbox link for you, but every time I try, it breaks before I even add any code. I think it does not correctly work with Nuxt3 yet.\nHas anyone successfully established a websocket server in a Nuxt 3 module yet? Or can anyone see what I am missing?\n\nI am interested in any working solution, it does not necessarily have to be `socket.io`.\n\n========================================\n\nTop Answer:\nBased on @ahbork's response and a addition from the Nuxt 3 docs, I got this on Vue 3 + Nuxt 3 + Typescript:\n\n```\nimport { Server } from 'socket.io'\nimport { defineNuxtModule } from '@nuxt/kit'\n\nexport default defineNuxtModule({\n setup(options, nuxt) {\n nuxt.hook('listen', (server) => {\n console.log('Socket listen', server.address(), server.eventNames())\n const io = new Server(server)\n\n nuxt.hook('close', () => io.close())\n\n io.on('connection', (socket) => {\n console.log('Connection', socket.id)\n })\n\n io.on('connect', (socket) => {\n socket.emit('message', `welcome ${socket.id}`)\n socket.broadcast.emit('message', `${socket.id} joined`)\n\n socket.on('message', function message(data: any) {\n console.log('message received: %s', data)\n socket.emit('message', { data })\n })\n\n socket.on('disconnecting', () => {\n console.log('disconnected', socket.id)\n socket.broadcast.emit('message', `${socket.id} left`)\n })\n })\n })\n },\n})\n```\n\n========================================\n\nCode:\n```text\n// Nuxt 2: modules/socket.js\nimport http from 'http'\nimport socketIO from 'socket.io'\n\nexport default function () {\n this.nuxt.hook('render:before', () => {\n const server = http.createServer(this.nuxt.renderer.app)\n const io = socketIO(server)\n\n this.nuxt.server.listen = (port, host) => new Promise(resolve => server.listen(port || 3000, host || 'localhost', resolve))\n this.nuxt.hook('close', () => new Promise(server.close))\n\n io.on('connection', (socket) => {\n console.log(\"CONNECTED\")\n })\n })\n}\n```\n\n```text\n// Nuxt 2: plugins/socket.client.js\nimport io from 'socket.io-client'\nconst socket = io('http://localhost:3000')\n\nexport default ({}, inject) => {\n inject('socket', socket)\n}\n```\n\n```text\n<!-- Nuxt 2: pages/index.vue -->\n<template>\n<div>\n <p>Check socket status in Vue devtools...</p>\n</div>\n</template>\n\n<script>\nexport default {\n computed: {\n socket() {\n return this.$socket ? this.$socket : {};\n }\n }\n}\n</script>\n```\n\n```text\n// Nuxt 3: modules/socket.js\nimport http from 'http'\nimport socketIO from 'socket.io'\n\nexport default (_, nuxt) => {\n // Note that I use the 'ready' hook here - render:before is apparently not included in Nuxt3.\n nuxt.hook('ready', renderer => {\n // nuxt.renderer is undefined, so I've tried with renderer.app instead, with no luck.\n const server = http.createServer(renderer.app)\n const io = socketIO(server)\n\n nuxt.server.listen = (port, host) => new Promise(resolve => server.listen(port || 3000, host || 'localhost', resolve))\n nuxt.hook('close', () => new Promise(server.close))\n \n io.on('connection', () => {\n console.log(\"CONNECTION\")\n })\n })\n}\n```\n\n```text\n// Nuxt 3: plugins/socket.client.js\nimport io from 'socket.io-client'\n\nexport default defineNuxtPlugin(() => {\n const socket = io('http://localhost:3000')\n\n return {\n provide: {\n socket: socket\n }\n }\n})\n```\n\n```text\n<!-- Nuxt 3: app.vue -->\n<template>\n <div>\n <p>Check socket status in Vue devtools...</p>\n </div>\n</template>\n\n<script setup>\n const { $socket } = useNuxtApp() \n</script>\n```\n\n```text\nthis.nuxt.renderer.app\n```\n\n```text\nmodules/socket.js\n```\n\n```text\nhttp.createServer(...)\n```\n\n```text\nrenderer.app\n```\n\n```text\nsocket.io\n```\n\n```text\nimport { Server } from 'socket.io'\n\nexport default (_, nuxt) => {\n nuxt.hook('listen', server => {\n const io = new Server(server)\n\n nuxt.hook('close', () => io.close())\n \n io.on('connection', () => {\n console.log(\"CONNECTION\")\n })\n })\n}\n```\n\n```text\nlisten\n```\n\n```text\nserver\n```\n\n```text\nmodules/socket.js\n```\n\n```text\nimport { WebSocketServer } from \"ws\";\nimport { defineNuxtModule } from \"@nuxt/kit\";\n\nexport default defineNuxtModule({\n setup(options, nuxt) {\n nuxt.hook(\"listen\", (server) => {\n const wss = new WebSocketServer({ server });\n nuxt.hook(\"close\", () => wss.close());\n wss.on(\"connection\", (ws) => {\n console.log(\"connection\");\n ws.on(\"message\", (data) => console.log(\"received: %s\", data));\n ws.send(\"someting\");\n });\n });\n },\n});\n```\n\n```text\nlet ws;\nonMounted(() => {\n const wsProtocol = window.location.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n ws = new WebSocket(`${wsProtocol}//${window.location.host}`);\n ws.onopen = () => console.log(\"connected\");\n ws.onmessage = ({ data }: any) => {\n console.log(\"data\", data);\n };\n});\nconst sendMessage = () => {\n ws.send(\"hello\");\n};\n```\n\n```js\nimport { Server } from 'socket.io'\nimport { defineNuxtModule } from '@nuxt/kit'\n\nexport default defineNuxtModule({\n setup(options, nuxt) {\n nuxt.hook('listen', (server) => {\n console.log('Socket listen', server.address(), server.eventNames())\n const io = new Server(server)\n\n nuxt.hook('close', () => io.close())\n\n io.on('connection', (socket) => {\n console.log('Connection', socket.id)\n })\n\n io.on('connect', (socket) => {\n socket.emit('message', `welcome ${socket.id}`)\n socket.broadcast.emit('message', `${socket.id} joined`)\n\n socket.on('message', function message(data: any) {\n console.log('message received: %s', data)\n socket.emit('message', { data })\n })\n\n socket.on('disconnecting', () => {\n console.log('disconnected', socket.id)\n socket.broadcast.emit('message', `${socket.id} left`)\n })\n })\n })\n },\n})\n```\n\n========================================\n\nComments:\n- I tried to do essentially what you are trying to do in Java a few years ago - I couldn't get handshake to work (apparently you need Berkeley Sockets - developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/…) the web socket server i am currently using is Ratchet, which I found to be fairly easy to set up and use (especially on Mac/unix)\n- When you build your application `npm run build` -> `nuxt build` and run the build by `node .output/server/index.mjs` is your socketServer included? I use the same approach but I'm missing the socketServer in the build/output.\n- listen hook only gets executed on build... is there any other solution?\n- how would I access the io instance in /server/api endpoints? E.g. if I want an endpoint that returns all connacted sockets, how would I do that?\n- this makes sense, but i've not tried to do such. sorry, this response is late.","metadata":{"transformedAt":"2026-08-18T18:33:07.853Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":375,"estimatedTokens":2330}}266{"id":"stack-68165911","source":"stackoverflow","questionId":68165911,"title":"How to efficiently load google fonts in Nuxt","tags":["css","vue.js","vuejs2","nuxt.js","google-fonts"],"text":"Title: How to efficiently load google fonts in Nuxt\nTags: css, vue.js, vuejs2, nuxt.js, google-fonts\nSource: Stack Overflow\n\nQuestion:\nI am using this google font `font-family: 'Saira Semi Condensed', sans-serif;`\n\nLink: https://fonts.google.com/specimen/Saira+Semi+Condensed\n\nI am working in on a NuxtJS project. I have to use this font in two different components but with different font-weight. I have imported all the google fonts links in `Layout.vue`.\n\nFor component A the `font-weight` is `600` & for component B the `font-weight` is `800`. So I thought giving different font-weights in the respective component will work. But it is not working. The only basic font has applied i.e. `Saira Semi Condensed, sans-serif;` but the font-weight values are not reflected. To resolve this problem I need import two google font links with the same fonts but different font-weight in `Layout.vue` which makes it redundant.\n\nFor font-weight: 600\n\n```\n@import url('https://fonts.googleapis.com/css2?family=Saira+Semi+Condensed:wght@600&display=swap%27);\n```\n\nFor font-weight: 800\n\n```\n@import url('https://fonts.googleapis.com/css2?family=Saira+Semi+Condensed:wght@800&display=swap%27);\n```\n\nI think my way of importing two links for the same fonts is not look good. Can you guys please help me to solve this issue?\nThank you in advanced.\n\n**Code**:\n\nLayout.vue\n\n```\n\n \n \n \n\n@import url('https://fonts.googleapis.com/css2?family=Nunito&display=swap');\n@import url('https://fonts.googleapis.com/css2?family=Saira+Semi+Condensed:wght@600&display=swap');\n@import url('https://fonts.googleapis.com/css2?family=Saira+Semi+Condensed:wght@800&display=swap');\n@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@700&display=swap');\n\nhtml {\n font-family: 'Source Sans Pro', -apple-system, BlinkMacSystemFont, 'Segoe UI',\n Roboto, 'Helvetica Neue', Arial, sans-serif;\n font-size: 16px;\n word-spacing: 1px;\n -ms-text-size-adjust: 100%;\n -webkit-text-size-adjust: 100%;\n -moz-osx-font-smoothing: grayscale;\n -webkit-font-smoothing: antialiased;\n box-sizing: border-box;\n}\n\n*,\n*::before,\n*::after {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n}\n\n```\n\nindex.vue\n\n```\n\n \n \n \n \n \n \n\nimport Navbar from '../components/Navbar.vue'\nimport Clock from '../components/ComponentA.vue'\nimport Days from '../components/ComponentB.vue'\nimport Footer from '../components/Footer.vue'\nexport default {\n components: {\n Navbar,\n ComponentA,\n ComponentB,\n Footer,\n },\n}\n\n```\n\nComponentA.vue\n\n```\n\n \n \n\n### I am component A\n\n \n\nexport default {\n name: 'ComponentA',\n}\n\nfooter {\n color: blue;\n font-family: 'Saira Semi Condensed', sans-serif;\n font-size: 20px;\n text-align: center;\n }\n\n```\n\nComponentB.vue\n\n```\n\n \n \n\n### I am component B\n\n \n\nexport default {\n name: 'ComponentB',\n}\n\nfooter {\n color: red;\n font-family: 'Saira Semi Condensed', sans-serif;\n font-size: 24px;\n text-align: center;\n }\n\n```\n\n========================================\n\nTop Answer:\nAn update from @kissu's great earlier answer.\n\nAs of 2024 the best option is to use Nuxt Fonts, an officially maintained Nuxt plugin which will:\n\n- auto-detect `font-family` use\n\n- determine the right provider and\n\n- download the asset at build time so it can be served as a static asset via your own domain\n\nIf you are wondering about losing the benefits of cross-domain caching (serving from google fonts for example) vs serving the asset yourself, this article has a good explanation for why this isn't as good a deal as it sounds like it would be (scroll down to the Cross-Domain Caching section).\n\n========================================\n\nCode:\n```css\n@import url('https://fonts.googleapis.com/css2?family=Saira+Semi+Condensed:wght@600&display=swap%27);\n```\n\n```css\n@import url('https://fonts.googleapis.com/css2?family=Saira+Semi+Condensed:wght@800&display=swap%27);\n```\n\n```html\n<template>\n <div>\n <Nuxt />\n </div>\n</template>\n\n<style>\n@import url('https://fonts.googleapis.com/css2?family=Nunito&display=swap');\n@import url('https://fonts.googleapis.com/css2?family=Saira+Semi+Condensed:wght@600&display=swap');\n@import url('https://fonts.googleapis.com/css2?family=Saira+Semi+Condensed:wght@800&display=swap');\n@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@700&display=swap');\n\nhtml {\n font-family: 'Source Sans Pro', -apple-system, BlinkMacSystemFont, 'Segoe UI',\n Roboto, 'Helvetica Neue', Arial, sans-serif;\n font-size: 16px;\n word-spacing: 1px;\n -ms-text-size-adjust: 100%;\n -webkit-text-size-adjust: 100%;\n -moz-osx-font-smoothing: grayscale;\n -webkit-font-smoothing: antialiased;\n box-sizing: border-box;\n}\n\n*,\n*::before,\n*::after {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n}\n</style>\n```\n\n```text\n<template>\n <div>\n <Navbar />\n <ComponentA />\n <ComponentB />\n <Footer />\n </div>\n</template>\n\n<script>\nimport Navbar from '../components/Navbar.vue'\nimport Clock from '../components/ComponentA.vue'\nimport Days from '../components/ComponentB.vue'\nimport Footer from '../components/Footer.vue'\nexport default {\n components: {\n Navbar,\n ComponentA,\n ComponentB,\n Footer,\n },\n}\n</script>\n```\n\n```text\n<template>\n <div>\n <h1>I am component A</h1>\n </div>\n</template>\n\n<script>\nexport default {\n name: 'ComponentA',\n}\n</script>\n\n<style scoped>\nfooter {\n color: blue;\n font-family: 'Saira Semi Condensed', sans-serif;\n font-size: 20px;\n text-align: center;\n }\n</style>\n```\n\n```text\n<template>\n <div>\n <h1>I am component B</h1>\n </div>\n</template>\n\n<script>\nexport default {\n name: 'ComponentB',\n}\n</script>\n\n<style scoped>\nfooter {\n color: red;\n font-family: 'Saira Semi Condensed', sans-serif;\n font-size: 24px;\n text-align: center;\n }\n</style>\n```\n\n```text\nfont-family: 'Saira Semi Condensed', sans-serif;\n```\n\n```text\nLayout.vue\n```\n\n```text\nfont-weight\n```\n\n```text\n600\n```\n\n```text\nfont-weight\n```\n\n```text\n800\n```\n\n```text\nSaira Semi Condensed, sans-serif;\n```\n\n```text\nLayout.vue\n```\n\n```js\nexport default {\n buildModules: [\n [\n '@nuxtjs/google-fonts',\n {\n families: {\n Mali: {\n wght: [400, 600, 700],\n },\n },\n subsets: ['latin'],\n display: 'swap',\n prefetch: false,\n preconnect: false,\n preload: false,\n download: true,\n base64: false,\n },\n ],\n ]\n}\n```\n\n```text\n@nuxtjs/google-fonts\n```\n\n```text\nnuxt.config.js\n```\n\n```text\noverwriting: true\n```\n\n```text\nfont-family\n```\n\n========================================\n\nComments:\n- I am not getting your answer. Can you please give some good explanation or any blog or example?\n- @rakshit I'm not sure what to tell more here. I gave a configuration to load properly the Google font named `Mali` with an on-build Nuxt.js module. You can then use it anywhere you need. And the module also allows you to set specific weights. What would you need here?\n- You can then use it in your components with some CSS and set the weight with `font-weight: 700` or alike.\n- It is showing me like this. `Error: Cannot find module '@nuxtjs/google-fonts'`\n- I don't understand, why did you set preload to false and base64 to false, doesn't it means that our font will NOT have to be loaded fully by the time your HTML/CSSOM is parsed and displayed?\n- @gazoon007 this is a `buildModules` and I don't want to download anything at runtime. So, it will only get the fonts once, and it will be available straight when the page will be rendered, no need for any preload or anything because the fonts will already be local.\n- But by this configuration, I have a problem with my project. So whenever the page has server-side routing or just reload the page during low connection, the font is always displayed the generic font (like monospace) and then later changes suddenly to google fonts, I don't know how by this configuration to make my font will have to be loaded fully before the HTML is rendered\n- @gazoon007 this is how a font works in CSS AFAIK. You can put a font that looks like that while loading tho.\n- @gazoon007 for me `base64: true` do the trick. I'm also using SSR and get my page with fully loaded fonts\n- That is a very good, up-to-date answer. Also yes: self-host the font for your own good!","metadata":{"transformedAt":"2026-08-18T18:33:07.853Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":357,"estimatedTokens":2054}}267{"id":"stack-67131283","source":"stackoverflow","questionId":67131283,"title":"How can i solve Nuxt.js cannot find module '@vue/composition-api' error?","tags":["vue.js","nuxt.js","vue-composition-api"],"text":"Title: How can i solve Nuxt.js cannot find module '@vue/composition-api' error?\nTags: vue.js, nuxt.js, vue-composition-api\nSource: Stack Overflow\n\nQuestion:\nWhen developing Nuxt.js\n\n```\ncannot find module '@ vue / composition-api\n```\n\nI get an error. Why does this error occur?\n\n========================================\n\nTop Answer:\nI've found out this error is being caused by Vuter extension. This extension is requiring composition API which is available on Vue 3.x Disabling it fixes the problem but again you need Vuter yikes!\n\n========================================\n\nCode:\n```text\ncannot find module '@ vue / composition-api\n```\n\n```text\n# if you use yarn\n$ yarn add @vue/composition-api\n\n# if you use npm\n$ npm install @vue/composition-api --save\n```\n\n========================================\n\nComments:\n- Described package works with Vue2 and it is community package. Check this for more info.","metadata":{"transformedAt":"2026-08-18T18:33:07.853Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":37,"estimatedTokens":226}}268{"id":"stack-62103635","source":"stackoverflow","questionId":62103635,"title":"Axios in Nuxt.js is not catch error properly","tags":["axios","nuxt.js"],"text":"Title: Axios in Nuxt.js is not catch error properly\nTags: axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nAs I mentioned above my Axios on Nuxt.js is not catch error properly\n\nI need to know the error, so I can prompt to let the user know their input is not correct but it only **console.log** the error code status not the message from my API\n\nthis is my code\n\n```\nawait axios\n .post(\n \"API LINK\",\n {\n email: user.email,\n password: \"123456\",\n name: user.name,\n dob: user.dob ?? null,\n gender: user.gender ?? null,\n profileImage: imageUrl ?? user.profileImage,\n userType: user.userType\n }\n )\n .then(res => {\n console.log(\"success\");\n console.log(res);\n })\n .catch(err => {\n console.log('fail');\n console.log(err)\n })\n```\n\nThis is what log on a chrome console\n\n```\nerror\nadd.vue?104b:181 Error: Request failed with status code 400\n at createError (createError.js?2d83:16)\n at settle (settle.js?467f:17)\n at XMLHttpRequest.handleLoad (xhr.js?b50d:61)\n```\n\nBut what I expect from the **console.log(err)** is\n\n```\n(This is response from postman)\n{\n \"message\": \"Error creating new user.\",\n \"error\": {\n \"code\": \"auth/invalid-password\",\n \"message\": \"The password must be a string with at least 6 characters.\"\n }\n}\n```\n\nI have no idea what is happening.\n\n========================================\n\nTop Answer:\nThis is working with a try / catch structure, which is the preferred way\n\n```\ntry {\n await axios.post(\"API LINK\", {\n email: user.email,\n password: \"123456\",\n name: user.name,\n dob: user.dob ?? null,\n gender: user.gender ?? null,\n profileImage: imageUrl ?? user.profileImage,\n userType: user.userType,\n })\n console.log(\"success\", res)\n } catch ({ response }) {\n console.log(\"fail\", response)\n }\n```\n\n========================================\n\nCode:\n```text\nawait axios\n .post(\n \"API LINK\",\n {\n email: user.email,\n password: \"123456\",\n name: user.name,\n dob: user.dob ?? null,\n gender: user.gender ?? null,\n profileImage: imageUrl ?? user.profileImage,\n userType: user.userType\n }\n )\n .then(res => {\n console.log(\"success\");\n console.log(res);\n })\n .catch(err => {\n console.log('fail');\n console.log(err)\n })\n```\n\n```text\nerror\nadd.vue?104b:181 Error: Request failed with status code 400\n at createError (createError.js?2d83:16)\n at settle (settle.js?467f:17)\n at XMLHttpRequest.handleLoad (xhr.js?b50d:61)\n```\n\n```text\n(This is response from postman)\n{\n \"message\": \"Error creating new user.\",\n \"error\": {\n \"code\": \"auth/invalid-password\",\n \"message\": \"The password must be a string with at least 6 characters.\"\n }\n}\n```\n\n```text\nconsole.log(err.response)\n```\n\n```text\n.catch(({ response }) => {\n console.log('fail');\n console.log(response)\n })\n```\n\n```text\n.catch(({ response: err }) => {\n console.log('fail');\n console.log(err)\n })\n```\n\n```text\nresponse\n```\n\n```text\n.response\n```\n\n```text\ntry {\n await axios.post(\"API LINK\", {\n email: user.email,\n password: \"123456\",\n name: user.name,\n dob: user.dob ?? null,\n gender: user.gender ?? null,\n profileImage: imageUrl ?? user.profileImage,\n userType: user.userType,\n })\n console.log(\"success\", res)\n } catch ({ response }) {\n console.log(\"fail\", response)\n }\n```\n\n========================================\n\nComments:\n- Thanks a lot, mate. It's working now. Btw can you explain to me why using err.response not the err because before this project I always use the err only and it work just fine.\n- @Purinut The problem is when the console.log tries to output the error, the string representation is printed, not the object structure, so you do not see the .response property. Here you can read about github.com/axios/axios/issues/960","metadata":{"transformedAt":"2026-08-18T18:33:07.853Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":176,"estimatedTokens":934}}269{"id":"stack-44225291","source":"stackoverflow","questionId":44225291,"title":"How to run nuxt.js in real service?","tags":["node.js","vue.js","publishing","pm2","nuxt.js"],"text":"Title: How to run nuxt.js in real service?\nTags: node.js, vue.js, publishing, pm2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI used vue-cli in\n\n vue init nuxt/express myProject\n\nand, \n\n npm run dev\n\ndeveloped.\n\nbut,\n\n npm run build\n\nafter, was created dist file.\n\nHow i can run in real service in pm2?\n\n(I will use ubuntu in AWS EC.)\n\n========================================\n\nTop Answer:\nPrerequisites\n\n- node.js installed on web server\n\n- nginx installed and configured on web server\n\n- pm2 installed and configured on web server\n\nThen\n\nAdd to your universal Nuxt app for serving it though PM2 is a file called **ecosystem.config.js.** Create a new file with that name in your root project directory and add the following content:\n\n```\nmodule.exports = {\n apps: [\n {\n name: 'project-name',\n exec_mode: 'cluster',\n instances: 'max', // Or a number of instances\n script: './node_modules/nuxt/bin/nuxt.js',\n args: 'start'\n }\n ]\n }\n```\n\nConnect to your linux server via FTP (FileZilla or etc..)\nSend the blue files I marked to the server.\n(you don't need to upload node_modues, .nuxt, dist, .git, .idea, etc... folders)\n\nhttps://i.sstatic.net/spAz1.png\n\nConnect server via ssh console, (windows : putty)\nand go to projects folder that you uploaded files.\n\n```\ncd /\n cd var/www/project-name\n```\n\nInstall node_modules folder by;\n\n```\nnpm install\n```\n\nExecute nuxt build and create .nuxt folder by;\n\n```\nnpm run build\n```\n\nFinally, ready to start starts pm2 server by;\n\n```\npm2 start\n```\n\n========================================\n\nCode:\n```text\npm2 start npm --name \"your-project-name\" -- start\n```\n\n```text\npm2 status\n```\n\n```text\npm2 restart your-project-name\npm2 stop your-project-name\n```\n\n```text\nmodule.exports = {\n apps: [\n {\n name: 'project-name',\n exec_mode: 'cluster',\n instances: 'max', // Or a number of instances\n script: './node_modules/nuxt/bin/nuxt.js',\n args: 'start'\n }\n ]\n }\n```\n\n```text\ncd /\n cd var/www/project-name\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run build\n```\n\n```text\npm2 start\n```\n\n========================================\n\nComments:\n- What is my project name? `Nuxt / express` Npm Do you need to target the folder created after run build?\n- The project name is just an alias for PM2. The most important is \"pm2 start npm -- start\", it's the way for PM2 to do a \"npm run start\", then the \"start\" script from nuxt know that the target folder is \"dist\".\n- I understand now. And I tried. **I finally solved it.** Thank you very much. Be happy.\n- Add, **What folders should be moved during the actual service?** `Build/main.js` and `.nuxt/dist`?","metadata":{"transformedAt":"2026-08-18T18:33:07.853Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":140,"estimatedTokens":657}}270{"id":"stack-71413599","source":"stackoverflow","questionId":71413599,"title":"jspdf doesn't work when loaded from a CDN","tags":["javascript","vue.js","nuxt.js","jspdf"],"text":"Title: jspdf doesn't work when loaded from a CDN\nTags: javascript, vue.js, nuxt.js, jspdf\nSource: Stack Overflow\n\nQuestion:\nI am going to use package(jspdf) loaded from **CDN **\n\nthis is CDN\n\n```\n\n```\n\nand I have **loaded** it like this in a page :\n\n```\nmounted() {\n if (document.getElementById('myScript')) { return }\n let src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js'\n let script = document.createElement('script')\n script.setAttribute('src', src)\n script.setAttribute('type', 'text/javascript')\n script.setAttribute('id', 'myScript')\n document.head.appendChild(script)\n}\n```\n\nand I have a **button** that when you **click** on it a below **method** will called and some pdf will be generated.\n\n```\ngenerateReport() {\n var doc = new jsPDF('l', 'mm', [62, 32])\n const margins = {\n top: 0,\n bottom: 60,\n left: 0,\n width: 122\n }\n\n doc.fromHTML(this.$refs.print, margins.left, margins.top, {\n width: margins.width\n })\n\n doc.save('test.pdf')\n}\n```\n\n**BUT** I get an error\n\nhttps://i.sstatic.net/axF5W.png\n\nSo, how can I **fix** this error?\n\n========================================\n\nTop Answer:\nThis one seems to be working :\n\n```\n\n```\n\n========================================\n\nCode:\n```text\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js\"></script>\n```\n\n```js\nmounted() {\n if (document.getElementById('myScript')) { return }\n let src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js'\n let script = document.createElement('script')\n script.setAttribute('src', src)\n script.setAttribute('type', 'text/javascript')\n script.setAttribute('id', 'myScript')\n document.head.appendChild(script)\n}\n```\n\n```js\ngenerateReport() {\n var doc = new jsPDF('l', 'mm', [62, 32])\n const margins = {\n top: 0,\n bottom: 60,\n left: 0,\n width: 122\n }\n\n doc.fromHTML(this.$refs.print, margins.left, margins.top, {\n width: margins.width\n })\n\n doc.save('test.pdf')\n}\n```\n\n```text\nconst { jsPDF } = window.jspdf;\n```\n\n```text\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.debug.js\"></script>\n```\n\n========================================\n\nComments:\n- You loaded the CDN but where is the jsPDF variable declaration?\n- Does this answer your question? How to add a 3rd party script code into Nuxt?\n- Also, are you sure that you want to use a CDN here? Pretty sure you can find the NPM package for that, it will be far better in a `package.json` tbh.\n- @DiesanRomero , variable declaration ? how can i do it ?\n- @kissu i a pretty sure that this way that i used cdn is worked because i can see that script is loaded , the problem is how to use it\n- Looks like the variable declaration is in generateReport(), `var doc = new jsPDF( ... )`. Possibly the class name is simply not spelled `jsPDF`. Have you checked the docs?\n- You should probably the recommended install and also the recommended usage. Otherwise, in \"Other module formats, Globals\", it's written `const { jsPDF } = window.jspdf;`. This way, you will get it out from the window. Still, even if it's loaded and feasible use it through an NPM package since it's more easy to control, more performant and less prone to a 404. And also because it's the recommended way from the package itself.\n- @GetSet i am sure class name is jsPDF() as written in doc\n- Super old version tho.","metadata":{"transformedAt":"2026-08-18T18:33:07.853Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":119,"estimatedTokens":835}}271{"id":"stack-75046466","source":"stackoverflow","questionId":75046466,"title":"Nuxt 3 extend NuxtApp type with custom plugins","tags":["typescript","plugins","nuxt.js"],"text":"Title: Nuxt 3 extend NuxtApp type with custom plugins\nTags: typescript, plugins, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhen i provide plugin to nuxtApp it knows its type\n\nhttps://i.sstatic.net/UFqZW.png\n\nbut when i try to use it on the page it show only type \"any\"\nhttps://i.sstatic.net/hVSzA.png\n\nCan i add types to extend NuxtApp type mannualy? or what can i do for it to know the right type of plugin?\n\ni think about something like this\n\n```\nimport type { order } from '~/plugins/order'\n\ninterface PluginsInjections {\n $order: ReturnType\n}\n\ndeclare global {\n interface NuxtApp extends PluginsInjections {}\n}\n```\n\n========================================\n\nTop Answer:\nYou shouldn't need to manually add types for properties and functions injected by plugins since it's supposed to work automatically as explained in the docs: https://nuxt.com/docs/guide/directory-structure/plugins#typing-plugins Instead, you should investigate why the automatic detection is not working as expected.\n\nMore advanced usecases can require you to manually define the types of injected properties. In that case you can this example:\n\n```\n// Your plugin\nexport default defineNuxtPlugin(() => {\n return {\n provide: {\n hello: (msg: string) => `Hello ${msg}!`\n }\n }\n})\n\n// index.d.ts\ndeclare module '#app' {\n interface NuxtApp {\n $hello (msg: string): string\n }\n}\n\ndeclare module '@vue/runtime-core' {\n interface ComponentCustomProperties {\n $hello (msg: string): string\n }\n}\n\nexport { }\n```\n\nfrom: https://nuxt.com/docs/guide/directory-structure/plugins#advanced\n\nBut do remember that doing this masks the consequences of another issue in your code base instead of solving the root cause.\n\n========================================\n\nCode:\n```text\nimport type { order } from '~/plugins/order'\n\ninterface PluginsInjections {\n $order: ReturnType<order>\n}\n\ndeclare global {\n interface NuxtApp extends PluginsInjections {}\n}\n```\n\n```text\nimport type { order } from '~/plugins/order'\n\ninterface PluginsInjections {\n $order: ReturnType<typeof order>\n}\n\ndeclare module '#app' {\n interface NuxtApp extends PluginsInjections {}\n}\n\ndeclare module 'nuxt/dist/app/nuxt' {\n interface NuxtApp extends PluginsInjections {}\n}\n\ndeclare module '@vue/runtime-core' {\n interface ComponentCustomProperties extends PluginsInjections {}\n}\n```\n\n```js\n// Your plugin\nexport default defineNuxtPlugin(() => {\n return {\n provide: {\n hello: (msg: string) => `Hello ${msg}!`\n }\n }\n})\n\n// index.d.ts\ndeclare module '#app' {\n interface NuxtApp {\n $hello (msg: string): string\n }\n}\n\ndeclare module '@vue/runtime-core' {\n interface ComponentCustomProperties {\n $hello (msg: string): string\n }\n}\n\nexport { }\n```\n\n========================================\n\nComments:\n- Updated to better reflect the point I was trying to make. Manually adding the types doesn't fix the fact that the automatic detection doesn't work.","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":130,"estimatedTokens":723}}272{"id":"stack-77594888","source":"stackoverflow","questionId":77594888,"title":"How to use i18n messages in a Nuxt3 pinia store","tags":["nuxt.js","pinia","nuxt-i18n"],"text":"Title: How to use i18n messages in a Nuxt3 pinia store\nTags: nuxt.js, pinia, nuxt-i18n\nSource: Stack Overflow\n\nQuestion:\nWhen trying to use an i18n message in a Nuxt3 Pinia store I get the error message:\n\"SyntaxError: Must be called at the top of a `setup` function\"\n\nWhen using a message in a template I can do:\n\n```\n\n {{ $t('welcome') }}\n\n```\n\nBut how to do it in the pinia store?\n\nHere is what I tried in the store that led to the error:\n\n```\nimport { defineStore } from 'pinia';\nconst { t } = useI18n();\n\nexport const useAppStore = defineStore('appStore', {\n state: () => {\n return {\n label: $t('welcome')\n };\n }, \n});\n```\n\n========================================\n\nTop Answer:\nBecause of `i18n` requiring app context, I would recommend to use it in that app context. Technically - translation string does not denote state of application.\nI would rather return string identifier in label, and then would resolve it in component, that would display that text.\n\n```\nimport { defineStore } from 'pinia';\n const { t } = useI18n();\n\n export const useAppStore = defineStore('appStore', {\n state: () => {\n return {\n label: 'welcome'\n };\n }, \n });\n```\n\nThen, in component template it will be\n\n```\n{{ $t(appStore.label) }}\n\n```\n\nSorry, it doesn't answer to question on how to use i18n in pinia store, but I think my solution will be sufficient for most use cases. If your specific case is not covered with it, I guess you will need to figure out reactivity as Ellrohir proposed in answer above\n\n========================================\n\nCode:\n```text\n<template>\n <p>{{ $t('welcome') }}</p>\n</template>\n```\n\n```text\nimport { defineStore } from 'pinia';\nconst { t } = useI18n();\n\nexport const useAppStore = defineStore('appStore', {\n state: () => {\n return {\n label: $t('welcome')\n };\n }, \n});\n```\n\n```text\nsetup\n```\n\n```js\nexport const useAppStore = defineStore('appStore', {\n state: () => {\n return {\n label: useNuxtApp().$i18n.t('welcome')\n };\n }, \n});\n```\n\n```js\nexport function useT (key: string): string {\n return useNuxtApp().$i18n.t(key)\n}\n```\n\n```text\nsetup()\n```\n\n```text\n<script setup>\n```\n\n```text\nconst { t } = useI18n();\n```\n\n```text\n$i18n\n```\n\n```text\nuseNuxtApp()\n```\n\n```text\nuseT('welcome')\n```\n\n```text\nuseAppStore()\n```\n\n```text\nuseAppStore()\n```\n\n```text\nimport { defineStore } from 'pinia';\n const { t } = useI18n();\n\n export const useAppStore = defineStore('appStore', {\n state: () => {\n return {\n label: 'welcome'\n };\n }, \n });\n```\n\n```text\n<p>{{ $t(appStore.label) }}</p>\n```\n\n```text\ni18n\n```\n\n========================================\n\nComments:\n- You better use `t` only in the template. Consider you have a label that has no translation like `Car` then the fallback will be `Car`, if there is an translation for the key `Car` it will use the translation\n- Thanks Ellrohir, accessing the message works fine with your solution. But when changing the language the message does not change. Im trying to access the message like this: {{ appStore.label }}\n- That would be because the outcome of `t` method is not reactive. I'd suggest to define an action on your store that will be triggered upon the language change and will translate all values again with the new locale.\n- Strange that t is not reactive here. It makes the tasks more complicated than it could be. Lets hope it will get improved. Thanks for your help @Ellrohir.\n- I think it makes sense the return type is a \"static\" value. Because otherwise you would force all users to unwrap it when using `t()` in their scripts adding extra complexity to everyone. Maybe there are some extensions or plugins allowing reactivity. Something like \"VueUse for I18n module\". But I am not familiar with any such solution.\n- For those who have problem with reactivity in this solution, try to modify it like this: ``` import { computed } from 'vue'; import { useNuxtApp } from '#app'; export function useT(key: string) { const { $i18n } = useNuxtApp(); return computed(() => $i18n.t(key)); } ``` Works for me","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":165,"estimatedTokens":1005}}273{"id":"stack-71684163","source":"stackoverflow","questionId":71684163,"title":"Nuxt2 - watch route change","tags":["vue.js","nuxt.js","vue-router"],"text":"Title: Nuxt2 - watch route change\nTags: vue.js, nuxt.js, vue-router\nSource: Stack Overflow\n\nQuestion:\nI know this was asked a couple of times, but I do not understand something about watching for a route change in Nuxt2.\n\nIt doesn't work for me.\n\nMy code is:\n\n```\nwatch: {\n $route(to, from) {\n console.log('route change to', to)\n console.log('route change from', from)\n },\n },\n```\n\n**Minimal reproducable example:**\n\nhttps://codesandbox.io/s/dreamy-feather-90gbjm\n\n**Expected behavior**\n\nshow console logs on route change.\n\n**result**\n\nnothing happens\n\n========================================\n\nTop Answer:\nWith **Nuxt 3**, you can use `onBeforeRouteUpdate` from `vue-router`:\n\n```\n\nimport { onBeforeRouteUpdate } from \"vue-router\"\n\nonBeforeRouteUpdate((newRoute) => {\n console.log(newRoute)\n})\n\n```\n\n========================================\n\nCode:\n```js\nwatch: {\n $route(to, from) {\n console.log('route change to', to)\n console.log('route change from', from)\n },\n },\n```\n\n```text\n| pages\n | index.vue\n | about.vue\n| layouts\n | base.vue\n```\n\n```html\n<template>\n <Nuxt />\n</template>\n\n<script>\nexport default {\n ....\n watch: {\n $route(to, from) {\n console.log('route change to', to)\n console.log('route change from', from)\n },\n },\n ....\n}\n</script>\n```\n\n```html\n<template>\n ... Many things here\n</template>\n\n<script>\nexport default {\n layout: 'base',\n ...\n}\n</script>\n```\n\n```text\nlayout\n```\n\n```text\nlayouts/base.vue\n```\n\n```text\nindex.vue\n```\n\n```text\nabout.vue\n```\n\n```text\n<script setup>\nimport { onBeforeRouteUpdate } from \"vue-router\"\n\nonBeforeRouteUpdate((newRoute) => {\n console.log(newRoute)\n})\n</script>\n```\n\n```text\nonBeforeRouteUpdate\n```\n\n```text\nvue-router\n```\n\n========================================\n\nComments:\n- Probably because you watch it only in a specific page, hence when you're coming or leaving it, it's not watching it the first time. (maybe `immediate: true` could help here) Still, it's probably better to have this kind of watcher in a middleware or in a wrapping layout.\n- Or use the `/layouts/default.vue`, that way you don't even need to specify it.\n- Nice, this worked. I was trying to setup the watcher in a component. It makes sense if you think about it, because routes only work for the whole page and not a component itself.","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":139,"estimatedTokens":580}}274{"id":"stack-53265106","source":"stackoverflow","questionId":53265106,"title":"nuxt-child doesn't render the parent component","tags":["javascript","vue.js","nuxt.js"],"text":"Title: nuxt-child doesn't render the parent component\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nMy folder structure is like this:\n\n```\n|-profile\n|-- index.vue\n|-- address/index.vue\n```\n\nAnd then I do `` which doesn't render the content of `profile/index.vue`! It just loads a whole new route. Please help!\n\n========================================\n\nCode:\n```text\n|-profile\n|-- index.vue\n|-- address/index.vue\n```\n\n```text\n<nuxt-child />\n```\n\n```text\nprofile/index.vue\n```\n\n```text\n|-pages/\n|--| profile/\n|-----| address.vue\n|-----| index.vue\n|--| profile.vue\n```\n\n```text\n<nuxt-child>\n```\n\n```text\n<nuxt-child>\n```\n\n```text\nprofile.vue\n```\n\n```text\nprofile/index.vue\n```\n\n```text\n/profile\n```\n\n```text\naddress.vue\n```\n\n```text\n/profile/address\n```\n\n========================================\n\nComments:\n- not working for me, how would you do this if your profile was _profile meaning dynamic\n- You'd do the same, but with `_` (underscore) for both `.vue` file and folder. See examples in documentation\n- @aBiscuit I'm using the same approach but when `keep-alive` is enabled, it will cause the `profile` page to cache and show other sub-pages ( like `address.vue` in your case ) and doesn't show the `profile/index.vue` content. Any ideas how to tackle this issue?","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":74,"estimatedTokens":323}}275{"id":"stack-54493541","source":"stackoverflow","questionId":54493541,"title":"\"Module not found\" Error when deploying Nuxtjs app to Netlify","tags":["javascript","vue.js","nuxt.js","netlify"],"text":"Title: \"Module not found\" Error when deploying Nuxtjs app to Netlify\nTags: javascript, vue.js, nuxt.js, netlify\nSource: Stack Overflow\n\nQuestion:\nMy nuxt app is runing locallly without problems but when im trying to deploy the site to Netlify I got error like:\n\n \"Module not found: Error: Can't resolve '~/components/Navbar.vue' in\n '/opt/build/repo/layouts'\"\n\nI'm getting the following error:\n\n```\nERROR in ./layouts/default.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--2-0!./node_modules/vue-loader/lib??vue-loader-options!./layouts/default.vue?vue&type=script&lang=js&)\n6:49:50 PM: Module not found: Error: Can't resolve '~/components/Navbar.vue' in '/opt/build/repo/layouts'\n6:49:50 PM: @ ./layouts/default.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--2-0!./node_modules/vue-loader/lib??vue-loader-options!./layouts/default.vue?vue&type=script&lang=js&) 8:0-45 11:12-18\n6:49:50 PM: @ ./layouts/default.vue?vue&type=script&lang=js&\n6:49:50 PM: @ ./layouts/default.vue\n6:49:50 PM: @ ./.nuxt/App.js\n6:49:50 PM: @ ./.nuxt/index.js\n6:49:50 PM: @ ./.nuxt/client.js\n6:49:50 PM: @ multi ./.nuxt/client.js\n```\n\nPlease help, \nthanks in advance.\n\n========================================\n\nCode:\n```text\nERROR in ./layouts/default.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--2-0!./node_modules/vue-loader/lib??vue-loader-options!./layouts/default.vue?vue&type=script&lang=js&)\n6:49:50 PM: Module not found: Error: Can't resolve '~/components/Navbar.vue' in '/opt/build/repo/layouts'\n6:49:50 PM: @ ./layouts/default.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--2-0!./node_modules/vue-loader/lib??vue-loader-options!./layouts/default.vue?vue&type=script&lang=js&) 8:0-45 11:12-18\n6:49:50 PM: @ ./layouts/default.vue?vue&type=script&lang=js&\n6:49:50 PM: @ ./layouts/default.vue\n6:49:50 PM: @ ./.nuxt/App.js\n6:49:50 PM: @ ./.nuxt/index.js\n6:49:50 PM: @ ./.nuxt/client.js\n6:49:50 PM: @ multi ./.nuxt/client.js\n```\n\n```html\n<script>\n import Navbar from '~/components/Navbar.vue'\n export default {\n\n components: {\n Navbar\n }\n }\n</script>\n```\n\n```text\ncomponents/NavBar.vue\n```\n\n```text\ncomponents/Navbar.Vue\n```\n\n```text\ncomponents/Navbar.vue\n```\n\n========================================\n\nComments:\n- Netlify support agrees: this is almost certainly the problem. It can be pretty hard to change case in git if you have a non-case-sensitive filesystem like OSX and Windows do, this might help you: stackoverflow.com/questions/17683458/…","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":70,"estimatedTokens":636}}276{"id":"stack-62546639","source":"stackoverflow","questionId":62546639,"title":"Request is missing required authentication credentials","tags":["javascript","vue.js","firebase-cloud-messaging","nuxt.js"],"text":"Title: Request is missing required authentication credentials\nTags: javascript, vue.js, firebase-cloud-messaging, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nTrying to get the Firebase Cloud Messaging SDK to work with Nuxt JS I keep getting:\n\nAn error occurred while retrieving token. FirebaseError: Messaging: A problem occured while subscribing the user to FCM: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential.\n\nfcm.js which I'm running as a plugin in nuxt.config.js:\n\n```\nimport firebase from \"../firebase/init\";\n\nfirebase\n .messaging()\n .usePublicVapidKey(\n \"BDYE2EYHdIp8qHjTKcJYPvO4PgaAH2pSruP55FOtNs5jWsgdeg7YK6OgJ0daSu21kN7aSzU19NRXRqC4bfITZYQ \"\n );\n\nfirebase\n .messaging()\n .getToken()\n .then((currentToken) => {\n console.log(currentToken);\n if (currentToken) {\n sendTokenToServer(currentToken);\n updateUIForPushEnabled(currentToken);\n } else {\n // Show permission request.\n console.log(\n \"No Instance ID token available. Request permission to generate one.\"\n );\n // Show permission UI.\n updateUIForPushPermissionRequired();\n setTokenSentToServer(false);\n }\n })\n .catch((err) => {\n console.log(\"An error occurred while retrieving token. \", err);\n showToken(\"Error retrieving Instance ID token. \", err);\n setTokenSentToServer(false);\n });\n```\n\nThe user is authenticated because I am able to access Firestore data and routes in my pages that I've guarded and I can see the UID details in my Vuex store. Removing the `usePublicVapidKey()` line doesn't work.\n\n========================================\n\nTop Answer:\nMake sure the public key you use is from the Firebase console. I was using a public key from the web push package.\n\n========================================\n\nCode:\n```text\nimport firebase from \"../firebase/init\";\n\nfirebase\n .messaging()\n .usePublicVapidKey(\n \"BDYE2EYHdIp8qHjTKcJYPvO4PgaAH2pSruP55FOtNs5jWsgdeg7YK6OgJ0daSu21kN7aSzU19NRXRqC4bfITZYQ \"\n );\n\nfirebase\n .messaging()\n .getToken()\n .then((currentToken) => {\n console.log(currentToken);\n if (currentToken) {\n sendTokenToServer(currentToken);\n updateUIForPushEnabled(currentToken);\n } else {\n // Show permission request.\n console.log(\n \"No Instance ID token available. Request permission to generate one.\"\n );\n // Show permission UI.\n updateUIForPushPermissionRequired();\n setTokenSentToServer(false);\n }\n })\n .catch((err) => {\n console.log(\"An error occurred while retrieving token. \", err);\n showToken(\"Error retrieving Instance ID token. \", err);\n setTokenSentToServer(false);\n });\n```\n\n```text\nusePublicVapidKey()\n```\n\n```text\nfirebase\n .messaging()\n .usePublicVapidKey(\n \"BDYE2EYHdIp8qHjTKcJYPvO4PgaAH2pSruP55FOtNs5jWsgdeg7YK6OgJ0daSu21kN7aSzU19NRXRqC4bfITZYQ \"\n );\n```\n\n========================================\n\nComments:\n- Make sure that the firebase messaging function is called only after the user authentication is done and your store is populated ?\n- Tried that already. Same error\n- does anything need to be in the firebase-messaging-sw.js for it to work? its currently empty\n- you are most probably using a wrong VAPID Key. go to firebase console -> Project settings -> cloud messaging -> web configuration -> web push certificates & copy the VAPID key. then use it in your app.\n- Should te random space be removed from the vapidKey that you pass here?\n- The space is the culprit!","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":110,"estimatedTokens":862}}277{"id":"stack-73069572","source":"stackoverflow","questionId":73069572,"title":"Nuxt.js 3 and on-site anchor navigation","tags":["vue.js","nuxt.js","anchor","nuxt3.js"],"text":"Title: Nuxt.js 3 and on-site anchor navigation\nTags: vue.js, nuxt.js, anchor, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am learning Nuxt.js 3 and am writing a simple project with a one-scroll design that has a menu with anchor links. Clicking a link, the site should automatically scroll to the anchor (like a div with an id).\nTo test this I set up a simple Nuxt 3 installation with `npx nuxi init nuxt-app`, removed the demo content and replaced it with this:\n\n`pages/index.vue`\n\n```\n\n \n hello world\n\n \n \n link\n \n \n placeholder\n ciao world\n\n \n \n link\n \n \n placeholder\n \n\n```\n\nThe problem is, that it is not working. The url in the browser is changed to `localhost:3000/#ciao` or `localhost:3000/#home` on click. But the view is not being changed.\n\nIs there something else I need to set up in nuxt, to get anchor navigation to work?\n\n========================================\n\nCode:\n```html\n<template>\n <div>\n <div id=\"home\"><p>hello world</p></div>\n <div class=\"menu\">\n <nuxt-link :to=\"{ path: '/', hash: '#ciao' }\">\n link\n </nuxt-link>\n </div>\n <div style=\"height: 3000px\">placeholder</div>\n <div id=\"ciao\"><p>ciao world</p></div>\n <div class=\"menu\">\n <nuxt-link :to=\"{ path: '/', hash: '#home' }\">\n link\n </nuxt-link>\n </div>\n <div style=\"height: 3000px\">placeholder</div>\n </div>\n</template>\n```\n\n```text\nnpx nuxi init nuxt-app\n```\n\n```text\npages/index.vue\n```\n\n```text\nlocalhost:3000/#ciao\n```\n\n```text\nlocalhost:3000/#home\n```\n\n```html\n<a href=\"/#ciao\">\n go to ciao's hash\n</a>\n```\n\n```html\n<nuxt-link :to=\"{ hash: '#home' }\" :external=\"true\"> <!-- no need for a path if same page -->\n go to home's hash\n</nuxt-link>\n```\n\n```text\na\n```\n\n```text\nexternal\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":96,"estimatedTokens":432}}278{"id":"stack-61802008","source":"stackoverflow","questionId":61802008,"title":"Vue JS : How can I access and change Css root variables from vue component to toggle CSS Variables Site Theming?","tags":["javascript","vue.js","vue-component","nuxt.js","css-variables"],"text":"Title: Vue JS : How can I access and change Css root variables from vue component to toggle CSS Variables Site Theming?\nTags: javascript, vue.js, vue-component, nuxt.js, css-variables\nSource: Stack Overflow\n\nQuestion:\nI want to access the values of css root variables in the project in a Vue component. For example, change the 10 variables, including the color, margin, and font size, by pressing a button to the new values, and then pressing the same button to change the variables to their ( default ) original values, in fact changing the values of the css root variables in the project. How can I do this ? In fact, I want to switch between dark and light by pressing a button.\n\nThis idea is inspired by the changes from the link below.\nThe example inside the link is written in the pure JavaScript script, and I want to use it in the Vue project that develope on Next Js Framework . To implement a website with about 10 variables whose values must change immediately with pressing a button to toggling in the dark / light mode.\n\nThe codepen link that inspired me :)\n\nHow can I access and change Css root variables?\n\n\r\n\r\n\n```\nnew Vue({\r\n\tel: \"#theme\",\r\n\tdata: {\r\n return {\r\n dark: true,\r\n \r\n };\r\n },\r\n \r\n watch: {\r\n dark() {\r\n \r\n let bg = this.dark ? \"#1b1b1b\" : \"#f5f5f5\";\r\n let txtColor = this.dark ? \"#999999\" : \"#333333\";\r\n \r\n document.documentElement.style.setProperty(\"--bg\", bg);\r\n document.documentElement.style.setProperty(\"--txt\", txtColor);\r\n \r\n }\r\n }\r\n});\n```\n\n\r\n\n```\n:root{\r\n\r\n--bg: white;\r\n--txt: black;\r\n\r\n}\r\n\r\n\r\nbody {\r\n background-color: var(--bg);\r\n color: var(--txt)\r\n}\r\narticle {\r\n padding: 50px\r\n}\r\narticle h2 {\r\n margin-top: 100px;\r\n}\n```\n\n\r\n\n```\n\r\n\r\n dark\r\n\r\n\r\n \n\n### Hello World\n\n\r\n Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean v\r\n\r\n\r\n\n```\n\n========================================\n\nCode:\n```js\nnew Vue({\n\tel: \"#theme\",\n\tdata: {\n return {\n dark: true,\n \n };\n },\n \n watch: {\n dark() {\n \n let bg = this.dark ? \"#1b1b1b\" : \"#f5f5f5\";\n let txtColor = this.dark ? \"#999999\" : \"#333333\";\n \n document.documentElement.style.setProperty(\"--bg\", bg);\n document.documentElement.style.setProperty(\"--txt\", txtColor);\n \n }\n }\n});\n```\n\n```css\n:root{\n\n--bg: white;\n--txt: black;\n\n}\n\n\nbody {\n background-color: var(--bg);\n color: var(--txt)\n}\narticle {\n padding: 50px\n}\narticle h2 {\n margin-top: 100px;\n}\n```\n\n```html\n<div id=\"theme\">\n\n <button @click=\"dark=!dark\">dark</button>\n\n<article>\n <h1>Hello World</h1>\n Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean v\n</article>\n\n</div>\n```\n\n```js\nnew Vue({\n el: \"#theme\",\n data() {\n return {\n dark: false,\n root: null\n };\n },\n mounted: function() {\n this.root = document.documentElement;\n },\n watch: {\n dark: {\n handler: function() {\n // because we are using this handler immideatly we need to wait for data changes using nextTick.\n this.$nextTick(() => {\n if (this.dark) {\n this.root.style.setProperty(\"--bg\", \"red\");\n this.root.style.setProperty(\"--text\", \"black\");\n this.root.style.setProperty(\"--padding\", \"10px\");\n this.root.style.setProperty(\"--font\", \"1rem\");\n } else {\n this.root.style.setProperty(\"--bg\", \"blue\");\n this.root.style.setProperty(\"--text\", \"green\");\n this.root.style.setProperty(\"--padding\", \"15px\");\n this.root.style.setProperty(\"--font\", \"2rem\");\n }\n })\n },\n immediate: true\n\n }\n }\n});\n```\n\n```css\n:root {\n --bg: white;\n --bg-text: black;\n --padding: 5px;\n --font: 3rem;\n}\n\nbody {\n background-color: var(--bg);\n color: var(--bg-text)\n}\n\narticle {\n padding: 50px\n}\n\narticle h2 {\n margin-top: 100px;\n}\n```\n\n```html\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"></script>\n<div id=\"theme\">\n\n <button @click=\"dark=!dark\">dark</button>\n\n <article>\n <h1>Hello World</h1>\n Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis,\n sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus.\n Vivamus elementum semper nisi. Aenean v\n </article>\n\n</div>\n```\n\n```text\ndata\n```\n\n========================================\n\nComments:\n- Yes, the bright mode will be displayed in the initial load.\n- I have updated my answer. You need to add `handler` and `immediate` properties to watch. Also, set `dark` to false\n- Thanks, between this solution and the next answer solution , which one has better performance?\n- I am not sure about performance. My guess that it won't make much difference if you have few changes. You can use computed instead of watch if you want vuejs to cache the values.\n- It nuxt js Framework gives an error when running, error text : ReferenceError document is not defined\n- I suspected this would an error but the example worked fine. Move root definition to `mounted` hook. I will update my answer.\n- Is it possible to delete the root values from the CSS file altogether, and execute their Variable the component from the beginning according to the condition, that is, to delete them from the CSS file ???\n- Yes it is. However, for best practice I prefer to initiate values from CSS file and then change through Vue.js (without using `immediate: true`). This way the content has some style even withouth JS loaded.\n- Thank you, if we want to save the user's choice in the local storage and show the user's selected mode in the next logs. In fact, I want the user selection to be saved locally in storage and run the same mode by default in the next visit. What is the right way to do this?\n- You might need to post a separate question for this.","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":236,"estimatedTokens":1752}}279{"id":"stack-52240262","source":"stackoverflow","questionId":52240262,"title":"Access LocalStorage in Middleware - NuxtJs","tags":["javascript","vue.js","local-storage","vue-router","nuxt.js"],"text":"Title: Access LocalStorage in Middleware - NuxtJs\nTags: javascript, vue.js, local-storage, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWell, I'm starting with nuxt and I have following routes:\n\n```\n/home\n\n/dashboard\n\n/login\n```\n\nI want to protect the /dashboard, but only for users logged in with a token in `localStorage`.\n\nThe simplest way I thought of doing this was by creating a /middleware/auth.js\n\n```\nexport default function () {\n if (!window.localStorage.getItem('token')) {\n window.location = '/login'\n }\n}\n```\n\nand registering it in the /dashboard/index.vue component.\n\n```\n\nexport default {\n middleware: 'auth',\n}\n\n```\n\nBut I cannot access `localStorage` within a middleware, because LocalStorage is client-side.\n\nI have already tried to add this same check in the `created()` dashboard layout, but I cannot return window not set `mounted()` is too late, it can only check after the page has been fully assembled.\n\nSo how can I achieve this?\nNote: I do not intend to use any Vuex for this project.\n\n========================================\n\nTop Answer:\nFor anyone not satisfied storing the information in cookies, here's me solution:\n\nI've been having a lot of problems with this and I were not satisfied setting a cookie. \nIf you are running Nuxt and haven't told it to run in spa mode it will run in universal mode. Nuxt defines universal mode as: \n\n Isomorphic application (server-side rendering + client-side navigation)\n\nThe result being that localStorage is not defined serverside and thus throws an error. \n\nThe give away for me was that console logging from middleware files and Vuex outputted to terminal and not the console in developer tools in the browser.\n\nThe solution for me was to change the mode to spa in the nuxt.config.js which is located at the root. \n\nPlease notice that you can still access localStorage, running universal mode, in page files and components because they are not server side. \n\nMiddleware files are, in universal mode, run server side, so changing to spa mode makes them run client side and thus allows them access to localStorage.\n\nFor more information about Nuxt modes, read these:\n\n- https://nuxtjs.org/guide/\n\n- https://recurse.me/posts/choosing-a-nuxt-mode.html\n\n========================================\n\nCode:\n```text\n/home\n\n/dashboard\n\n/login\n```\n\n```text\nexport default function () {\n if (!window.localStorage.getItem('token')) {\n window.location = '/login'\n }\n}\n```\n\n```text\n<script>\nexport default {\n middleware: 'auth',\n}\n</script>\n```\n\n```text\nlocalStorage\n```\n\n```text\nlocalStorage\n```\n\n```text\ncreated()\n```\n\n```text\nmounted()\n```\n\n```text\nwindow.$cookies.set('token', payload, {\n path: '/',\n})\n```\n\n```text\nexport default (context) => {\n if (!context.app.$cookies.get('token')) {\n return context.redirect('/login')\n }\n}\n```\n\n```text\nexport default defineNuxtRouteMiddleware(to => {\n\n if (process.server) {\n // this section will run on the server\n }\n\n if (process.client) {\n //this section will run in the browser so you can access \n // local storage\n }\n\n\n const nuxtApp = useNuxtApp()\n if (process.client && nuxtApp.isHydrating && \n nuxtApp.payload.serverRendered) {\n // this section will run only once , in the browser, when the page \n // initialized\n }\n})\n```\n\n```text\nexport default defineNuxtRouteMiddleware((to, from) => {\n // skip middleware on server (first middleware execution)\n if (import.meta.server) return\n\n // now we are on the client side (second middleware execution)\n // we have access to localStorage\n if (import.meta.client)\n if(localStorage.getItem('token'))\n return\n else\n return navigateTo('/login')\n})\n```\n\n========================================\n\nComments:\n- I did not find ways to use examples, or documentation\n- @YungSilva yes, it don`t exist yet. Sources are way to go.The point is that you need to either use cookies or to use other thing than middleware -> see this issue for problems and some workaround github.com/nuxt/nuxt.js/issues/2653#issuecomment-390588837\n- This is actually very decent module. I just used it in one of my projects and it works really well.","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":170,"estimatedTokens":1043}}280{"id":"stack-49117416","source":"stackoverflow","questionId":49117416,"title":"website using nuxt and @nuxtjs/pwa not caching google fonts","tags":["service-worker","nuxt.js"],"text":"Title: website using nuxt and @nuxtjs/pwa not caching google fonts\nTags: service-worker, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI created my app with `npx create-nuxt-app`, then added `npm install @nuxtjs/pwa --save`. I'm including a google font in index.html with:\n\n```\n\n```\n\nI tested my app in offline mode in Chrome by clicking the \"Offline\" checkbox in the devtools/application tab, and reloading. Everything is cached except for the font.\n\nI then added:\n\n```\nworkbox: {\n runtimeCaching: [\n {\n urlPattern: 'https://fonts.googleapis.com/.*',\n handler: 'cacheFirst',\n method: 'GET'\n },\n ]\n}\n```\n\nto the `nuxt.config.js` file but I can't get the font to be cached. I've tried a number of variations on the urlPattern.\n\nNuxt is generating a service worker for me, and it looks like this:\n\n```\nimportScripts('/_nuxt/workbox.3de3418b.js')\n\nconst workboxSW = new self.WorkboxSW({\n \"cacheId\": \"my-app\",\n \"clientsClaim\": true,\n \"directoryIndex\": \"/\"\n})\n\nworkboxSW.precache([\n {\n \"url\": \"/_nuxt/app.bb74329360a7ee70c2af.js\",\n \"revision\": \"8477c51cbf9d3188f34f1d61ec1ae6bc\"\n },\n {\n \"url\": \"/_nuxt/layouts/default.ce9446c7c3fffa50cfd2.js\",\n \"revision\": \"504d33b2d46614e60d919e01ec59bbc8\"\n },\n {\n \"url\": \"/_nuxt/manifest.912c22076a54259e047d.js\",\n \"revision\": \"a51a74b56987961c8d34afdcf4efa85c\"\n },\n {\n \"url\": \"/_nuxt/pages/index.6bfd6741c6dfd79fd94d.js\",\n \"revision\": \"1a80379a5d35d5d4084d4c2b85e1ee10\"\n },\n {\n \"url\": \"/_nuxt/vendor.f681eb653617896fcd64.js\",\n \"revision\": \"59c58901fd5142fdaac57cbee8c1aeb4\"\n }\n])\n\nworkboxSW.router.registerRoute(new RegExp('/_nuxt/.*'), workboxSW.strategies.cacheFirst({}), 'GET')\n\nworkboxSW.router.registerRoute(new RegExp('/.*'), workboxSW.strategies.networkFirst({}), 'GET')\n\nworkboxSW.router.registerRoute(new RegExp('https://fonts.googleapis.com/.*'), workboxSW.strategies.cacheFirst({}), 'GET')\n```\n\nWhy is the font not getting cached?\n\nEDIT #1:\nThanks to Jeff Posnick, I understand what's happening. I haven't figured out the right syntax to pass in the `nuxt.config.js` file, but as an experiment, I hacked the `sw.js` file directly and added these two lines:\n\n```\nworkboxSW.router.registerRoute(new RegExp('https://fonts.googleapis.com/.*'),\n workboxSW.strategies.cacheFirst({cacheableResponse: {statuses: [0, 200]}}), \n 'GET')\n\nworkboxSW.router.registerRoute(new RegExp('https://fonts.gstatic.com/.*'),\n workboxSW.strategies.cacheFirst({cacheableResponse: {statuses: [0, 200]}}),\n 'GET')\n```\n\nThat worked!\n\n========================================\n\nTop Answer:\nThis is due to the fact that Workbox won't cache opaque responses using a `cacheFirst` strategy, unless you specifically tell it to.\n\nThis was a common source of confusion with Workbox v2, and we've improved the JavaScript console logs and documentation for the upcoming v3 release. The \"Handle Third Party Requests\" guide goes into more detail.\n\nYou can change your config to\n\n```\nruntimeCaching: [{\n urlPattern: 'https://fonts.googleapis.com/.*',\n handler: 'cacheFirst',\n method: 'GET',\n cacheableResponse: {statuses: [0, 200]}\n}]\n```\n\nto get that behavior in the current v2 release of Workbox.\n\n========================================\n\nCode:\n```text\n<link href=\"https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons\" rel=\"stylesheet\" data-n-head=\"true\">\n```\n\n```text\nworkbox: {\n runtimeCaching: [\n {\n urlPattern: 'https://fonts.googleapis.com/.*',\n handler: 'cacheFirst',\n method: 'GET'\n },\n ]\n}\n```\n\n```text\nimportScripts('/_nuxt/workbox.3de3418b.js')\n\nconst workboxSW = new self.WorkboxSW({\n \"cacheId\": \"my-app\",\n \"clientsClaim\": true,\n \"directoryIndex\": \"/\"\n})\n\nworkboxSW.precache([\n {\n \"url\": \"/_nuxt/app.bb74329360a7ee70c2af.js\",\n \"revision\": \"8477c51cbf9d3188f34f1d61ec1ae6bc\"\n },\n {\n \"url\": \"/_nuxt/layouts/default.ce9446c7c3fffa50cfd2.js\",\n \"revision\": \"504d33b2d46614e60d919e01ec59bbc8\"\n },\n {\n \"url\": \"/_nuxt/manifest.912c22076a54259e047d.js\",\n \"revision\": \"a51a74b56987961c8d34afdcf4efa85c\"\n },\n {\n \"url\": \"/_nuxt/pages/index.6bfd6741c6dfd79fd94d.js\",\n \"revision\": \"1a80379a5d35d5d4084d4c2b85e1ee10\"\n },\n {\n \"url\": \"/_nuxt/vendor.f681eb653617896fcd64.js\",\n \"revision\": \"59c58901fd5142fdaac57cbee8c1aeb4\"\n }\n])\n\n\nworkboxSW.router.registerRoute(new RegExp('/_nuxt/.*'), workboxSW.strategies.cacheFirst({}), 'GET')\n\nworkboxSW.router.registerRoute(new RegExp('/.*'), workboxSW.strategies.networkFirst({}), 'GET')\n\nworkboxSW.router.registerRoute(new RegExp('https://fonts.googleapis.com/.*'), workboxSW.strategies.cacheFirst({}), 'GET')\n```\n\n```text\nworkboxSW.router.registerRoute(new RegExp('https://fonts.googleapis.com/.*'),\n workboxSW.strategies.cacheFirst({cacheableResponse: {statuses: [0, 200]}}), \n 'GET')\n\nworkboxSW.router.registerRoute(new RegExp('https://fonts.gstatic.com/.*'),\n workboxSW.strategies.cacheFirst({cacheableResponse: {statuses: [0, 200]}}),\n 'GET')\n```\n\n```text\nnpx create-nuxt-app\n```\n\n```text\nnpm install @nuxtjs/pwa --save\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nsw.js\n```\n\n```text\nworkbox: {\n runtimeCaching: [\n {\n urlPattern: 'https://fonts.googleapis.com/.*',\n handler: 'cacheFirst',\n method: 'GET',\n strategyOptions: {cacheableResponse: {statuses: [0, 200]}}\n },\n {\n urlPattern: 'https://fonts.gstatic.com/.*',\n handler: 'cacheFirst',\n method: 'GET',\n strategyOptions: {cacheableResponse: {statuses: [0, 200]}}\n },\n ]\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nruntimeCaching: [{\n urlPattern: 'https://fonts.googleapis.com/.*',\n handler: 'cacheFirst',\n method: 'GET',\n cacheableResponse: {statuses: [0, 200]}\n}]\n```\n\n```text\ncacheFirst\n```\n\n```text\npwa: {\n workbox: {\n runtimeCaching: [\n {\n urlPattern: 'https://my-api-url/.*',\n handler: 'networkFirst',\n method: 'GET',\n strategyOptions: {\n cacheName: 'my-api-cache',\n cacheableResponse: {statuses: [0, 200]}\n }\n }\n ]\n }\n },\n```\n\n```text\n@nuxtjs/pwa@3.0.0-beta.20\n```\n\n```text\nnuxt@2.11.0\n```\n\n```text\npwa\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nCache Storage\n```\n\n```text\nruntimeCaching: [\n {\n urlPattern: 'https://fonts.googleapis.com/.*',\n handler: 'CacheFirst',\n method: 'GET',\n options: {cacheableResponse: {statuses: [0, 200]}}\n },\n {\n urlPattern: 'https://fonts.gstatic.com/.*',\n handler: 'CacheFirst',\n method: 'GET',\n options: {cacheableResponse: {statuses: [0, 200]}}\n },\n ]\n```\n\n========================================\n\nComments:\n- Thanks for the explanation and example! I'm still struggling with getting the google font cached, though. After adding the cacheableResponse line, the generated sw.js file is not changed from what I posted in the question.","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":291,"estimatedTokens":1741}}281{"id":"stack-61354470","source":"stackoverflow","questionId":61354470,"title":"Nuxt: Fetching data only on server side","tags":["vue.js","nuxt.js","server-side-rendering"],"text":"Title: Nuxt: Fetching data only on server side\nTags: vue.js, nuxt.js, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nI am using Github's API to fetch the list of my pinned repositories, and I put the call in the AsyncData method so that I have the list on the first render. But I just learnt that AsyncData is called once on ServerSide, then everytime the page is loaded on the client. That means that the client no longer has the token to make API calls, and anyways, I wouldn't let my Github token in the client.\n\nAnd when I switch page (from another page to the page with the list) the data is not there I just have the default empty array\n\nI can't figure out what is the best way to be sure that my data is always loaded on server side ?\n\n```\nexport default defineComponent({\n name: 'Index',\n components: { GithubProject, Socials },\n asyncData(context: Context) {\n return context.$axios.$post>('https://api.github.com/graphql', {\n query,\n }, {\n headers: {\n // Token is defined on the server, but not on the client\n Authorization: `bearer ${process.env.GITHUB_TOKEN}`,\n },\n })\n .then((data) => ({ projects: data.data.user.pinnedItems.nodes }))\n .catch(() => {});\n },\n setup() {\n const projects = ref([]);\n\n return {\n projects,\n };\n },\n});\n```\n\n========================================\n\nTop Answer:\nWrap your request in `if(process.server)` within the `asyncData` method of the page.\n\nIf you absolutely require the server-side to call and cannot do it from the client side, then you can just manipulate the `location.href` to force the page to do a full load.\n\n========================================\n\nCode:\n```ts\nexport default defineComponent({\n name: 'Index',\n components: { GithubProject, Socials },\n asyncData(context: Context) {\n return context.$axios.$post<Query<UserPinnedRepositoriesQuery>>('https://api.github.com/graphql', {\n query,\n }, {\n headers: {\n // Token is defined on the server, but not on the client\n Authorization: `bearer ${process.env.GITHUB_TOKEN}`,\n },\n })\n .then((data) => ({ projects: data.data.user.pinnedItems.nodes }))\n .catch(() => {});\n },\n setup() {\n const projects = ref<Repository[]>([]);\n\n return {\n projects,\n };\n },\n});\n```\n\n```js\nexport const state = () => ({\n data: []\n})\n```\n\n```js\nexport const actions = {\n async nuxtServerInit ({ state }, { req }) {\n let response = await axios.get(\"some/path/...\");\n state.data = response.data;\n }\n}\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nstore/index.js\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nreq\n```\n\n```text\nlet cookie = req.headers.cookie;\n```\n\n```text\nif(process.server)\n```\n\n```text\nasyncData\n```\n\n```text\nlocation.href\n```\n\n========================================\n\nComments:\n- That's indeed a solution, but I'm just catching the error and not doing anything, that's the same. My problem here is that If I navigate onto this page, I don't have the data. I really need the server to make this request, not the server\n- @nook Then you're going to need to use `location.href=/my-page` instead of using Vue router, so it forces a hard load.\n- Obviously. So simple that I forgot that. A basic anchor should do the work though. Please update your answer so I can validate it\n- There is no authentication required, the request will always be the same, no matter who, no matter where. I need to try your solution, I think this is what I needed.\n- You can also store the API token in the store. when u navigate between pages the store wont lose his state. Only if you refresh the page the store will refresh\n- Is the store available to the user when inspecting ? This is a personnal access token to Github's API, not my own platform token.\n- the store is technically inspectable because its on the client side... because `nuxtServerInit` is on the server side you can use `env` variables\n- Alright, I already use env variables for the token. Putting the token in the store is way too risky and may result in an anticipated token expiracy.\n- i am not quite sure but you should be able to access your variables like this `process.env` in the `nuxtServerInit` function\n- Exactly this way :)","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":137,"estimatedTokens":1047}}282{"id":"stack-67364474","source":"stackoverflow","questionId":67364474,"title":"Vuetify: editing no-data-text prop or no-data slot for v-select doesn't seem to have any effect","tags":["nuxt.js","vuetify.js","v-select","no-data"],"text":"Title: Vuetify: editing no-data-text prop or no-data slot for v-select doesn't seem to have any effect\nTags: nuxt.js, vuetify.js, v-select, no-data\nSource: Stack Overflow\n\nQuestion:\nI'm using Vuetify in a Nuxt project. By using the slot `no-data` in a `v-data-table` I was able to modify the \"No data available\" message. It's also working if I use the prop `no-data-text`.\n\n```\n\n \n My no data message\n \n\n```\n\nOR\n\n```\n\n```\n\nAs the documentation of the v-select shows the same prop and slot, I tried to update the message as well but I still have \"No data available\" showing instead of my own message.\nAm I doing something wrong?\n\nThe only other subject I found which might be related is https://github.com/vuetifyjs/vuetify/issues/2081\n\nThanks in advance for any help!\n\n========================================\n\nTop Answer:\nYou can use the v-bind syntax if the no data text will change based on some condition\n\n```\n \n \n\nexport default {\n data:function(){\n return {\n no_results_text: \"test message\"\n }\n }, \n methods: {\n updateText(){\n this.no_results_text=\"other message\"\n }\n }\n}\n\n```\n\n========================================\n\nCode:\n```text\n<v-data-table>\n <template slot=\"no-data\">\n My no data message\n </template>\n</v-data-table>\n```\n\n```text\n<v-data-table no-data-text=\"My no data message\"></v-data-table>\n```\n\n```text\nno-data\n```\n\n```text\nv-data-table\n```\n\n```text\nno-data-text\n```\n\n```text\n<v-data-table :no-data-text=\"no_results_text\"> \n </v-data-table>\n\n<script>\nexport default {\n data:function(){\n return {\n no_results_text: \"test message\"\n }\n }, \n methods: {\n updateText(){\n this.no_results_text=\"other message\"\n }\n }\n}\n</script>\n```\n\n```text\n<v-data-table ...> \n</v-data-table>\n\n<template #no-data>\n {{ no_results_text }}\n</template>\n\n<script>\nexport default {\n data(){\n return {\n no_results_text: \"test message\"\n }\n }, \n methods: {\n updateText(){\n this.no_results_text=\"other message\"\n }\n }\n}\n</script>\n```\n\n```text\n<template #no-data>\n <span v-html=\"no_results_text\"></span>\n</template>\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":128,"estimatedTokens":515}}283{"id":"stack-56381771","source":"stackoverflow","questionId":56381771,"title":"Nuxt: Unexpected token <","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Nuxt: Unexpected token <\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nhttps://i.sstatic.net/MbM9f.png\n\nI am working on a nuxt project, and I'm trying to build a map component using google maps and the plugin https://www.npmjs.com/package/vue2-google-maps. I have installed the plugin using npm\n\nIn my index.html page I have a normally working page that looks like:\n\n```\n\n \n\n \n\n -->\n \n \n \n\nimport Panel from '~/components/panel.vue'\nimport Card from '~/components/detailCard.vue'\n// import GoogleMap from '~/components/googleMap.vue'\n\nexport default {\n\n components: {\n\n Panel,\n Card,\n// GoogleMap\n }\n\n}\n\n```\n\nWhen I Uncomment the 3 lines with Googlemap in them I get the error in the screenshot .\n\nThe Googlemap component is:\n\n```\n\n \n \n\nimport Vue from \"vue\";\nimport * as VueGoogleMaps from \"vue2-google-maps\";\n\nVue.use(VueGoogleMaps, {\n load: {\n key: \"MYTOKEN\",\n libraries: \"places\"\n }\n});\n\nexport default {\n\n}\n\n```\n\nWhat am I doing wrong?\n\nedit:\n\nhttps://i.sstatic.net/EeLKF.png\n\n========================================\n\nTop Answer:\nOften it refers to the response from a request, where it was expecting a JSON object, but instead is returned HTML. The `Check the responses coming back from the APIs or other services you’re using.\n\n========================================\n\nCode:\n```text\n<template>\n <div>\n\n<br>\n<br>\n <Card/>\n<br>\n<br>\n<br>\n<br>\n <!-- <Googlemap/> -->\n <Panel/>\n <Four/>\n </div> \n</template>\n\n<script>\n\nimport Panel from '~/components/panel.vue'\nimport Card from '~/components/detailCard.vue'\n// import GoogleMap from '~/components/googleMap.vue'\n\n\nexport default {\n\n components: {\n\n Panel,\n Card,\n// GoogleMap\n }\n\n}\n</script>\n```\n\n```text\n<template>\n <GmapMap\n :center=\"{lat:10, lng:10}\"\n :zoom=\"7\"\n map-type-id=\"terrain\"\n style=\"width: 500px; height: 300px\"\n>\n <GmapMarker\n :key=\"index\"\n v-for=\"(m, index) in markers\"\n :position=\"m.position\"\n :clickable=\"true\"\n :draggable=\"true\"\n @click=\"center=m.position\"\n />\n</GmapMap>\n\n</template>\n\n\n<script>\nimport Vue from \"vue\";\nimport * as VueGoogleMaps from \"vue2-google-maps\";\n\nVue.use(VueGoogleMaps, {\n load: {\n key: \"MYTOKEN\",\n libraries: \"places\"\n }\n});\n\nexport default {\n\n}\n\n</script>\n\n\n<style>\n\n</style>\n```\n\n```text\ntranspile: [/^vue2-google-maps($|\\/)/]\n```\n\n```text\n<\n```\n\n```text\n<!DOCTYPE\n```\n\n========================================\n\nComments:\n- I've added a screenshot of the net tab in devtools. I'm not seeing anything from google. I've not used this api key before so its possible its somehow not active. Any thoughts on how to test that?\n- After adding your statement to the build object, the error is gone. However I do not see a map.\n- @user61629 hard to say what wrong else. create a codesandbox with reproductio","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":177,"estimatedTokens":702}}284{"id":"stack-68405988","source":"stackoverflow","questionId":68405988,"title":"How do I intercept server-side api calls by cypress","tags":["nuxt.js","cypress"],"text":"Title: How do I intercept server-side api calls by cypress\nTags: nuxt.js, cypress\nSource: Stack Overflow\n\nQuestion:\nI am using Nuxt.js as frontend framework and Laravel as api server, and writing some e2e testings with Cypress. I'm trying to reduce asyncData api call by using cy.intercept but failed to sucessfully intercept the api call, my test spec looks like below:\n\n```\nconst siteUrl = Cypress.env('site_url')\nconst apiUrl = Cypress.env('api_url')\ndescribe('Post Test', () => {\n beforeEach(() => {\n cy.intercept('GET', `${apiUrl}/post`, {\n fixture: 'post.json',\n })\n })\n it('should render posts same as mock data', () => {\n cy.visit(`/post`)\n cy.contains('some posts from mock data')\n })\n})\n```\n\nand my posts/index.vue look like this:\n\n```\n\n \n \n\n### {{ post.title }}\n\n {{ post.description }}\n\n \n\n export default {\n async asyncData({ params, $http }) {\n const post = await $http.$get(`${apiUrl}/post`)\n return { post }\n }\n }\n\n```\n\nWhen I run the test, in asyncData hook Nuxt.js will still send actual request to Laravel asking for post data. I've read this issue but still want to ask is there any other ways to intercept api calls from server-side with Cypress?\n\n========================================\n\nCode:\n```js\nconst siteUrl = Cypress.env('site_url')\nconst apiUrl = Cypress.env('api_url')\ndescribe('Post Test', () => {\n beforeEach(() => {\n cy.intercept('GET', `${apiUrl}/post`, {\n fixture: 'post.json',\n })\n })\n it('should render posts same as mock data', () => {\n cy.visit(`/post`)\n cy.contains('some posts from mock data')\n })\n})\n```\n\n```html\n<template>\n <div>\n <h1>{{ post.title }}</h1>\n <p>{{ post.description }}</p>\n </div>\n</template>\n\n<script>\n export default {\n async asyncData({ params, $http }) {\n const post = await $http.$get(`${apiUrl}/post`)\n return { post }\n }\n }\n</script>\n```\n\n```js\nlet server; // static reference to the mock server\n // so we can close and re-assign on 2nd call\n\nmodule.exports = (on, config) => {\n on('task', {\n mockServer({ interceptUrl, fixture }) {\n\n const fs = require('fs')\n const http = require('http')\n const { URL } = require('url')\n\n if (server) server.close(); // close any previous instance\n\n const url = new URL(interceptUrl)\n server = http.createServer((req, res) => {\n if (req.url === url.pathname) {\n const data = fs.readFileSync(`./cypress/fixtures/${fixture}`)\n res.end(data)\n } else {\n res.end()\n }\n })\n\n server.listen(url.port)\n console.log(`listening at port ${url.port}`)\n\n return null\n },\n })\n}\n```\n\n```js\nconst apiUrl = Cypress.env('api_url'); // e.g \"http://localhost:9000\"\n\ncy.task('mockServer', { interceptUrl: `${apiUrl}/post`, fixture: 'post.json' })\ncy.visit('/post')\n\n// a different fixture\ncy.task('mockServer', { interceptUrl: `${apiUrl}/post`, fixture: 'post2.json' })\ncy.visit('/post')\n```\n\n```js\n{\n \"baseUrl\": \"http://localhost:3000\",\n \"env\": {\n \"api_url\": \"http://localhost:9000\"\n }\n}\n```\n\n```js\nfunction interceptHydration( interceptUrl, fixture, key ) {\n cy.fixture(fixture).then(mockData => {\n cy.intercept(\n interceptUrl,\n (req) => {\n req.continue(res => {\n // look for \"key\" in page body, replace with fixture\n const regex = new RegExp(`${key}:\\s*{([^}]*)}`)\n const mock = `${key}: ${JSON.stringify(mockData)}`\n res.body = res.body.replace(regex, mock)\n })\n }\n )\n })\n}\n\nit('changes hydration data', () => {\n interceptHydration( '/post', 'post', 'post' )\n cy.visit('/post')\n cy.get('h1').contains('post #2') // value from fixture\n})\n```\n\n```text\nasyncData()\n```\n\n```text\ncy.intercept()\n```\n\n```text\napiUrl\n```\n\n========================================\n\nComments:\n- It works! Now all I need is to extend it to support HTTP methods, thank you! Can I ask how you worked this out? I couldn't find it on Cypress official doc\n- From your description it seemed that start-server-and-test was the way to go, picking the simplest server (node http) it seemed easier to wrap it in a task - the whole thing is less fuss for anyone who knows Cypress.\n- What is the key parameter in the interceptHydration function referencing?","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":179,"estimatedTokens":1067}}285{"id":"stack-66175833","source":"stackoverflow","questionId":66175833,"title":"Nuxt.js: How move Global CSS from style tag to css file","tags":["javascript","vue.js","webpack","nuxt.js"],"text":"Title: Nuxt.js: How move Global CSS from style tag to css file\nTags: javascript, vue.js, webpack, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm confused with the Nuxt.js SCSS compilation...\nI have the **assets** folder and it has two SCSS files included in `nuxt.config.js`:\n\n```\n// Global CSS (https://go.nuxtjs.dev/config-css)\n css: [\n '~assets/scss/bootstrap.scss',\n '~assets/scss/main.scss'\n ],\n```\n\nLaunch `npm run build` and then `npm run generate`, then I go into the **dist** folder and open the **index.html** file, what I see is all css (and it is too big) inside the **style** tag on the page:\n\nhttps://i.sstatic.net/uu1Zw.png\n\nNuxt.js has compiled the SCSS files from assets and put CSS in the style tag.\nHow put into a file and connect with link tag in the head section like this?\n\n```\n\n```\n\nYou may say I can use **head** settings in `nuxt.config.js`, but I cannot because it is possible only with remote and static files, it does not work like this:\n\n```\nhead: {\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1, user-scalable=0, shrink-to-fit=no' },\n { hid: 'description', name: 'description', content: '' }\n ],\n link: [\n { rel: 'stylesheet', href: '~/assets/scss/bootstrap.scss' },\n { rel: 'stylesheet', href: '~/assets/scss/main.scss' },\n { rel: 'icon', type: 'image/svg+xml', href: '/images/logo.svg' },\n ],\n script: []\n},\n```\n\nI did not find in the Nuxt.js documentation how put the Global CSS to a file. Is it possible with Nuxt.js config or change the Webpack build config only? Help me understand please :-)\n\n========================================\n\nCode:\n```text\n// Global CSS (https://go.nuxtjs.dev/config-css)\n css: [\n '~assets/scss/bootstrap.scss',\n '~assets/scss/main.scss'\n ],\n```\n\n```text\n<link rel=\"stylesheet\" href=\"/css/bootstrap.css\">\n<link rel=\"stylesheet\" href=\"/css/main.css\">\n```\n\n```text\nhead: {\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1, user-scalable=0, shrink-to-fit=no' },\n { hid: 'description', name: 'description', content: '' }\n ],\n link: [\n { rel: 'stylesheet', href: '~/assets/scss/bootstrap.scss' },\n { rel: 'stylesheet', href: '~/assets/scss/main.scss' },\n { rel: 'icon', type: 'image/svg+xml', href: '/images/logo.svg' },\n ],\n script: []\n},\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run generate\n```\n\n```text\nnuxt.config.js\n```\n\n```js\n// nuxt.config.js\n\nexport default {\n build: {\n extractCSS: true\n }\n}\n```\n\n```text\nextractCSS\n```\n\n========================================\n\nComments:\n- Dat works! I'll be read the docs more accurately. thanks for the answer and the doc link.\n- I'm wondering if there are some issues with it being set to `true` as a default because this one seems to be really nice and with no drawbacks.\n- The drawback is that the users browser has to make multiple network requests.","metadata":{"transformedAt":"2026-08-18T18:33:07.854Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":115,"estimatedTokens":732}}286{"id":"stack-71648007","source":"stackoverflow","questionId":71648007,"title":"Npm install error. 'npm ERR! gyp ERR! find Python, stack Error'","tags":["python","node.js","npm","nuxt.js","npm-install"],"text":"Title: Npm install error. 'npm ERR! gyp ERR! find Python, stack Error'\nTags: python, node.js, npm, nuxt.js, npm-install\nSource: Stack Overflow\n\nQuestion:\nWhenever I try to run `npm install` or `npm update` in my nuxt.js(vue.js) project, error below appears.\n\n```\nnpm ERR! code 1\nnpm ERR! path /Users/kyeolhan/ForWork/BackOffceFront/node_modules/deasync\nnpm ERR! command failed\nnpm ERR! command sh -c node ./build.js\nnpm ERR! gyp info it worked if it ends with ok\nnpm ERR! gyp info using node-gyp@7.1.2\nnpm ERR! gyp info using node@16.14.2 | darwin | arm64\nnpm ERR! gyp ERR! find Python\nnpm ERR! gyp ERR! find Python Python is not set from command line or npm configuration\nnpm ERR! gyp ERR! find Python Python is not set from environment variable PYTHON\nnpm ERR! gyp ERR! find Python checking if \"python3\" can be used\nnpm ERR! gyp ERR! find Python - \"python3\" is not in PATH or produced an error\nnpm ERR! gyp ERR! find Python checking if \"python\" can be used\nnpm ERR! gyp ERR! find Python - \"python\" is not in PATH or produced an error\nnpm ERR! gyp ERR! find Python checking if \"python2\" can be used\nnpm ERR! gyp ERR! find Python - \"python2\" is not in PATH or produced an error\nnpm ERR! gyp ERR! find Python\nnpm ERR! gyp ERR! find Python **********************************************************\nnpm ERR! gyp ERR! find Python You need to install the latest version of Python.\nnpm ERR! gyp ERR! find Python Node-gyp should be able to find and use Python. If not,\nnpm ERR! gyp ERR! find Python you can try one of the following options:\nnpm ERR! gyp ERR! find Python - Use the switch --python=\"/path/to/pythonexecutable\"\nnpm ERR! gyp ERR! find Python (accepted by both node-gyp and npm)\nnpm ERR! gyp ERR! find Python - Set the environment variable PYTHON\nnpm ERR! gyp ERR! find Python - Set the npm configuration variable python:\nnpm ERR! gyp ERR! find Python npm config set python \"/path/to/pythonexecutable\"\nnpm ERR! gyp ERR! find Python For more information consult the documentation at:\nnpm ERR! gyp ERR! find Python https://github.com/nodejs/node-gyp#installation\nnpm ERR! gyp ERR! find Python **********************************************************\nnpm ERR! gyp ERR! find Python\nnpm ERR! gyp ERR! configure error\nnpm ERR! gyp ERR! stack Error: Could not find any Python installation to use\nnpm ERR! gyp ERR! stack at PythonFinder.fail (/Users/kyeolhan/ForWork/BackOffceFront/node_modules/node-gyp/lib/find-python.js:302:47)\nnpm ERR! gyp ERR! stack at PythonFinder.runChecks (/Users/kyeolhan/ForWork/BackOffceFront/node_modules/node-gyp/lib/find-python.js:136:21)\nnpm ERR! gyp ERR! stack at PythonFinder. (/Users/kyeolhan/ForWork/BackOffceFront/node_modules/node-gyp/lib/find-python.js:179:16)\nnpm ERR! gyp ERR! stack at PythonFinder.execFileCallback (/Users/kyeolhan/ForWork/BackOffceFront/node_modules/node-gyp/lib/find-python.js:266:16)\nnpm ERR! gyp ERR! stack at exithandler (node:child_process:406:5)\nnpm ERR! gyp ERR! stack at ChildProcess.errorhandler (node:child_process:418:5)\nnpm ERR! gyp ERR! stack at ChildProcess.emit (node:events:526:28)\nnpm ERR! gyp ERR! stack at Process.ChildProcess._handle.onexit (node:internal/child_process:289:12)\nnpm ERR! gyp ERR! stack at onErrorNT (node:internal/child_process:478:16)\nnpm ERR! gyp ERR! stack at processTicksAndRejections (node:internal/process/task_queues:83:21)\nnpm ERR! gyp ERR! System Darwin 21.4.0\nnpm ERR! gyp ERR! command \"/Users/kyeolhan/.nvm/versions/node/v16.14.2/bin/node\" \"/Users/kyeolhan/ForWork/BackOffceFront/node_modules/.bin/node-gyp\" \"rebuild\"\nnpm ERR! gyp ERR! cwd /Users/kyeolhan/ForWork/BackOffceFront/node_modules/deasync\nnpm ERR! gyp ERR! node -v v16.14.2\nnpm ERR! gyp ERR! node-gyp -v v7.1.2\nnpm ERR! gyp ERR! not ok\nnpm ERR! Build failed\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /Users/kyeolhan/.npm/_logs/2022-03-28T12_56_28_864Z-debug-0.log\n```\n\npython3 is installed in my mac (Apple M1 Pro, macOS Monterey 12.3).\n\n```\n$ python3 --version\nPython 3.9.12\n```\n\nI also tried with --python option with paths below.\n\n```\n$ which -a python3\n/opt/homebrew/bin/python3\n/usr/bin/python3\n/opt/homebrew/bin/python3\n```\n\n```\nnpm i --python=\"/usr/bin/python3\"\nnpm i --python=\"/opt/homebrew/bin/python3\"\n```\n\nBut it doesn't work\n\n```\nnpm ERR! code 1\nnpm ERR! path /Users/kyeolhan/ForWork/BackOffceFront/node_modules/deasync\nnpm ERR! command failed\nnpm ERR! command sh -c node ./build.js\nnpm ERR! gyp info it worked if it ends with ok\nnpm ERR! gyp info using node-gyp@9.0.0\nnpm ERR! gyp info using node@16.14.2 | darwin | arm64\nnpm ERR! gyp ERR! find Python\nnpm ERR! gyp ERR! find Python checking Python explicitly set from command line or npm configuration\nnpm ERR! gyp ERR! find Python - \"--python=\" or \"npm config get python\" is \"/usr/bin/python3\"\nnpm ERR! gyp ERR! find Python - \"/usr/bin/python3\" is not in PATH or produced an error\nnpm ERR! gyp ERR! find Python Python is not set from environment variable PYTHON\nnpm ERR! gyp ERR! find Python checking if \"python3\" can be used\nnpm ERR! gyp ERR! find Python - \"python3\" is not in PATH or produced an error\nnpm ERR! gyp ERR! find Python checking if \"python\" can be used\nnpm ERR! gyp ERR! find Python - \"python\" is not in PATH or produced an error\nnpm ERR! gyp ERR! find Python\nnpm ERR! gyp ERR! find Python **********************************************************\nnpm ERR! gyp ERR! find Python You need to install the latest version of Python.\nnpm ERR! gyp ERR! find Python Node-gyp should be able to find and use Python. If not,\nnpm ERR! gyp ERR! find Python you can try one of the following options:\nnpm ERR! gyp ERR! find Python - Use the switch --python=\"/path/to/pythonexecutable\"\nnpm ERR! gyp ERR! find Python (accepted by both node-gyp and npm)\nnpm ERR! gyp ERR! find Python - Set the environment variable PYTHON\nnpm ERR! gyp ERR! find Python - Set the npm configuration variable python:\nnpm ERR! gyp ERR! find Python npm config set python \"/path/to/pythonexecutable\"\nnpm ERR! gyp ERR! find Python For more information consult the documentation at:\nnpm ERR! gyp ERR! find Python https://github.com/nodejs/node-gyp#installation\nnpm ERR! gyp ERR! find Python **********************************************************\nnpm ERR! gyp ERR! find Python\nnpm ERR! gyp ERR! configure error\nnpm ERR! gyp ERR! stack Error: Could not find any Python installation to use\nnpm ERR! gyp ERR! stack at PythonFinder.fail (/Users/kyeolhan/.nvm/versions/node/v16.14.2/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:330:47)\nnpm ERR! gyp ERR! stack at PythonFinder.runChecks (/Users/kyeolhan/.nvm/versions/node/v16.14.2/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:159:21)\nnpm ERR! gyp ERR! stack at PythonFinder. (/Users/kyeolhan/.nvm/versions/node/v16.14.2/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:202:16)\nnpm ERR! gyp ERR! stack at PythonFinder.execFileCallback (/Users/kyeolhan/.nvm/versions/node/v16.14.2/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:294:16)\nnpm ERR! gyp ERR! stack at exithandler (node:child_process:406:5)\nnpm ERR! gyp ERR! stack at ChildProcess.errorhandler (node:child_process:418:5)\nnpm ERR! gyp ERR! stack at ChildProcess.emit (node:events:526:28)\nnpm ERR! gyp ERR! stack at Process.ChildProcess._handle.onexit (node:internal/child_process:289:12)\nnpm ERR! gyp ERR! stack at onErrorNT (node:internal/child_process:478:16)\nnpm ERR! gyp ERR! stack at processTicksAndRejections (node:internal/process/task_queues:83:21)\nnpm ERR! gyp ERR! System Darwin 21.4.0\nnpm ERR! gyp ERR! command \"/Users/kyeolhan/.nvm/versions/node/v16.14.2/bin/node\" \"/Users/kyeolhan/.nvm/versions/node/v16.14.2/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js\" \"rebuild\"\nnpm ERR! gyp ERR! cwd /Users/kyeolhan/ForWork/BackOffceFront/node_modules/deasync\nnpm ERR! gyp ERR! node -v v16.14.2\nnpm ERR! gyp ERR! node-gyp -v v9.0.0\nnpm ERR! gyp ERR! not ok\nnpm ERR! Build failed\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /Users/kyeolhan/.npm/_logs/2022-03-28T13_05_45_769Z-debug-0.log\n```\n\nI think the 'deasync' package is requiring python since only projects containing that package in package-lock.json make this error.\n\nHow can I solve it?\n\n========================================\n\nTop Answer:\nYes downgrading to nodejs V 14.19.a worked for me as well.\nYou are probably try to run react app to test services like aws.\n\nif you dont downgrade it remove the node saas dependency as it is not compatible with new version of node js\nbut then if your code again give error if they require the package.\n\n========================================\n\nCode:\n```text\nnpm ERR! code 1\nnpm ERR! path /Users/kyeolhan/ForWork/BackOffceFront/node_modules/deasync\nnpm ERR! command failed\nnpm ERR! command sh -c node ./build.js\nnpm ERR! gyp info it worked if it ends with ok\nnpm ERR! gyp info using node-gyp@7.1.2\nnpm ERR! gyp info using node@16.14.2 | darwin | arm64\nnpm ERR! gyp ERR! find Python\nnpm ERR! gyp ERR! find Python Python is not set from command line or npm configuration\nnpm ERR! gyp ERR! find Python Python is not set from environment variable PYTHON\nnpm ERR! gyp ERR! find Python checking if \"python3\" can be used\nnpm ERR! gyp ERR! find Python - \"python3\" is not in PATH or produced an error\nnpm ERR! gyp ERR! find Python checking if \"python\" can be used\nnpm ERR! gyp ERR! find Python - \"python\" is not in PATH or produced an error\nnpm ERR! gyp ERR! find Python checking if \"python2\" can be used\nnpm ERR! gyp ERR! find Python - \"python2\" is not in PATH or produced an error\nnpm ERR! gyp ERR! find Python\nnpm ERR! gyp ERR! find Python **********************************************************\nnpm ERR! gyp ERR! find Python You need to install the latest version of Python.\nnpm ERR! gyp ERR! find Python Node-gyp should be able to find and use Python. If not,\nnpm ERR! gyp ERR! find Python you can try one of the following options:\nnpm ERR! gyp ERR! find Python - Use the switch --python=\"/path/to/pythonexecutable\"\nnpm ERR! gyp ERR! find Python (accepted by both node-gyp and npm)\nnpm ERR! gyp ERR! find Python - Set the environment variable PYTHON\nnpm ERR! gyp ERR! find Python - Set the npm configuration variable python:\nnpm ERR! gyp ERR! find Python npm config set python \"/path/to/pythonexecutable\"\nnpm ERR! gyp ERR! find Python For more information consult the documentation at:\nnpm ERR! gyp ERR! find Python https://github.com/nodejs/node-gyp#installation\nnpm ERR! gyp ERR! find Python **********************************************************\nnpm ERR! gyp ERR! find Python\nnpm ERR! gyp ERR! configure error\nnpm ERR! gyp ERR! stack Error: Could not find any Python installation to use\nnpm ERR! gyp ERR! stack at PythonFinder.fail (/Users/kyeolhan/ForWork/BackOffceFront/node_modules/node-gyp/lib/find-python.js:302:47)\nnpm ERR! gyp ERR! stack at PythonFinder.runChecks (/Users/kyeolhan/ForWork/BackOffceFront/node_modules/node-gyp/lib/find-python.js:136:21)\nnpm ERR! gyp ERR! stack at PythonFinder.<anonymous> (/Users/kyeolhan/ForWork/BackOffceFront/node_modules/node-gyp/lib/find-python.js:179:16)\nnpm ERR! gyp ERR! stack at PythonFinder.execFileCallback (/Users/kyeolhan/ForWork/BackOffceFront/node_modules/node-gyp/lib/find-python.js:266:16)\nnpm ERR! gyp ERR! stack at exithandler (node:child_process:406:5)\nnpm ERR! gyp ERR! stack at ChildProcess.errorhandler (node:child_process:418:5)\nnpm ERR! gyp ERR! stack at ChildProcess.emit (node:events:526:28)\nnpm ERR! gyp ERR! stack at Process.ChildProcess._handle.onexit (node:internal/child_process:289:12)\nnpm ERR! gyp ERR! stack at onErrorNT (node:internal/child_process:478:16)\nnpm ERR! gyp ERR! stack at processTicksAndRejections (node:internal/process/task_queues:83:21)\nnpm ERR! gyp ERR! System Darwin 21.4.0\nnpm ERR! gyp ERR! command \"/Users/kyeolhan/.nvm/versions/node/v16.14.2/bin/node\" \"/Users/kyeolhan/ForWork/BackOffceFront/node_modules/.bin/node-gyp\" \"rebuild\"\nnpm ERR! gyp ERR! cwd /Users/kyeolhan/ForWork/BackOffceFront/node_modules/deasync\nnpm ERR! gyp ERR! node -v v16.14.2\nnpm ERR! gyp ERR! node-gyp -v v7.1.2\nnpm ERR! gyp ERR! not ok\nnpm ERR! Build failed\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /Users/kyeolhan/.npm/_logs/2022-03-28T12_56_28_864Z-debug-0.log\n```\n\n```text\n$ python3 --version\nPython 3.9.12\n```\n\n```text\n$ which -a python3\n/opt/homebrew/bin/python3\n/usr/bin/python3\n/opt/homebrew/bin/python3\n```\n\n```text\nnpm i --python=\"/usr/bin/python3\"\nnpm i --python=\"/opt/homebrew/bin/python3\"\n```\n\n```text\nnpm ERR! code 1\nnpm ERR! path /Users/kyeolhan/ForWork/BackOffceFront/node_modules/deasync\nnpm ERR! command failed\nnpm ERR! command sh -c node ./build.js\nnpm ERR! gyp info it worked if it ends with ok\nnpm ERR! gyp info using node-gyp@9.0.0\nnpm ERR! gyp info using node@16.14.2 | darwin | arm64\nnpm ERR! gyp ERR! find Python\nnpm ERR! gyp ERR! find Python checking Python explicitly set from command line or npm configuration\nnpm ERR! gyp ERR! find Python - \"--python=\" or \"npm config get python\" is \"/usr/bin/python3\"\nnpm ERR! gyp ERR! find Python - \"/usr/bin/python3\" is not in PATH or produced an error\nnpm ERR! gyp ERR! find Python Python is not set from environment variable PYTHON\nnpm ERR! gyp ERR! find Python checking if \"python3\" can be used\nnpm ERR! gyp ERR! find Python - \"python3\" is not in PATH or produced an error\nnpm ERR! gyp ERR! find Python checking if \"python\" can be used\nnpm ERR! gyp ERR! find Python - \"python\" is not in PATH or produced an error\nnpm ERR! gyp ERR! find Python\nnpm ERR! gyp ERR! find Python **********************************************************\nnpm ERR! gyp ERR! find Python You need to install the latest version of Python.\nnpm ERR! gyp ERR! find Python Node-gyp should be able to find and use Python. If not,\nnpm ERR! gyp ERR! find Python you can try one of the following options:\nnpm ERR! gyp ERR! find Python - Use the switch --python=\"/path/to/pythonexecutable\"\nnpm ERR! gyp ERR! find Python (accepted by both node-gyp and npm)\nnpm ERR! gyp ERR! find Python - Set the environment variable PYTHON\nnpm ERR! gyp ERR! find Python - Set the npm configuration variable python:\nnpm ERR! gyp ERR! find Python npm config set python \"/path/to/pythonexecutable\"\nnpm ERR! gyp ERR! find Python For more information consult the documentation at:\nnpm ERR! gyp ERR! find Python https://github.com/nodejs/node-gyp#installation\nnpm ERR! gyp ERR! find Python **********************************************************\nnpm ERR! gyp ERR! find Python\nnpm ERR! gyp ERR! configure error\nnpm ERR! gyp ERR! stack Error: Could not find any Python installation to use\nnpm ERR! gyp ERR! stack at PythonFinder.fail (/Users/kyeolhan/.nvm/versions/node/v16.14.2/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:330:47)\nnpm ERR! gyp ERR! stack at PythonFinder.runChecks (/Users/kyeolhan/.nvm/versions/node/v16.14.2/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:159:21)\nnpm ERR! gyp ERR! stack at PythonFinder.<anonymous> (/Users/kyeolhan/.nvm/versions/node/v16.14.2/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:202:16)\nnpm ERR! gyp ERR! stack at PythonFinder.execFileCallback (/Users/kyeolhan/.nvm/versions/node/v16.14.2/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:294:16)\nnpm ERR! gyp ERR! stack at exithandler (node:child_process:406:5)\nnpm ERR! gyp ERR! stack at ChildProcess.errorhandler (node:child_process:418:5)\nnpm ERR! gyp ERR! stack at ChildProcess.emit (node:events:526:28)\nnpm ERR! gyp ERR! stack at Process.ChildProcess._handle.onexit (node:internal/child_process:289:12)\nnpm ERR! gyp ERR! stack at onErrorNT (node:internal/child_process:478:16)\nnpm ERR! gyp ERR! stack at processTicksAndRejections (node:internal/process/task_queues:83:21)\nnpm ERR! gyp ERR! System Darwin 21.4.0\nnpm ERR! gyp ERR! command \"/Users/kyeolhan/.nvm/versions/node/v16.14.2/bin/node\" \"/Users/kyeolhan/.nvm/versions/node/v16.14.2/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js\" \"rebuild\"\nnpm ERR! gyp ERR! cwd /Users/kyeolhan/ForWork/BackOffceFront/node_modules/deasync\nnpm ERR! gyp ERR! node -v v16.14.2\nnpm ERR! gyp ERR! node-gyp -v v9.0.0\nnpm ERR! gyp ERR! not ok\nnpm ERR! Build failed\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /Users/kyeolhan/.npm/_logs/2022-03-28T13_05_45_769Z-debug-0.log\n```\n\n```text\nnpm install\n```\n\n```text\nnpm update\n```\n\n```bash\napt install build-essential -y\napt install python3 -y\n```\n\n========================================\n\nComments:\n- Why would you need python for a node-based project? Do you have a github link?\n- @kissu No… because it’s code of my company. It’s private. But I heard that ‘node-gyp’ has python dependency.\n- This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review","metadata":{"transformedAt":"2026-08-18T18:33:07.855Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":302,"estimatedTokens":4227}}287{"id":"stack-65812581","source":"stackoverflow","questionId":65812581,"title":"Tailwind custom colors default not working","tags":["nuxt.js","tailwind-css"],"text":"Title: Tailwind custom colors default not working\nTags: nuxt.js, tailwind-css\nSource: Stack Overflow\n\nQuestion:\nI have clean nuxt.js project with Nuxt/Tailwind as styling.\n\nWith the configuration below i should be able to use these classes on a div or in postcss with @apply `text-testred` and `text-testred-dark`.\nHowever, only `text-testred-dark` works and not the default value with `text-testred`.\n\nAlso `text-testred-DEFAULT` works, so it's interpreting it wrong, since according to the docs it \"DEFAULT\" will be ignored and will be used as the default suffix of class.\n\n**nuxt.config.js**\n\n```\ntailwindcss: {\n configPath: '~/tailwind.config.js',\n cssPath: '~/assets/css/tailwind.css'\n}\n```\n\n**tailwind.config.js**\n\n```\nmodule.exports = {\n theme: {\n fontFamily:{\n sans: [\"'GT Walsheim Pro'\"],\n serif: [\"'GT Walsheim Pro'\"],\n mono: [\"'GT Walsheim Pro'\"],\n display: [\"'GT Walsheim Pro'\"],\n body: [\"'GT Walsheim Pro'\"]\n },\n colors: {\n // Configure your color palette here\n transparent: 'transparent',\n current: 'currentColor',\n testred: {\n lightest: '#efdfa4',\n lighter: '#f1cb8a',\n light: '#f5b575',\n DEFAULT: '#f89f68',\n dark: '#fb8762',\n darker: '#f86e61',\n darkest: '#f15764'\n },\n }\n}\n```\n\n**tailwind.css**\n\n```\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n@layer base {\n body{\n @apply text-testred; //doesn't work\n @apply text-testred-DEFAULT; //works\n }\n}\n```\n\n**EDIT**\n\nIn version 4.0.2 and above of @nuxtjs/tailwindcss this works as expected.\n\n========================================\n\nCode:\n```text\ntailwindcss: {\n configPath: '~/tailwind.config.js',\n cssPath: '~/assets/css/tailwind.css'\n}\n```\n\n```text\nmodule.exports = {\n theme: {\n fontFamily:{\n sans: [\"'GT Walsheim Pro'\"],\n serif: [\"'GT Walsheim Pro'\"],\n mono: [\"'GT Walsheim Pro'\"],\n display: [\"'GT Walsheim Pro'\"],\n body: [\"'GT Walsheim Pro'\"]\n },\n colors: {\n // Configure your color palette here\n transparent: 'transparent',\n current: 'currentColor',\n testred: {\n lightest: '#efdfa4',\n lighter: '#f1cb8a',\n light: '#f5b575',\n DEFAULT: '#f89f68',\n dark: '#fb8762',\n darker: '#f86e61',\n darkest: '#f15764'\n },\n }\n}\n```\n\n```text\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n@layer base {\n body{\n @apply text-testred; //doesn't work\n @apply text-testred-DEFAULT; //works\n }\n}\n```\n\n```text\ntext-testred\n```\n\n```text\ntext-testred-dark\n```\n\n```text\ntext-testred-dark\n```\n\n```text\ntext-testred\n```\n\n```text\ntext-testred-DEFAULT\n```\n\n```text\nyarn add --dev tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.855Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":142,"estimatedTokens":654}}288{"id":"stack-60434485","source":"stackoverflow","questionId":60434485,"title":"Nuxt auth with passportjs?","tags":["passport.js","nuxt.js","passport-local","passport-jwt"],"text":"Title: Nuxt auth with passportjs?\nTags: passport.js, nuxt.js, passport-local, passport-jwt\nSource: Stack Overflow\n\nQuestion:\nHow use nuxt auth Module (front-end) with passport-local using JWT (back-end express) ?\n\ndefining jwt strategy for verify jwt token (express)\n\n```\nvar JwtStrategy = require('passport-jwt').Strategy,\n ExtractJwt = require('passport-jwt').ExtractJwt;\n var opts = {}\n opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();\n opts.secretOrKey = 'secret';\n opts.issuer = 'accounts.examplesoft.com';\n opts.audience = 'yoursite.net';\n passport.use(new JwtStrategy(opts, function(jwt_payload, done) {\n User.findOne({id: jwt_payload.sub}, function(err, user) {\n if (err) {\n return done(err, false);\n }\n if (user) {\n return done(null, user);\n } else {\n return done(null, false);\n // or you could create a new account\n }\n });\n }));\n```\n\ndefining local strategy for verify username nad password (express)\n\n```\npassport.use(new LocalStrategy(\n function(username, password, done) {\n User.findOne({ username: username }, function (err, user) {\n if (err) { return done(err); }\n if (!user) { return done(null, false); }\n if (!user.verifyPassword(password)) { return done(null, false); }\n return done(null, user);\n });\n }\n ));\n```\n\ncode for issuing token after verifying username and password (expresss)\n\n```\napp.post('/login', \n passport.authenticate('local', { failureRedirect: '/login' }), //need to update from nuxt auth.\n function(req, res) {\n res.redirect('/');\n });\n```\n\nnuxt auth local strategy consume username and passsword returns a JWT token (nuxt)\n\n```\nthis.$auth.loginWith('local', {\n data: {\n username: 'your_username',\n password: 'your_password'\n }\n })\n```\n\nIt can work independently how do i combine these ?\n\n========================================\n\nCode:\n```js\nvar JwtStrategy = require('passport-jwt').Strategy,\n ExtractJwt = require('passport-jwt').ExtractJwt;\n var opts = {}\n opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();\n opts.secretOrKey = 'secret';\n opts.issuer = 'accounts.examplesoft.com';\n opts.audience = 'yoursite.net';\n passport.use(new JwtStrategy(opts, function(jwt_payload, done) {\n User.findOne({id: jwt_payload.sub}, function(err, user) {\n if (err) {\n return done(err, false);\n }\n if (user) {\n return done(null, user);\n } else {\n return done(null, false);\n // or you could create a new account\n }\n });\n }));\n```\n\n```js\npassport.use(new LocalStrategy(\n function(username, password, done) {\n User.findOne({ username: username }, function (err, user) {\n if (err) { return done(err); }\n if (!user) { return done(null, false); }\n if (!user.verifyPassword(password)) { return done(null, false); }\n return done(null, user);\n });\n }\n ));\n```\n\n```js\napp.post('/login', \n passport.authenticate('local', { failureRedirect: '/login' }), //need to update from nuxt auth.\n function(req, res) {\n res.redirect('/');\n });\n```\n\n```js\nthis.$auth.loginWith('local', {\n data: {\n username: 'your_username',\n password: 'your_password'\n }\n })\n```\n\n```text\nconst passport = require('passport');\nconst LocalStrategy = require('passport-local').Strategy;\nconst JwtStrategy = require('passport-jwt').Strategy;\n\npassport.use(\n new LocalStrategy(\n {\n usernameField: 'username',\n passwordField: 'password'\n },\n function(username, password, done) {\n users.findOne({ email: username }, function(err, user) {\n if (err) {\n return done(err);\n }\n if (!user) {\n return done(null, false, { error: 'Invalid username' });\n }\n if (!user.checkPassword(password)) {\n return done(null, false, { error: 'invalid password' });\n }\n\n const info = { scope: '*' };\n done(null, user, info);\n });\n }\n )\n);\n\n\nconst opts = {};\nopts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();\nopts.secretOrKey = 'JWT_SECRET_OR_KEY';\npassport.use(\n new JwtStrategy(opts, function(payload, done) {\n users.findById(payload, function(err, user) {\n if (err) {\n return done(err, false);\n }\n if (user) {\n return done(null, user);\n }\n return done(null, false);\n });\n })\n);\n```\n\n```text\nconst express = require('express');\nconst passport = require('passport');\nconst app = express();\napp.use(express.json());\napp.use(express.urlencoded({ extended: false }));\napp.use(cookieParser());\n\napp.use(passport.initialize()); // Used to initialize passport\n\n// Routes\n\napp.post(\n '/login',\n passport.authenticate('local', { session: false }),\n function(req, res) {\n const token = jwt.sign(req.user.userId, 'JWT_SECRET_OR_KEY');\n return res.json({ token });\n }\n );\napp.get(\n '/me',\n passport.authenticate(['jwt', 'bearer'], { session: false }),\n function(req, res, next) {\n const { userId } = req.user;\n users.findOne({ _id: userId }, (err, data) => {\n if (err) {\n res.status(500).send(err);\n } else if (data) {\n const userData = data;\n res.status(200).send(userData);\n } else {\n res.status(500).send('invalid token');\n }\n });\n}\n);\n```\n\n```text\nauth: {\n resetOnError: true,\n redirect: {\n login: '/login', // User will be redirected to this path if login is required.\n home: '/app/dashboard', // User will be redirect to this path after login. (rewriteRedirects will rewrite this path)\n logout: '/login', // User will be redirected to this path if after logout, current route is protected.\n user: '/user/profile',\n callback: '/callback // User will be redirect to this path by the identity provider after login. (Should match configured Allowed Callback URLs (or similar setting) in your app/client with the identity provider)\n },\n strategies: {\n local: {\n endpoints: {\n login: {\n url: '/login',\n method: 'post',\n propertyName: 'token'\n },\n logout: false,\n user: {\n url: '/me',\n method: 'GET',\n propertyName: false\n }\n },\n tokenRequired: true,\n tokenType: 'Bearer'\n }\n}\n```\n\n```text\nthis.$auth\n .loginWith('local', {\n data: {\n username: this.user.email,\n password: this.user.password\n }\n })\n .catch(err => {\n console.error(err );\n });\n```\n\n========================================\n\nComments:\n- upvoted! does this work if you are not using JWT, i mean if you use express-session?\n- yes @PirateApp you may need this","metadata":{"transformedAt":"2026-08-18T18:33:07.855Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":263,"estimatedTokens":1756}}289{"id":"stack-57626282","source":"stackoverflow","questionId":57626282,"title":"Using Bootstrap 4 with NuxtJS","tags":["vue.js","bootstrap-4","nuxt.js","bootstrap-vue"],"text":"Title: Using Bootstrap 4 with NuxtJS\nTags: vue.js, bootstrap-4, nuxt.js, bootstrap-vue\nSource: Stack Overflow\n\nQuestion:\nI'm trying to associate bootstrap 4 (bootstrap-vue) with Nuxt.\n\nI have difficulties using mixins and variables in pages or components, although I added style-resources-module.\n\nHere is an extract of `nuxt.config.js`:\n\n```\n/*\n** Global CSS\n*/\ncss: [\"~/scss/vars.scss\"],\n\n/*\n** Plugins to load before mounting the App\n*/\nplugins: [],\n/*\n\n/*\n** Nuxt.js modules\n*/\nmodules: [\n // Doc: https://bootstrap-vue.js.org/docs/\n \"bootstrap-vue/nuxt\",\n // Doc: https://github.com/nuxt-community/style-resources-module\n \"@nuxtjs/style-resources\"\n],\n\n/*\n** Disabling Bootstrap Compiled CSS\n*/\nbootstrapVue: {\n bootstrapCSS: false,\n bootstrapVueCSS: false\n},\n\n/*\n** Style resources\n*/\nstyleResources: {\n scss: [\n \"./scss/*.scss\",\n \"~bootstrap/scss/bootstrap.scss\",\n \"~bootstrap-vue/src/index.scss\"\n ]\n},\n```\n\n`./scss/vars.scss` sets variables, and also overrides Bootstrap's\n\n(e.g. `$orange: #DD7F58;`\n\nHere is an extract of one of the components:\n\n```\n\n .myClass{\n display: none;\n @include media-breakpoint-up(md) {\n display: block;\n }\n }\n\n```\n\nCompilation throws the following error: `_No mixin named media-breakpoint-up_`.\n\n========================================\n\nTop Answer:\nI use the following code inside `nuxt.config.js`:\n\n```\nmodules: [\n 'bootstrap-vue/nuxt',\n '@nuxtjs/style-resources',\n ],\n bootstrapVue: {\n bootstrapCSS: false,\n bootstrapVueCSS: false\n },\n styleResources: {\n scss: [\n 'bootstrap/scss/_functions.scss',\n 'bootstrap/scss/_variables.scss',\n 'bootstrap/scss/_mixins.scss',\n 'bootstrap-vue/src/_variables.scss',\n '~/assets/css/_variables.scss', // my custom variable overrides\n ],\n },\n```\n\n========================================\n\nCode:\n```js\n/*\n** Global CSS\n*/\ncss: [\"~/scss/vars.scss\"],\n\n/*\n** Plugins to load before mounting the App\n*/\nplugins: [],\n/*\n\n/*\n** Nuxt.js modules\n*/\nmodules: [\n // Doc: https://bootstrap-vue.js.org/docs/\n \"bootstrap-vue/nuxt\",\n // Doc: https://github.com/nuxt-community/style-resources-module\n \"@nuxtjs/style-resources\"\n],\n\n/*\n** Disabling Bootstrap Compiled CSS\n*/\nbootstrapVue: {\n bootstrapCSS: false,\n bootstrapVueCSS: false\n},\n\n/*\n** Style resources\n*/\nstyleResources: {\n scss: [\n \"./scss/*.scss\",\n \"~bootstrap/scss/bootstrap.scss\",\n \"~bootstrap-vue/src/index.scss\"\n ]\n},\n```\n\n```text\n<style lang=\"scss\" scoped>\n .myClass{\n display: none;\n @include media-breakpoint-up(md) {\n display: block;\n }\n }\n</style>\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n./scss/vars.scss\n```\n\n```text\n$orange: #DD7F58;\n```\n\n```text\n_No mixin named media-breakpoint-up_\n```\n\n```js\n/*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://bootstrap-vue.js.org/docs/\n \"bootstrap-vue/nuxt\",\n // Doc: https://github.com/nuxt-community/style-resources-module\n \"@nuxtjs/style-resources\"\n ],\n\n /*\n ** Disabling Bootstrap Compiled CSS\n */\n bootstrapVue: {\n bootstrapCSS: false,\n bootstrapVueCSS: false\n },\n\n /*\n ** Style resources\n */\n styleResources: {\n scss: \"./scss/*.scss\"\n },\n```\n\n```css\n// Variable overrides\n $orange: #DD7F58;\n\n// Bootstrap and BootstrapVue SCSS files\n @import '~bootstrap/scss/bootstrap.scss';\n @import '~bootstrap-vue/src/index.scss';\n\n// General style overrides and custom classes\n body {\n margin: 0;\n }\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n./scss/custom.scss\n```\n\n```js\nmodules: [\n 'bootstrap-vue/nuxt',\n '@nuxtjs/style-resources',\n ],\n bootstrapVue: {\n bootstrapCSS: false,\n bootstrapVueCSS: false\n },\n styleResources: {\n scss: [\n 'bootstrap/scss/_functions.scss',\n 'bootstrap/scss/_variables.scss',\n 'bootstrap/scss/_mixins.scss',\n 'bootstrap-vue/src/_variables.scss',\n '~/assets/css/_variables.scss', // my custom variable overrides\n ],\n },\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ncss: [\n '@/assets/scss/main.scss',\n ],\n styleResources: {\n scss: [\n '~/node_modules/bootstrap/scss/_functions.scss',\n '~/node_modules/bootstrap/scss/_variables.scss',\n '~/node_modules/bootstrap/scss/_mixins.scss',\n '~/node_modules/bootstrap/scss/_containers.scss',\n '~/node_modules/bootstrap/scss/_grid.scss'\n ]\n },\n modules: [\n '@nuxtjs/style-resources',\n ],\n```\n\n```text\n<style scoped lang=\"scss\">\n.header {\n @include make-container(); \n}\n</style>\n```\n\n========================================\n\nComments:\n- However, the doc of Style-Resources says not to import actual styles: \"Importing actual styles will include them in every component and will also make your build/HMR magnitudes slower. Do not do this!\" Therefore, I'm not sure to use the right approach there...\n- I'm having the same issue... in the docs it states clearly do not import actual styles... have you found any solution to properly import bootstrap to Nuxt?\n- @GuillermoLópez I didn't get any updates so far. So I kept that solution. Still I'd be interested to know if there's a better way...\n- I'm thinking of separating out the mixins and variables that i need in bootstrap and putting those in styleResources. Thinking that might be the right approach.\n- upvoted! how do I use this without bootstrap-vue i am using a theme that needs bootstrap only not bootstrap-vue, i want to customize the scss files of boostrap","metadata":{"transformedAt":"2026-08-18T18:33:07.855Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":276,"estimatedTokens":1350}}290{"id":"stack-59327247","source":"stackoverflow","questionId":59327247,"title":"CloudFront can't find page of Nuxt.js static site after reloading","tags":["amazon-cloudfront","nuxt.js","static-site"],"text":"Title: CloudFront can't find page of Nuxt.js static site after reloading\nTags: amazon-cloudfront, nuxt.js, static-site\nSource: Stack Overflow\n\nQuestion:\nI am new to deploying static sites. Searching for solution for about a while, I didn't find any useful information according to the problem I faced with.\n\n**Purpose**: I want to run my generated Nuxt.js static site on CloudFront.\n\n**Problem**: \n\nRan command `nuxt generate`\n\nGot static files of site e.g:\n\n```\n-| dist/\n----| about/\n------| index.html\n----| index.html\n```\n\nI configured properly CloudFront with all necessary options, loaded site to the S3 and connected it with CloudFront. It works fine in case I navigate the app without reloading the page and getting back to the previous page by browser facilities. Things go wrong when I try to request any path (apart from root '/', because CloudFront handles it correctly - image). Any time I try to request path for example `http://domainname.com/about/` (with '/' or not at the end) I get XML error code which means that site page was not found. \n\n```\n\n `NoSuchKey`\n The specified key does not exist.\n about\n request-id-hash\n \n host-id-hash\n \n\n```\n\nThis is due to the reason that CloudFront waits from the client to request full path to the file.\n\nFor example: `http://domainname.com/about/index.html` will return page as expected.\n\nAlso, I have tried to generate files with `subFolders: false` option to achieve this:\n\n```\n-| dist/\n----| about.html\n----| index.html\n```\n\nBut still went to the same problem: CloudFront wants *full path* to the requested file, so `http://domainname.com/about` won't return web page. It will send error code instead as previously.\n\nHow to make CloudFront understand that I want to get index.html file, when I request path to the folder where it is stored? Please, don't suggest Amazon Lambda or any other additional services to make it possible. It must be done just with CloudFront.\n\nCould anybody help me with it? What am I doing wrong? I will be glad to any tips and suggestions!\n\n========================================\n\nCode:\n```text\n-| dist/\n----| about/\n------| index.html\n----| index.html\n```\n\n```text\n<Error>\n <Code>NoSuchKey</Code>\n <Message>The specified key does not exist.</Message>\n <Key>about</Key>\n <RequestId>request-id-hash</RequestId>\n <HostId>\n host-id-hash\n </HostId>\n</Error>\n```\n\n```text\n-| dist/\n----| about.html\n----| index.html\n```\n\n```text\nnuxt generate\n```\n\n```text\nhttp://domainname.com/about/\n```\n\n```text\nhttp://domainname.com/about/index.html\n```\n\n```text\nsubFolders: false\n```\n\n```text\nhttp://domainname.com/about\n```\n\n========================================\n\nComments:\n- your server is online? nuxt generate will generate a static files for you, but you need run npm start to use your application. I don't think I understood your question very well.\n- @HenriqueVanKlaveren yes, it is online for sure. When I try to request any non root URLs manually, CloudFront can't look up into folder for index.html file. I have found exactly the same issue (but with not Nuxt) here. It is what I am trying to overcome. I will try proposed solution from the link above and I will give a response on it as soon as possible.\n- thanks for posting your solution. I previously only found some weird hack with lambda@edge and rewriting the URL which seemed overkill\n- this solved my issue too, it was the s3 website URL that worked. Thanks for posting.","metadata":{"transformedAt":"2026-08-18T18:33:07.855Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":109,"estimatedTokens":858}}291{"id":"stack-52230470","source":"stackoverflow","questionId":52230470,"title":"How to use webpack dev proxy with Nuxt","tags":["webpack","nuxt.js","nuxt-edge"],"text":"Title: How to use webpack dev proxy with Nuxt\nTags: webpack, nuxt.js, nuxt-edge\nSource: Stack Overflow\n\nQuestion:\nUsing Nuxt to develop a universal JS app, I'm attempting to configure webpack's dev proxy so that, *in development only*, requests to `/api` get proxied to `http://127.0.0.1:500/api` where they'll reach a Python REST API. Following the Nuxt docs, I've extended the webpack config in `nuxt.config.js` like so:\n\n```\nbuild: {\n extend (config, { isDev }) {\n // Proxy /api to Python only in dev\n if (isDev) {\n const devServer = {\n proxy: {\n '/api': 'http://127.0.0.1:5000'\n }\n }\n config.devServer = devServer;\n }\n }\n}\n```\n\nIf I log the config, I see that change being applied:\n\n```\n...\ndevServer: { proxy: { '/api': 'http://127.0.0.1:5000' } } }\n...\n```\n\nYet, when I visit http://127.0.0.1:8080/api/things, my Nuxt app is returned (it runs on port 8080 in dev), indicating that the webpack dev proxy is not catching the `/api` path and performing the proxying. Just to confirm that the proxy *destination* is working, if I visit http://127.0.0.1:5000/api/things, I get the expected API response. **Why, when I've extended the Nuxt webpack config to enable the webpack dev proxy, does the proxy not function?**\n\nI have, however, had success with the @nuxt/proxy module, but critically, I could not find a way to make it only affect development and not production. That portion of `nuxt.config.js` looked like this:\n\n```\naxios: {\n proxy: true\n},\nproxy: {\n '/api': 'http://127.0.0.1:5000'\n},\n```\n\nI'm happy to use the @nuxt/proxy module instead of (on top of?) the webpack dev proxy if it can be made to work in development only.\n\n========================================\n\nTop Answer:\nI needed to do this and was able to solve this using the following in nuxt.config.js\n\n```\nexport default {\n // other config ...\n\n ...process.env.NODE_ENV === 'development' && {\n proxy: {\n '/api': 'http://localhost:8000',\n }\n },\n}\n```\n\nThis code will only add the proxy key in the nuxt config if we're doing a development build.\n\nReference to the syntax used to insert the conditional object field (this was previously unknown to myself):\nhttps://stackoverflow.com/a/51200448\n\n========================================\n\nCode:\n```text\nbuild: {\n extend (config, { isDev }) {\n // Proxy /api to Python only in dev\n if (isDev) {\n const devServer = {\n proxy: {\n '/api': 'http://127.0.0.1:5000'\n }\n }\n config.devServer = devServer;\n }\n }\n}\n```\n\n```text\n...\ndevServer: { proxy: { '/api': 'http://127.0.0.1:5000' } } }\n...\n```\n\n```text\naxios: {\n proxy: true\n},\nproxy: {\n '/api': 'http://127.0.0.1:5000'\n},\n```\n\n```text\n/api\n```\n\n```text\nhttp://127.0.0.1:500/api\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n/api\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n/\n```\n\n```text\n/api\n```\n\n```text\nexport default {\n // other config ...\n\n ...process.env.NODE_ENV === 'development' && {\n proxy: {\n '/api': 'http://localhost:8000',\n }\n },\n}\n```\n\n========================================\n\nComments:\n- This answer on a similar question helped me stackoverflow.com/questions/67990952/…\n- But sometimes all requests are sent from the client, like submitting the form. Under such condition, proxy only in development is still necessary.","metadata":{"transformedAt":"2026-08-18T18:33:07.855Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":147,"estimatedTokens":816}}292{"id":"stack-58329587","source":"stackoverflow","questionId":58329587,"title":"How can I access the current fullPath inside of a axios plugin in Nuxt.js?","tags":["vue.js","vuejs2","axios","nuxt.js"],"text":"Title: How can I access the current fullPath inside of a axios plugin in Nuxt.js?\nTags: vue.js, vuejs2, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to get the current path through `route.fullPath` from within a Nuxt plugin for Axios. It is working to a degree, but it looks like because it is coming from the context, it is only ever setting the path when the page was initially loaded. How can I get the current `route.fullPath` (after any route changes) at the time of the Axios error to show?\n\n```\nexport default function ({ $axios, store, route, redirect }) {\n $axios.onError((error) => {\n if (error.response.status === 401) {\n store.commit('misc/setRedirect', route.fullPath);\n\n redirect('/sign-in');\n }\n });\n}\n```\n\n========================================\n\nCode:\n```js\nexport default function ({ $axios, store, route, redirect }) {\n $axios.onError((error) => {\n if (error.response.status === 401) {\n store.commit('misc/setRedirect', route.fullPath);\n\n redirect('/sign-in');\n }\n });\n}\n```\n\n```text\nroute.fullPath\n```\n\n```text\nroute.fullPath\n```\n\n```js\n// plugins/axios.js\nexport default function ({ $axios, app }) {\n $axios.onError(error => {\n console.log(error, app.router.currentRoute)\n })\n}\n```\n\n```text\napp.router.currentRoute\n```\n\n```text\napp\n```\n\n========================================\n\nComments:\n- Thank you for the workaround! I have created an issue with the nuxt-community/axios-module to determine if it is indeed a bug. github.com/nuxt-community/axios-module/issues/295","metadata":{"transformedAt":"2026-08-18T18:33:07.855Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":63,"estimatedTokens":382}}293{"id":"stack-56055584","source":"stackoverflow","questionId":56055584,"title":"Is it possible to make props conditional in Vue, e.g. prop2 depends on the value of prop1?","tags":["vue.js","eslint","nuxt.js"],"text":"Title: Is it possible to make props conditional in Vue, e.g. prop2 depends on the value of prop1?\nTags: vue.js, eslint, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a use case where I need to pass a specific error message to a custom component. If and only if a certain prop is set to `true`. But I doubt `this.required` is available within the props because it will not have been initialized.\n\n```\n//custom component\nprops: {\n required: {\n type: Boolean,\n default: false\n },\n requiredErrorMsg: {\n type: String,\n default: '',\n required: this.required\n }\n}\n```\n\nVue (or eslint?) should then throw a warning or error, if the prop is missing depending on whether `required` was set to true or not.\n\n```\n //missing prop error\n //no issues\n```\n\ncurrently using: \n\nnuxt v2.3.4\n\neslint v5.0.1\n\n========================================\n\nTop Answer:\nSure you can... VUE 3\n\n```\nprops: {\n prop1: {\n type: Boolean,\n default: false\n },\n prop2: {\n type: String,\n default: (propsListWithValues) => {\n if (propsListWithValues.prop1 == true) {\n return \"prop2 now have conditional text by prop1\"\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\n//custom component\nprops: {\n required: {\n type: Boolean,\n default: false\n },\n requiredErrorMsg: {\n type: String,\n default: '',\n required: this.required\n }\n}\n```\n\n```text\n<Custom :required=\"true\" /> //missing prop error\n<Custom :required=\"true\" required-error-msg=\"this is an error\"/> //no issues\n```\n\n```text\ntrue\n```\n\n```text\nthis.required\n```\n\n```text\nrequired\n```\n\n```js\nVue.component('custom-component', {\n template: `\n <div>\n required:<br>\n {{ required }}\n <br><br>\n requiredErrorMessage:<br>\n {{ requiredErrorMessage }}\n </div>\n `,\n props: {\n required: {\n type: Boolean,\n default: false\n },\n requiredErrorMessage: {\n type: String,\n default: '',\n required: true // <-- Explicitly set to true\n }\n }\n});\n\nnew Vue({\n el: '#app'\n});\n```\n\n```html\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"></script>\n\n<div id=\"app\">\n <custom-component\n :required=\"true\"\n />\n</div>\n```\n\n```js\nVue.component('custom-component', {\n template: `\n <div>\n required:<br>\n {{ required }}\n <br><br>\n requiredErrorMessage:<br>\n {{ errorMessage }}\n </div>\n `,\n props: {\n required: {\n type: Boolean,\n default: false\n },\n requiredErrorMessage: {\n type: String,\n default: '',\n }\n },\n computed: {\n errorMessage(){\n if (this.required === true && !this.requiredErrorMessage)\n // Explicitly call `throw` when required conditions are not met\n throw new Error('Missing prop error.');\n \n return this.requiredErrorMessage;\n }\n }\n});\n\nnew Vue({\n el: '#app'\n});\n```\n\n```html\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"></script>\n\n<div id=\"app\">\n <custom-component\n :required=\"true\"\n />\n</div>\n```\n\n```text\n[Vue warn]\n```\n\n```text\nthrow\n```\n\n```text\ncomputed\n```\n\n```text\nthrow\n```\n\n```text\nprops: {\n prop1: {\n type: Boolean,\n default: false\n },\n prop2: {\n type: String,\n default: (propsListWithValues) => {\n if (propsListWithValues.prop1 == true) {\n return \"prop2 now have conditional text by prop1\"\n }\n }\n }\n}\n```\n\n========================================\n\nComments:\n- did you try wrapping the required prop in a computed?\n- I think you shouldn't use **required** as a variable name - it's a reserved word (maybe not for a variable name, but it will get confusing in the end). Maybe **requiredMsg** would be OK.\n- the : in front of required makes it a boolean and not a string and the variable name has nothing to do with OP's question :)\n- Yes, the **bool** question is OK, but naming does have to do with the question. Try it with a snippet - with **required** it won't work at all, while with **requiredMsg** it will.\n- @JC97, using a computed doesn't work, the issue being using `this` inside the prop wont work because it will not have been initialized. **Cannot read property isRequired' of undefined** using a computed named `isRequired` and the prop = `required: this.isRequired`\n- @muka.gergely, like @JC97 has said, because of the `:` prefix of `required` it will not matter if the word is reserved or not. But just to provide you some proof, if you change the word `required` to `hihi` you will get: **Cannot read property 'hihi' of undefined**\n- I understand that there's a **v-bind:** shorthand before the property, but as it's a reserved word that spells trouble. And that's why I placed my suggestion in a **comment**, **not an answer** - it's not of outmost importance to the question.\n- This is not really conditional required though, it's default value based on the value of other props, but the prop itself is never \"required\"","metadata":{"transformedAt":"2026-08-18T18:33:07.855Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":222,"estimatedTokens":1227}}294{"id":"stack-58089746","source":"stackoverflow","questionId":58089746,"title":"Does nuxt need a server?","tags":["vue.js","single-page-application","nuxt.js","server-side-rendering"],"text":"Title: Does nuxt need a server?\nTags: vue.js, single-page-application, nuxt.js, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nI'm studying nuxt.\nI leave a question because I have a question while studying.\nnuxt can ssr, but ssr is known as server side rendering.\nThen, I wonder where the server is.\nBecause vue is built on node, is the server automatically made into node server?\nAnd, how is SEO possible if we make it with nuxt?\nI understand that it is possible if you make html with MPA. However, using nuxt makes SEO possible.\nSo, when you create a project with nuxt, does the client make it an MPA when it makes the first request?\n\n========================================\n\nComments:\n- Thank you for your answer! However, here is more question. If I want to use nuxt only as the front end and Python as the back end, does it need a total of three servers as the Web server, node server, and backend server?\n- depends... you can create a graphql or rest api with python and use vue apollo or axios to connect direct with frontend, nuxt wil be fine,\n- but if you need something more complex in serverside, processing things before and after the frontend was renderes well you need mix nuxt with other server framwork as express, koa or hapi","metadata":{"transformedAt":"2026-08-18T18:33:07.855Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":20,"estimatedTokens":313}}295{"id":"stack-78240834","source":"stackoverflow","questionId":78240834,"title":"Localization of numbers and dates is not working in Nuxt3 + VueI18n","tags":["vue.js","nuxt.js","vue-i18n"],"text":"Title: Localization of numbers and dates is not working in Nuxt3 + VueI18n\nTags: vue.js, nuxt.js, vue-i18n\nSource: Stack Overflow\n\nQuestion:\nI've tried to configure Nuxt 3 along with the VueI18n plugin as described here. It works fine for \"normal\" translations using `$t()` within the template or using `t()` in the script part. I load my files containing the translations lazy from a S3 bucket, each language its own file. Also the localization of URLs is working.\n\nOnly the localization of numbers (`$n()`) and dates (`$d()`) is not working. I followed this guide without success.\n\nHere is my Vue component:\n\n```\n\n \n \n\n### {{ $t('index.hello') }}\n\n \n Number {{ $n(5000, 'currency') }}\n \n\n \n {{ $d(new Date()) }}\n \n\n \n\n```\n\n`$n()` gives me a warning on the console: [intlify] Not found 'currency' key in 'de_DE' locale messages.\n\n`$d()` gives me a 500 error with this message: Incorrect locale information provided. Providing a locale as second parameter `$d(\"2023-05-06\", \"de_DE\")` gives me this error message: [intlify] Not found 'de_DE' key in 'de_DE' locale messages.)`\n\nPlease see my Nuxt configuration file below:\n\n```\nexport default defineNuxtConfig({\n pages: true\n app: {},\n modules: [\n 'nuxt-gtag',\n '@nuxtjs/i18n'\n ],\n i18n: {\n defaultLocale: 'de_DE',\n lazy: true,\n langDir: 'lang',\n locales: [{ code: 'de_DE', file: 'loadFromS3.ts', iso: 'de-DE', isCatchallLocale: true }],\n strategy: 'prefix_except_default',\n customRoutes: 'config',\n pages: {\n 'catalog/index': {\n de_DE: '/katalog'\n },\n 'index': {\n de_DE: '/'\n }\n }\n }\n})\n```\n\n========================================\n\nTop Answer:\nThanks a lot to JUBEI for his comment.\n\n```\n// package.json\n{ \n \"dependencies\": {\n \"@nuxtjs/i18n\": \"^10.2.0\",\n \"nuxt\": \"4.1.3\",\n \"vue\": \"^3.5.24\",\n }\n}\n```\n\n```\n// nuxt.config.ts\nexport default defineNuxtConfig({\n i18n: {\n langDir: \"locales\", // Or other\n locales: [\n { code: \"en\", language: \"en-US\", file: \"en.json\" },\n { code: \"fr\", language: \"fr-FR\", file: \"fr.json\" },\n ],\n defaultLocale: \"en\",\n strategy: \"no_prefix\", // Or other \n },\n}\n```\n\n```\n// i18n/i18n.config.ts\nimport { datetimeFormats } from \"./datetime-formats\";\n\nexport default defineI18nConfig(() => ({\n fallbackLocale: \"en\",\n datetimeFormats,\n}));\n```\n\n```\n// i18n/datetime-formats.ts\nexport const datetimeFormats = {\n fr: {\n short: {\n day: \"2-digit\",\n month: \"short\",\n year: \"numeric\",\n },\n },\n en: {\n short: {\n day: \"2-digit\",\n month: \"short\",\n year: \"numeric\",\n },\n },\n} as const;\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div class=\"container\">\n <h1>{{ $t('index.hello') }}</h1>\n <p>\n Number {{ $n(5000, 'currency') }}\n </p>\n\n <p>\n {{ $d(new Date()) }}\n </p>\n </div>\n</template>\n\n<script setup></script>\n```\n\n```text\nexport default defineNuxtConfig({\n pages: true\n app: {},\n modules: [\n 'nuxt-gtag',\n '@nuxtjs/i18n'\n ],\n i18n: {\n defaultLocale: 'de_DE',\n lazy: true,\n langDir: 'lang',\n locales: [{ code: 'de_DE', file: 'loadFromS3.ts', iso: 'de-DE', isCatchallLocale: true }],\n strategy: 'prefix_except_default',\n customRoutes: 'config',\n pages: {\n 'catalog/index': {\n de_DE: '/katalog'\n },\n 'index': {\n de_DE: '/'\n }\n }\n }\n})\n```\n\n```text\n$t()\n```\n\n```text\nt()\n```\n\n```text\n$n()\n```\n\n```text\n$d()\n```\n\n```text\n$n()\n```\n\n```text\n$d()\n```\n\n```text\n$d(\"2023-05-06\", \"de_DE\")\n```\n\n```text\nexport default defineNuxtConfig({\n modules: ['@nuxtjs/i18n'],\n i18n: {\n vueI18n: './i18n.config.ts'\n }\n})\n```\n\n```text\nexport default defineI18nConfig(() => ({\n defaultLocale: \"de_DE\",\n lazy: true,\n langDir: \"lang\",\n locales: [\n {\n code: \"de_DE\",\n file: \"loadFromS3.ts\",\n iso: \"de-DE\",\n isCatchallLocale: true,\n },\n ],\n strategy: \"prefix_except_default\",\n customRoutes: \"config\",\n pages: {\n \"catalog/index\": {\n de_DE: \"/katalog\",\n },\n index: {\n de_DE: \"/\",\n },\n },\n}));\n```\n\n```text\nexport default defineI18nConfig(() => ({\n defaultLocale: \"de_DE\",\n lazy: true,\n ...\n numberFormats: {\n 'de-DE': {\n currency: {\n style: 'currency', currency: 'EUR', notation: 'standard'\n },\n }\n },\n datetimeFormats: {\n 'de-DE': {\n short: {\n year: 'numeric', month: 'short', day: 'numeric'\n },\n long: {\n year: 'numeric', month: 'short', day: 'numeric',\n weekday: 'short', hour: 'numeric', minute: 'numeric'\n }\n },\n },\n}))\n```\n\n```text\nNuxt 3\n```\n\n```text\n@nuxtjs/i18n\n```\n\n```text\nnumberFormats\n```\n\n```text\ndatetimeFormats\n```\n\n```text\nvueI18n\n```\n\n```text\ni18n\n```\n\n```text\n./i18n.config.ts\n```\n\n```text\nnumberFormats\n```\n\n```text\ndatetimeFormats\n```\n\n```text\nVue I18n\n```\n\n```text\nVue I18n\n```\n\n```text\n@nuxtjs/i18n\n```\n\n```text\n// package.json\n{ \n \"dependencies\": {\n \"@nuxtjs/i18n\": \"^10.2.0\",\n \"nuxt\": \"4.1.3\",\n \"vue\": \"^3.5.24\",\n }\n}\n```\n\n```text\n// nuxt.config.ts\nexport default defineNuxtConfig({\n i18n: {\n langDir: \"locales\", // Or other\n locales: [\n { code: \"en\", language: \"en-US\", file: \"en.json\" },\n { code: \"fr\", language: \"fr-FR\", file: \"fr.json\" },\n ],\n defaultLocale: \"en\",\n strategy: \"no_prefix\", // Or other \n },\n}\n```\n\n```text\n// i18n/i18n.config.ts\nimport { datetimeFormats } from \"./datetime-formats\";\n\nexport default defineI18nConfig(() => ({\n fallbackLocale: \"en\",\n datetimeFormats,\n}));\n```\n\n```text\n// i18n/datetime-formats.ts\nexport const datetimeFormats = {\n fr: {\n short: {\n day: \"2-digit\",\n month: \"short\",\n year: \"numeric\",\n },\n },\n en: {\n short: {\n day: \"2-digit\",\n month: \"short\",\n year: \"numeric\",\n },\n },\n} as const;\n```\n\n========================================\n\nComments:\n- Thanks. Moving all Nuxt i18n configuration to i18n.config.ts did not work for me as Nuxt i18n and vueI18n configs are not fully compatible. Documentation suggests creating i18n/i18n.config.ts that will autoload vueI18n configuration. That worked. I'm now keeping numberFormats and datetimeFormats definitions in that file and rest of configuration stays in nuxt.config.ts under i18n key.","metadata":{"transformedAt":"2026-08-18T18:33:07.855Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":368,"estimatedTokens":1583}}296{"id":"stack-71951915","source":"stackoverflow","questionId":71951915,"title":"Nuxt3 - `_nuxt`-directory not found (404) on GitHub Pages","tags":["nuxt.js","github-actions","github-pages","nuxt3.js","mjs"],"text":"Title: Nuxt3 - `_nuxt`-directory not found (404) on GitHub Pages\nTags: nuxt.js, github-actions, github-pages, nuxt3.js, mjs\nSource: Stack Overflow\n\nQuestion:\n(I know it might sound similar to missing js files from _nuxt folder, but unfortunately, I was not able to understand the answer from there)\n\nWhen I deploy my `dist`-folder to GitHub Pages, it contains\n\n```\ndist \n| _nuxt\n | css/main.css\n | entry.*******.css\n | entry-*******.mjs\n | index-*******.mjs\n | history-********.mjs\n | header-********.mjs\n | ... some other mjs-files\n| css/main.css\n| index.html\n| history.html\n| ... some other HTML-files\n```\n\nThe HTML-pages are served, perfectly fine, and in the ``-section, they want to load the modules (`.mjs`-files). All of these requests, unfortunately, fail with a 404:\n\nhttps://i.sstatic.net/Zgh0m.png\nhttps://i.sstatic.net/gUiHm.png\n\nWhy do the requests to the `_nuxt`-folder fail, while `/` and `/css` requests go through?\n\nEdit: Just seen that in VS Code, this folder is just marked as a **symlink to the `.output/public`-folder** (generated by `nuxi generate`):\n\nhttps://i.sstatic.net/LZB3B.png.\n\nMight that be the issue? But appears that it contains the files, anyway:\n\nhttps://i.sstatic.net/YlF8Q.png\n\nEdit II:\nI cannot run `npm run start` for local tests (`node .output/server/index.mjs`), because the `.output/server` folder is empty, as can be seen on the image:\n\nhttps://i.sstatic.net/ib4J0.png\n\nWhen running the folder in Live Server (VS Code extension), the errors return:\n\nhttps://i.sstatic.net/P0mkS.png\n\nActually, after downloading the generated `.tar`-file (the artifact that is generated automatically by `GitHub Actions` for deployment) does not include the `_nuxt`-directory, but just the static HTML-files and `css`-directory as well as an `assets` dir with `assets/css/main.css`-file in it. Why is the `_nuxt`-directory ignored by the GitHub Action?\n\n========================================\n\nTop Answer:\nAdd `.nojekyll` empty file to the `public` folder and run `npm run generate`.\n\nAdd the below snippet to `defineNuxtConfig` config\n\n```\ntarget: 'static',\n router: {\n base: '/ repo name /', //eg:- /crstnmac.github.io/\n },\n```\n\nUse the below script to deploy your nuxt website to github pages\n\n`\"deploy\": \"push-dir --dir=dist --branch=gh-pages --cleanup\"`\n\n========================================\n\nCode:\n```text\ndist \n| _nuxt\n | css/main.css\n | entry.*******.css\n | entry-*******.mjs\n | index-*******.mjs\n | history-********.mjs\n | header-********.mjs\n | ... some other mjs-files\n| css/main.css\n| index.html\n| history.html\n| ... some other HTML-files\n```\n\n```text\ndist\n```\n\n```text\n<head>\n```\n\n```text\n.mjs\n```\n\n```text\n_nuxt\n```\n\n```text\n/\n```\n\n```text\n/css\n```\n\n```text\n.output/public\n```\n\n```text\nnuxi generate\n```\n\n```text\nnpm run start\n```\n\n```text\nnode .output/server/index.mjs\n```\n\n```text\n.output/server\n```\n\n```text\n.tar\n```\n\n```text\nGitHub Actions\n```\n\n```text\n_nuxt\n```\n\n```text\ncss\n```\n\n```text\nassets\n```\n\n```text\nassets/css/main.css\n```\n\n```text\n_nuxt\n```\n\n```text\n_nuxt\n```\n\n```text\n.nojekyll\n```\n\n```text\n.nojekyll\n```\n\n```text\ndist\n```\n\n```text\npublic\n```\n\n```text\ndist\n```\n\n```js\ntarget: 'static',\n router: {\n base: '/ repo name /', //eg:- /crstnmac.github.io/\n },\n```\n\n```text\n.nojekyll\n```\n\n```text\npublic\n```\n\n```text\nnpm run generate\n```\n\n```text\ndefineNuxtConfig\n```\n\n```text\n\"deploy\": \"push-dir --dir=dist --branch=gh-pages --cleanup\"\n```\n\n```text\n`\"deploy\": \"gh-pages -d dist -t true\"`\n```\n\n```text\n.nojekyll\n```\n\n```text\n-t true\n```\n\n```text\n_nuxt\n```\n\n```text\ngenerate\n```\n\n```text\n.nojekyll\n```\n\n```text\n.nojekyll\n```\n\n```text\npublic\n```\n\n```text\n_nuxt\n```\n\n```text\n-t true\n```\n\n```text\ngh-pages\n```\n\n```text\n.nojekyll\n```\n\n```text\ndist\n```\n\n========================================\n\nComments:\n- Does it work locally once built?\n- No, not through running `npm run start` (`node .output/server/index.mjs`), since the `.output/server`-folder is empty, only `output/public` folder has files in it, which are the same as in `dist` (=> symbolic link?), see Edit II\n- Please do not post link-only but actual text. Links can 404.","metadata":{"transformedAt":"2026-08-18T18:33:07.855Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":44,"totalLines":269,"estimatedTokens":1028}}297{"id":"stack-56985397","source":"stackoverflow","questionId":56985397,"title":"how to hook beforeRouteEnter in NuxtJs","tags":["vue.js","nuxt.js"],"text":"Title: how to hook beforeRouteEnter in NuxtJs\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to get the previous route for my nuxtjs app, so for i used `beforeRouteEnter`, but `beforeRouteEnter` is not firing.\n\n***i tried to add key in nuxt-link :*** *and still not working..*\n\n```\n\n```\n\n**so here is my code:**\n\n```\ncreated: function(){\n console.log(\"created\");\n },\n\n mounted: function(){\n console.log(\"mounted\");\n },\n\n mounted: function(){\n console.log(\"mounted\");\n },\n\n beforeRouteEnter(to, from, next) {\n\n console.log(\"before route called\");\n\n next(vm => {\n console.log(\"prev rout is: \"+vm.prevRoute);\n })\n\n }\n```\n\n**i expected :**\n\n```\nbefore route called\nprev rout is: /services\ncreated\nmounted\n```\n\n**but i only get :**\n\n```\ncreated\nmounted\n```\n\nIs there anything that i'm doing wrong?\n\n========================================\n\nCode:\n```text\n<nuxt-link :key=\"$route.path\" :to=\"'/services/'+service.id\">\n```\n\n```text\ncreated: function(){\n console.log(\"created\");\n },\n\n mounted: function(){\n console.log(\"mounted\");\n },\n\n mounted: function(){\n console.log(\"mounted\");\n },\n\n beforeRouteEnter(to, from, next) {\n\n console.log(\"before route called\");\n\n next(vm => {\n console.log(\"prev rout is: \"+vm.prevRoute);\n })\n\n }\n```\n\n```text\nbefore route called\nprev rout is: /services\ncreated\nmounted\n```\n\n```text\ncreated\nmounted\n```\n\n```text\nbeforeRouteEnter\n```\n\n```text\nbeforeRouteEnter\n```\n\n```text\n_slug.js:200 before route called\n_slug.js:192 created\n_slug.js:198 mounted\n_slug.js:205 prev rout is: undefined\n```\n\n```text\nbeforeRouteEnter(to, from, next) {\n console.log(\"before route called\");\n const previousRoute = from.path || from.fullPath\n console.log(`Previous Route ${previousRoute}`)\n}\n```\n\n```text\n_slug.js:200 before route called\n_slug.js:202 Previous Route /\n```\n\n========================================\n\nComments:\n- Are you only looking in the browser console? beforeRouteEnter is probably logging in the terminal.\n- @Andrew1325 yeah. i checked in both console and terminal. still not printing\n- This must only apply to previous versions, cos it worked just fine for me!\n- Yes, you have to use these hook in nuxt page component. Glad you solved!","metadata":{"transformedAt":"2026-08-18T18:33:07.855Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":135,"estimatedTokens":554}}298{"id":"stack-62523610","source":"stackoverflow","questionId":62523610,"title":"External Javascript files in nuxtjs","tags":["javascript","vue.js","nuxt.js"],"text":"Title: External Javascript files in nuxtjs\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am basing a website on an old tutorial, which uses 3 external js files. I am not able to recreate this using nuxtjs.\n\nFirst, I tried to include the js files before the tag.\n\n**nuxt.config.js**\n\n```\nhead: {\n script: [\n { src: 'js/imagesloaded.pkgd.min.js', type: 'text/javascript', body: true, defer: true },\n { src: 'js/TweenMax.min.js', type: 'text/javascript', body: true, defer: true },\n { src: 'js/demo.js', type: 'text/javascript', body: true, defer: true }\n ]\n },\n```\n\nThis works on initial page load. However, as soon as I change the page, the js files are ignored.\n\nAfter some research, I tried to include the files as a plugin, to avoid ssr.\n\n**nuxt.config.js**\n\n```\nplugins: [\n { src: \"plugins/imagesloaded.pkgd.min.js\", mode: 'client' },\n { src: \"plugins/TweenMax.min.js\", mode: 'client' },\n { src: \"plugins/demo.js\", mode: 'client' }\n ],\n```\n\nThis gave me multiple error messages (amongst other things: `'Cannot read property addEventListener of null`).\n\nThis is a very small project with a lot of time pressure, so any kind of help would be highly appreciated!\n\n**Update:**\n\nOriginal GitHub repository.\n\n========================================\n\nTop Answer:\nTo integrate bootstrap within antd-ui for my nuxt js project, this is what worked for me:\n\nin nuxt.config.js, add the following\n\nadd boostrap css files in css folder within assets folder:\n\ncss: [\n'ant-design-vue/dist/antd.css',\n'~/assets/css/bootstrap.min.css',\n'~/assets/css/bootstrap-grid.min.css',\n'~/assets/css/bootstrap-utilities.min.css'\n],\n\nadd boostrap js files in js folder within static folder:\n\nplugins: [\n'@/plugins/antd-ui',\n{src: '~/static/js/bootstrap.bundle.min.js', mode:'client'},\n],\n\nThis worked for me\n\n========================================\n\nCode:\n```text\nhead: {\n script: [\n { src: 'js/imagesloaded.pkgd.min.js', type: 'text/javascript', body: true, defer: true },\n { src: 'js/TweenMax.min.js', type: 'text/javascript', body: true, defer: true },\n { src: 'js/demo.js', type: 'text/javascript', body: true, defer: true }\n ]\n },\n```\n\n```text\nplugins: [\n { src: \"plugins/imagesloaded.pkgd.min.js\", mode: 'client' },\n { src: \"plugins/TweenMax.min.js\", mode: 'client' },\n { src: \"plugins/demo.js\", mode: 'client' }\n ],\n```\n\n```text\n'Cannot read property addEventListener of null\n```\n\n```text\nlink: [\n { rel: 'stylesheet', type: 'text/css', href: 'css/base.css' }\n ],\n script: [\n { src: 'js/imagesloaded.pkgd.min.js', type: 'text/javascript', body: true, defer: true },\n { src: 'js/TweenMax.min.js', type: 'text/javascript', body: true, defer: true },\n { src: 'js/demo.js', type: 'text/javascript', body: true, defer: true }\n ]\n```\n\n```text\n<div class=\"background\" style=\"background-image: url(img/1.jpg)\"></div>\n```\n\n```text\nbase.css\n```\n\n```text\njs\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nbase.css\n```\n\n```text\nbase.css\n```\n\n```text\nurl('../img/1.jpg')\n```\n\n```text\nHTML\n```\n\n========================================\n\nComments:\n- Thank you for your response! It looks better than before. However, I am still getting some error messages, like TypeError: Cannot read property 'addEventListener' of null, or TypeError: Cannot read property 'addEventListener' of null. Which makes me suspicious about this being loaded on the client...\n- Can you try importing it one by one like that and see if there is a particular file that causes this issue, please (possibly `demo.js`)?\n- Yes, it is the demo.js file. Everything else works perfectly with your method.\n- That is very helpful. Thank you! I added the entire content of the file to my question.\n- I managed to make it fully functional with Nuxt.js (Vue.js & Node.js). Please have a look at the edited answer. Thanks.\n- Unfortunately that doesn't help. It is exactly what I already described in my question. As described there: 'This works on initial page load. However, as soon as I change the page, the js files are ignored.' Probably somebody else can profit from this, so I will accept it anyway. Thank you so much for all your effort!\n- The original repo was created for a single page scenario so there is a problem with these `js` files as they will be most likely referring to the specific elements that might not exist on other pages. It could mean that `js` files would also have to be edited if you wanted to re-use the functionality across the application and not just that specific page.","metadata":{"transformedAt":"2026-08-18T18:33:07.856Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":146,"estimatedTokens":1128}}299{"id":"stack-52369563","source":"stackoverflow","questionId":52369563,"title":"How to define a Nuxt link in a Vuetify button when portion of the path belongs to $route.params?","tags":["javascript","vuejs2","vuetify.js","nuxt.js"],"text":"Title: How to define a Nuxt link in a Vuetify button when portion of the path belongs to $route.params?\nTags: javascript, vuejs2, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn Nuxt and Vuetify application, I have a series of buttons:\n\n```\n\n favorite\n studentName\n\n```\n\nI want to refactor this code knowing that I get className from the route: `$route.params.className` And I get studentName from a normal JavaScript array.\n\nWhen I type href={{$route.params.className}}/studentName I get an error:\n\nUse v-bind or the colon shorthand instead. For example, instead of\n\n, use .\n\nAnd when I do it that way:\n\n```\n:href=\"$route.params.className/studentName\"\n```\n\nI get this error instead:\n\nInvalid prop: type check failed for prop \"href\". Expected String,\nObject, got Number.\n\nSo how to define correctly my `href` prop without hard writing `className` (I mean I want to use `$route.params.className` in order to refactor my code which has several buttons?\n\n========================================\n\nTop Answer:\nYou should use `to=\"studentName\" nuxt`\n\nFor example:\n\n```\n\n Home \n Contact \n Login \n \n```\n\n========================================\n\nCode:\n```js\n<v-btn dark color=\"orange\" href=\"className/studentName\" nuxt>\n <v-icon large left>favorite</v-icon>\n studentName\n</v-btn>\n```\n\n```text\n:href=\"$route.params.className/studentName\"\n```\n\n```text\n$route.params.className\n```\n\n```text\nhref\n```\n\n```text\nclassName\n```\n\n```text\n$route.params.className\n```\n\n```text\n:href=\"$route.params.className + '/studentName'\"\n```\n\n```text\n/studentName\n```\n\n```text\nv-bind:href=className+\"/\"+studentName\n```\n\n```text\n<v-toolbar-items class=\"hidden-sm-and\">\n <v-btn flat to=\"/home\" nuxt> Home </v-btn>\n <v-btn flat to=\"/contact\" nuxt> Contact </v-btn>\n <v-btn flat to=\"/login\" nuxt> Login </v-btn>\n </v-toolbar-items>\n```\n\n```text\nto=\"studentName\" nuxt\n```\n\n========================================\n\nComments:\n- Please elaborate\n- vuetifyjs.com/en/components/buttons It shows to use `nuxt` as stated\n- Docs: vuetifyjs.com/en/api/v-btn/#props (search `nuxt`)","metadata":{"transformedAt":"2026-08-18T18:33:07.856Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":110,"estimatedTokens":514}}300{"id":"stack-50973576","source":"stackoverflow","questionId":50973576,"title":"nuxtjs spa dynamic routes generate 404 after prod deployment","tags":["dynamic","vue.js","routes","nuxt.js"],"text":"Title: nuxtjs spa dynamic routes generate 404 after prod deployment\nTags: dynamic, vue.js, routes, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using nuxtjs\n\n- v.1.4.0\n\n- spa mode set in nuxt.config.js\n\n- with dynamic routing\n\nWhen running in dev mode all urls work corretly, after `npm run build` and deployment to a weblogic server I can only access the webroot directly. \nFrom there the navigation to the dynamic routes work by clicking around.\nHowever, when I type in a URL (other than the webroot) that should translate to a dynamic route, I get a 404 (but this works in dev mode).\n\n========================================\n\nTop Answer:\nYou need to add `fallback: true` to nuxt config generate parameter (docs). This redirects missing pages to `404.html` which then loads the `index.html`\n\n```\n// nuxt.config.js\nexport default {\n generate: {\n fallback: true\n }\n}\n```\n\n========================================\n\nCode:\n```text\nnpm run build\n```\n\n```text\nparams\n```\n\n```text\nquery\n```\n\n```text\n/product/_id.vue\n```\n\n```text\n/product.vue\n```\n\n```text\nparams: {id: product_id}\n```\n\n```text\nquery: {id: product_id}\n```\n\n```text\nn-link\n```\n\n```text\n:to=\"'/product/' + product_id\"\n```\n\n```text\n:to=\"'/product?id=' + product_id\"\n```\n\n```text\nhash\n```\n\n```js\n// nuxt.config.js\nexport default {\n generate: {\n fallback: true\n }\n}\n```\n\n```text\nfallback: true\n```\n\n```text\n404.html\n```\n\n```text\nindex.html\n```\n\n```text\nexport default defineNuxtConfig({\n ssr: true,\n routeRules: {\n '/vLoginRedirect': {ssr: false},\n '/vlogout': {ssr: false},\n '/**': {ssr: true},\n '/tasks/**': { ssr: true },\n '/tasksearch/**': { ssr: true },\n '/pages/tasks/**': { ssr: true },\n '/pages/tasksearch/**': { ssr: true },\n },\n```\n\n========================================\n\nComments:\n- The answer given below is correct, please accept it.\n- yeah, i checked that before, but i do not do generate, i performed npm run build. as shown in the SPA section of nuxtjs.org/guide/commands\n- That's doesn't change a fact. You needed generate routes if you don't use SSR\n- Are dynamic nested routes and SPA concepts mutually exclusive? (stackoverflow.com/questions/52820584/…)\n- @BillalBegueradj no, it isnt. You just need to route all your request to index.html in spa mode.\n- Yes, I just confirmed that both in theory and using code. Thank you","metadata":{"transformedAt":"2026-08-18T18:33:07.856Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":122,"estimatedTokens":585}}301{"id":"stack-53610949","source":"stackoverflow","questionId":53610949,"title":"Using cypress with vuetify","tags":["vue.js","nuxt.js","cypress","vuetify.js","e2e-testing"],"text":"Title: Using cypress with vuetify\nTags: vue.js, nuxt.js, cypress, vuetify.js, e2e-testing\nSource: Stack Overflow\n\nQuestion:\nI have a Vue.js project (Nuxt.js) and as UI I use the Vuetify. \nFor e2e testing I use the Cypress. \n\nBelow is my scenarios of test in Cypress:\n\nI have a problem while creating test for page where I use v-autocomplete component. \nThe problem is that I can't use Vuetify native classes to get the element I want to test.\nbelow is an example with data-cy selector\n\n```\n\n```\n\nI type some text into search input. \nThen in v-autocomplete have been found search results. \nAnd example of one of there is below: \n\n```\n...\n \n \n \n Result item\n result item\n \n \n \n \n...\n```\n\nThen I want select one of search items by clicking to one of found results.\nAnd for that I should to use native classes of Vuetify, but it is not have stability (`.v-list__tile--link` class сan be renamed by developers).\nHow I can add data-cy selector into result search html item? \nMaybe who know any another way to resolve this problem?\n\n========================================\n\nCode:\n```text\n<v-autocomplete\n v-model=\"model\"\n :items=\"items\"\n item-text=\"Description\"\n item-value=\"API\"\n label=\"Public APIs\"\n placeholder=\"Start typing to Search\"\n data-cy=\"autocomplete\"\n ></v-autocomplete>\n```\n\n```text\n...\n <div>\n <a class=\"v-list__tile v-list__tile--link theme--light\">\n <div class=\"v-list__tile__content\">\n <div class=\"v-list__tile__title\">Result item\n <span class=\"v-list__tile__mask\">result item</span>\n </div>\n </div>\n </a>\n </div>\n...\n```\n\n```text\n.v-list__tile--link\n```\n\n```js\ncy.contains('div', 'itemTextToSelect').parent('a').click()\n```\n\n```text\nv-list__tile--link\n```\n\n```text\ndisplay: none\n```\n\n```text\n.type('something')\n```\n\n```text\n.click({force: true})\n```\n\n========================================\n\nComments:\n- thank you! it works well. `cy.get(inputSelector).type(searchQuery); cy.contains('a', searchQuery).click()`\n- Oh yeah, much simpler.","metadata":{"transformedAt":"2026-08-18T18:33:07.856Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":99,"estimatedTokens":512}}302{"id":"stack-64951696","source":"stackoverflow","questionId":64951696,"title":"How to use Vue I18n translation in component attribute/property","tags":["vue.js","nuxt.js","vue-i18n"],"text":"Title: How to use Vue I18n translation in component attribute/property\nTags: vue.js, nuxt.js, vue-i18n\nSource: Stack Overflow\n\nQuestion:\nHow do I translate the passed-in attribute/property of a component? For instance, I have a card component with a title and description prop defined like this.\n\n\r\n\r\n\n```\n\n \n \n \n\n### {{title}}\n\n {{description}}\n \n \n\n \n export default {\n props: {\n title: String,\n descritpion: String\n }\n }\n \n```\n\n\r\n\r\n\r\n\nThen using the my-card component in another page/component like this\n\n\r\n\r\n\n```\n\n \n\n Page header\n \n Page footer\n \n \n```\n\n\r\n\r\n\r\n\nHow do I us vue I18n to translate the component props?\n\n\r\n\r\n\n```\n\n \n\n Page header\n \n Page footer\n \n \n```\n\n\r\n\r\n\r\n\nI can't seem to get the translation to work with passed-in props.\n\nPS: I know I could add the translation in the place I defined my-card component but the issue here is that the components are third-party components from NPM library.\n\nI know some packages in React.js has this feature.\n\n========================================\n\nTop Answer:\nYou can use I18n translation in component props like this.\n\n```\n\n```\n\n========================================\n\nCode:\n```html\n<!-- my-card component -->\n <template>\n <div>\n <h2>{{title}}</h2>\n <span>{{description}}</span>\n </div>\n </template>\n\n <script>\n export default {\n props: {\n title: String,\n descritpion: String\n }\n }\n </script>\n```\n\n```html\n<template>\n <div>\n\n <header>Page header</header>\n <my-card :title=\"the best card title\" :description=\"the best description\" />\n <footer>Page footer</footer>\n </div>\n </template>\n```\n\n```html\n<template>\n <div>\n\n <header>Page header</header>\n <my-card :title=\"{{ $t('myCard.title')}}\" :description=\"{{$t('myCard.description')}}\" />\n <footer>Page footer</footer>\n </div>\n </template>\n```\n\n```text\n<my-card :title=\"$t('myCard.title')\" :description=\"$t('myCard.description')\" />\n```\n\n```text\n{{}}\n```\n\n```text\n<my-card \n:title=\"$t('myCard.title')\"\n:description=\"$t('myCard.description')\" \n/>\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.856Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":149,"estimatedTokens":527}}303{"id":"stack-67081708","source":"stackoverflow","questionId":67081708,"title":"Custom styling for Sweet alert 2","tags":["javascript","css","vue.js","sweetalert2","nuxt.js"],"text":"Title: Custom styling for Sweet alert 2\nTags: javascript, css, vue.js, sweetalert2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI define a className to customize a sweetAlert2 but apparently the styling wont apply to the sweet alert. I called the class name everything but nothing seems to work. could the problem be with main css file for this package ?\n\n```\nswal.fire({\n title: Welcome,\n className: styleTitle\n});\n```\n\nThe CSS\n\n```\n.styleTitle{\n font-size: 25px;\n}\n```\n\n========================================\n\nTop Answer:\n```\n.confirm-button-class {\n background-color: red !important;\n color: white !important;\n border: none !important;\n}\n\n.title-class {\n font-size: 15px !important;\n}\n\n.icon-class {\n font-size: 10px !important;\n}\n\n.confirm-button-class .swal2-icon svg {\n width: 12px !important;\n height: 12px !important;\n}\n\n.swal2-actions .swal2-confirm {\n background-color: #f1c40f !important;\n color: white !important;\n border: none !important;\n box-shadow: none !important;\n}\n\n.swal2-actions .swal2-cancel {\n border-color: #f1c40f !important;\n box-shadow: none !important;\n border: none !important;\n}\n\n.swal2-confirm:focus, .swal2-cancel:focus {\n box-shadow: none !important;\n border: none !important;\n}\n\n.swal2-actions button:hover {\n border: none !important;\n}\n```\n\nbelow is the customized sweetalert2\n\n```\nSwal.fire({\n icon: 'warning',\n title: 'Are you sure?',\n text: 'This action cannot be undone.',\n showCancelButton: true,\n confirmButtonText: 'Yes, delete it!',\n cancelButtonText: 'No, cancel!',\n customClass: {\n confirmButton: 'confirm-button-class',\n title: 'title-class',\n icon: 'icon-class'\n },\n html: `\n \n ${allItems.map((item) => `\n \n \n Name: ${item.name}\n\n Address: ${item.address}\n\n \n \n \n `).join('')}\n \n `,\n }).then((result) => {\n if (result.isConfirmed) {\n Swal.fire('Deleted!', 'Your item has been deleted.', 'success');\n } else if (result.isDismissed) {\n Swal.fire('Cancelled', 'Your item is safe :)', 'error');\n }\n });\n```\n\nHope this will help you.\n\n========================================\n\nCode:\n```text\nswal.fire({\n title: Welcome,\n className: styleTitle\n});\n```\n\n```text\n.styleTitle{\n font-size: 25px;\n}\n```\n\n```text\ncustomClass\n```\n\n```text\nclassName\n```\n\n```text\n.confirm-button-class {\n background-color: red !important;\n color: white !important;\n border: none !important;\n}\n\n.title-class {\n font-size: 15px !important;\n}\n\n\n.icon-class {\n font-size: 10px !important;\n}\n\n.confirm-button-class .swal2-icon svg {\n width: 12px !important;\n height: 12px !important;\n}\n\n.swal2-actions .swal2-confirm {\n background-color: #f1c40f !important;\n color: white !important;\n border: none !important;\n box-shadow: none !important;\n}\n\n.swal2-actions .swal2-cancel {\n border-color: #f1c40f !important;\n box-shadow: none !important;\n border: none !important;\n}\n\n.swal2-confirm:focus, .swal2-cancel:focus {\n box-shadow: none !important;\n border: none !important;\n}\n\n.swal2-actions button:hover {\n border: none !important;\n}\n```\n\n```text\nSwal.fire({\n icon: 'warning',\n title: 'Are you sure?',\n text: 'This action cannot be undone.',\n showCancelButton: true,\n confirmButtonText: 'Yes, delete it!',\n cancelButtonText: 'No, cancel!',\n customClass: {\n confirmButton: 'confirm-button-class',\n title: 'title-class',\n icon: 'icon-class'\n },\n html: `\n <div style=\"max-height: 300px; overflow-y: scroll;\">\n ${allItems.map((item) => `\n <div key=\"${item.asset_number}\">\n <div>\n <p>Name: ${item.name}</p>\n <p>Address: ${item.address}</p>\n </div>\n <hr style=\"border-color: gray; border-width: 1px; margin: 10px 0;\" />\n </div>\n `).join('')}\n </div>\n `,\n }).then((result) => {\n if (result.isConfirmed) {\n Swal.fire('Deleted!', 'Your item has been deleted.', 'success');\n } else if (result.isDismissed) {\n Swal.fire('Cancelled', 'Your item is safe :)', 'error');\n }\n });\n```\n\n========================================\n\nComments:\n- Oh forgot to paste that my bad that's not the issue thou\n- Oh, and how do you import the css?\n- its vue im using so import css on the same page/ file\n- yh i think that should help thanks the official docs told me i could use class Name","metadata":{"transformedAt":"2026-08-18T18:33:07.856Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":219,"estimatedTokens":1079}}304{"id":"stack-65077883","source":"stackoverflow","questionId":65077883,"title":"Nuxt.js: can't generate routes","tags":["vue.js","routes","nuxt.js"],"text":"Title: Nuxt.js: can't generate routes\nTags: vue.js, routes, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to generate both static routes (`/contact`, `/about`, ...) and dynamic routes (`/project/1`, `/project/2,` ...) for my project, so that when user refreshes the page while visiting any of these routes, the page still works.\n\nBut when doing `npm run generate` I only get `Generated route \"/\"` and in `/dist` folder I see no routes generated.\n\nNuxt.js version used: `2.14.7`\n\nI tried with both `universal` and `spa` modes, it works with neither.\n\nIn nuxt.config.js I have at the top:\n\n```\nconst axios = require('axios')\n\nconst dynamicRoutes = async () => {\n const routes = await axios.get('http://my-project.com/wp/wp-json/projects/v1/posts')\n .then(res => res.data.map((project) => `/project/${project.ID}/${project.post_name}`))\n .then(res => res.concat(\n [\n '/about',\n '/contact',\n '/portfolio'\n ]\n ))\n return routes\n}\n```\n\nThen in `export default {}`:\n\n```\ngenerate: {\n routes: dynamicRoutes\n},\n```\n\n========================================\n\nTop Answer:\nFirst of all you don't have to add `mode: 'universal'` in config. Add `target: 'static'` to simplify it. Read more - https://nuxtjs.org/docs/2.x/features/deployment-targets/. With `ssr: true` you will get full static mode website with relevant hooks as mentioned in https://stackoverflow.com/a/65208463/8153537.\n\nNext, you can remove @nuxt/router module. Check my gist - https://gist.github.com/MexsonFernandes/d04495c86b115bbe29f26b36b0b35d2d. Nuxt would generate all the required routes as per the folder structure. So there is no need for extra config.\n\nCheck this gist for project page route - https://gist.github.com/MexsonFernandes/d04495c86b115bbe29f26b36b0b35d2d#gistcomment-3555332.\n\n========================================\n\nCode:\n```js\nconst axios = require('axios')\n\nconst dynamicRoutes = async () => {\n const routes = await axios.get('http://my-project.com/wp/wp-json/projects/v1/posts')\n .then(res => res.data.map((project) => `/project/${project.ID}/${project.post_name}`))\n .then(res => res.concat(\n [\n '/about',\n '/contact',\n '/portfolio'\n ]\n ))\n return routes\n}\n```\n\n```js\ngenerate: {\n routes: dynamicRoutes\n},\n```\n\n```text\n/contact\n```\n\n```text\n/about\n```\n\n```text\n/project/1\n```\n\n```text\n/project/2,\n```\n\n```text\nnpm run generate\n```\n\n```text\nGenerated route \"/\"\n```\n\n```text\n/dist\n```\n\n```text\n2.14.7\n```\n\n```text\nuniversal\n```\n\n```text\nspa\n```\n\n```text\nexport default {}\n```\n\n```text\nrouter.mode='hash'\n```\n\n```text\ngenerate.routes\n```\n\n```text\nrouter.mode\n```\n\n```text\nhash\n```\n\n```text\ngenerate.routes\n```\n\n```text\n/\n```\n\n```text\nhash\n```\n\n```text\nindex.html\n```\n\n```text\nrouter.js\n```\n\n```text\nrouter.js\n```\n\n```text\ngenerate.routes\n```\n\n```text\nmode='universal'\n```\n\n```text\nssr=true\n```\n\n```text\nssr=false\n```\n\n```text\nssr=true\n```\n\n```text\nasyncData()\n```\n\n```text\nfetch()\n```\n\n```text\n/about\n```\n\n```text\n/contact\n```\n\n```text\n/portfolio\n```\n\n```text\ndynamicRoutes()\n```\n\n```text\ngenerate: {\n async routes(){\n const routes = await axios.get('http://my-project.com/wp/wp-json/projects/v1/posts')\n .then(res => res.data.map((project) => `/project/${project.ID}/${project.post_name}`))\n return [...routes,\n [\n '/about',\n '/contact',\n '/portfolio'\n ]\n ]\n }\n}\n```\n\n```text\nmode: 'universal'\n```\n\n```text\ntarget: 'static'\n```\n\n```text\nssr: true\n```\n\n========================================\n\nComments:\n- I cloned the project on my own machine and it generate the routes in the dist folder\n- @BoussadjraBrahim any idea why Nuxt fails to generate any route on my machine when running `npm run generate`?\n- could you show a screenshot after running the command?\n- i use such issue to generate sitemap on nuxt.js in nuxt.config.js add to module '@nuxtjs/sitemap' and then add sitemap sitemap: { routes () { return axios.post(process.env.APP_URL+'/sitemap') .then( res => res.data.map(link => link) ) } }, i think you can use same behave\n- @drake035 you gotta remove the nuxt router module and fix the file structure - gist.github.com/MexsonFernandes/…. I have cloned and checked...its working flawlessly.\n- Thanks, but same result I'm afraid.\n- Could you log: the response from axios, create an array of the return, log it, then return the array and show use the directory structure as Brahim said\n- Axios response: `[\"/project/14/test\", \"/project/16/16\", \"/project/17/17\"`. About `/pages` directory structure: I have `about.vue`, `contact.vue` etc at the root of this directory, and also a its root I have a `/projects` folder in which there is a `_id.vue` file and a `/slug` directory.\n- Thank you :) But @tony19's slighltly earlier answer already solved my issue (`target: 'static'` doesn't seem required btw)","metadata":{"transformedAt":"2026-08-18T18:33:07.856Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":243,"estimatedTokens":1209}}305{"id":"stack-67718493","source":"stackoverflow","questionId":67718493,"title":"NuxtJS - manage several axios instances","tags":["vue.js","nuxt.js"],"text":"Title: NuxtJS - manage several axios instances\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI use NuxtJS 2, and I need to have 2 or more axios instances with different configs.\n\nIn VueJS / JS classic, I can just create a new instance of `axios`:\n\n```\nvar axiosElasticSearch = axios.create({\n baseURL: 'https://elastic.com/',\n timeout: 1000,\n headers: {'X-Custom-Header': 'foobar'}\n});\n```\n\nBut in Nuxt, they apply their own config to handle this, because of the SSR layer.\n\nIn my Nuxt config, I have this :\n\n```\naxios: {\n baseUrl: process.env.API_URL,\n browserBaseUrl: process.env.BROWSER_API_URL,\n withCredentials: true,\n headers: {\n common: {\n Accept: 'application/json',\n Authorization: 'Bearer ' + process.env.API_TOKEN\n }\n }\n },\n```\n\nAnd then, I can inject it easily.\n\nIs it possible to manage it in Nuxt? I looked at proxy option, but I don't think it's what I want.\n\n========================================\n\nCode:\n```js\nvar axiosElasticSearch = axios.create({\n baseURL: 'https://elastic.com/',\n timeout: 1000,\n headers: {'X-Custom-Header': 'foobar'}\n});\n```\n\n```js\naxios: {\n baseUrl: process.env.API_URL,\n browserBaseUrl: process.env.BROWSER_API_URL,\n withCredentials: true,\n headers: {\n common: {\n Accept: 'application/json',\n Authorization: 'Bearer ' + process.env.API_TOKEN\n }\n }\n },\n```\n\n```text\naxios\n```\n\n```js\n// ~/plugin/api.js\nexport default function ({ $axios }, inject) {\n // Create a custom axios instance\n const api = $axios.create({\n headers: {\n common: {\n Accept: 'text/plain, */*'\n }\n }\n })\n\n // Set baseURL to something different\n api.setBaseURL('https://my_api.com')\n\n // Inject to context as $api\n inject('api', api)\n}\n```\n\n```js\n// nuxt.config.js\nexport default {\n plugins: ['~/plugins/api.js']\n}\n```\n\n```js\n// MyComponent.vue\nexport default {\n fetch() {\n this.$api.get(...)\n },\n asyncData({ $api }) {\n $api.get(...)\n }\n}\n```\n\n```text\nnuxt/axios\n```\n\n```text\n$axios.create\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- This can maybe help: github.com/nuxt-community/axios-module/issues/…","metadata":{"transformedAt":"2026-08-18T18:33:07.856Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":123,"estimatedTokens":540}}306{"id":"stack-64233657","source":"stackoverflow","questionId":64233657,"title":"Include a custom script in the head tag in nuxt","tags":["vue.js","nuxt.js"],"text":"Title: Include a custom script in the head tag in nuxt\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a custom script that I want to include in my nuxt project.\n\nThe thing is, this script needs to be included *before* the dom loads. It contains overrides for this particular project.\n\nMy assets folder is structured with a scripts subfolder:\n\nhttps://i.sstatic.net/4wt2T.png\n\nIn my nuxt.config.js file I've got this:\n\n```\nexport default {\n css: [\"~/assets/css/main.scss\"],\n head: {\n script: [\n {\n src: \"https://cdnjs.cloudflare.com/ajax/libs/aframe/1.0.4/aframe.min.js\", \n src: \"_nuxt/assets/scripts/bundle.js\", // this is the script that I'm trying to include\n },\n```\n\nI added the `_nuxt/` after looking at how some of the other assets are being successfully included\n\nhttps://i.sstatic.net/xSFZj.png\n\nAll of the stuff we need to happen before the dom is loaded is already bundled up in the file and, even though it's unconventional, this *would* work if we could get it to load.\n\nI've looked through the nuxt docs about the `head` property either in this config or in the actual .vue files, but it talks about external resources and not those local to the project.\n\nHow would I properly include this file in the head within nuxt?\n\nAlso, if there's a proper way of bundling the source code for this bundle separate from the main nuxt js code so that it can pass through nuxt/tsc properly I'm def open to it.\n\n========================================\n\nCode:\n```text\nexport default {\n css: [\"~/assets/css/main.scss\"],\n head: {\n script: [\n {\n src: \"https://cdnjs.cloudflare.com/ajax/libs/aframe/1.0.4/aframe.min.js\", \n src: \"_nuxt/assets/scripts/bundle.js\", // this is the script that I'm trying to include\n },\n```\n\n```text\n_nuxt/\n```\n\n```text\nhead\n```\n\n```text\nstatic\n```\n\n```text\nstatic\n```\n\n```text\nassets\n```\n\n```text\nscripts\n```\n\n```text\nassets\n```\n\n```text\nstatic\n```\n\n```text\njs\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nstatic\n```\n\n========================================\n\nComments:\n- Thanks for going into detail, I saw a similar post to this but they didn't go into detail and I still couldn't figure it out but thanks to you I did :)\n- Great work, thanks for this! I was doing exactly the same, assumed that assets was the right place to put a script. It'd be great if Nuxt included a way to add a \"@/\" or \"~/\" path to head scripts like you can with the css property.","metadata":{"transformedAt":"2026-08-18T18:33:07.856Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":101,"estimatedTokens":606}}307{"id":"stack-66639714","source":"stackoverflow","questionId":66639714,"title":"Nuxt Linking CSS Files in Head property from assets issue","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: Nuxt Linking CSS Files in Head property from assets issue\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to link my css files by using head property of nuxt in only one specific page like this:\n\n\r\n\r\n\n```\nhead: {\n link: [\n {rel: 'stylesheet', href: require('~/assets/css/font.css')},\n {rel: 'stylesheet', href: require('~/assets/css/style.css')},\n ]\n}\n```\n\n\r\n\r\n\r\n\nAfter doing this when I load my page Everything is fine but I see this Error at Console\n**GET http://localhost:3000/[object%20Object] net::ERR_ABORTED 404 (Not Found)**\n\nand when I looked at source I saw that CSS Files were linked this way :\n\n\r\n\r\n\n```\n\n```\n\n\r\n\r\n\r\n\nI need to import my CSS filed this way but I still have this problem, How can I solve this ?\n\n========================================\n\nCode:\n```js\nhead: {\n link: [\n {rel: 'stylesheet', href: require('~/assets/css/font.css')},\n {rel: 'stylesheet', href: require('~/assets/css/style.css')},\n ]\n}\n```\n\n```html\n<link data-n-head=\"ssr\" rel=\"stylesheet\" href=\"[object Object]\">\n<link data-n-head=\"ssr\" rel=\"stylesheet\" href=\"[object Object]\">\n```\n\n```js\nhead: {\n link: [\n {rel: 'stylesheet', type: 'text/css', href: '/css/font.css'},\n {rel: 'stylesheet', type: 'text/css', href: '/css/style.css'}\n ]\n}\n```\n\n```html\n<style scoped>\n @import url('~assets/css/font.css');\n @import url('~assets/css/style.css');\n</style>\n```\n\n```text\n/static\n```\n\n```text\n@import\n```\n\n```text\n<style>\n```\n\n```text\n.vue\n```\n\n========================================\n\nComments:\n- remove require ... use like this {rel: 'stylesheet', href: '~/assets/css/font.css'},\n- If I remove require styles wouldn't be added properly It doesn't works that way\n- it will work ... is ur assets and nuxt cofig in same folder?\n- I tried that before posting this issue here, if I remove require it will be linked this way : and it doesn't work\n- For Nuxt3 its `/public` folder","metadata":{"transformedAt":"2026-08-18T18:33:07.856Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":98,"estimatedTokens":481}}308{"id":"stack-74138162","source":"stackoverflow","questionId":74138162,"title":"Nuxt 3 : Difference nuxt start / nuxt preview?","tags":["vue.js","nuxt.js","nuxt3.js"],"text":"Title: Nuxt 3 : Difference nuxt start / nuxt preview?\nTags: vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nIs there a difference between nuxt start + nuxt preview?\n\nAnd is it correct to start a server with an ssr nuxt app in production mode with:\nnpm run build (nuxt build)\n\nnpm run start (nuxt start) ?\n\nFor me, the docs are a little bit confusing, https://v3.nuxtjs.org/api/commands/preview/\n\"The preview command starts a server to preview your Nuxt application after running the build command.\"\n\n========================================\n\nTop Answer:\n**I think, nuxt start and nuxt preview is similar.**\n\nDepend on this documentation https://nuxt.com/docs/getting-started/deployment\n\nTo deploy nuxt into server, we can use `node .output/server/index.mjs`\n\nAt the same time, when we use command `nuxt preview` this also execute the similar entry point.\n\nhttps://i.sstatic.net/MPjet.png\n\nDepend on this documentation https://nuxt.com/docs/api/commands/preview/\n\nThis command sets process.env.NODE_ENV to production\n\nSo my conclusion is we can use command `nuxt preview` for **production**.\n\n========================================\n\nCode:\n```json\n\"scripts\": {\n \"build\": \"nuxt build\",\n \"start\": \"node .output/server/index.mjs\"\n}\n```\n\n```text\nnuxt dev\n```\n\n```text\nnuxt build\n```\n\n```text\nnuxt generate\n```\n\n```text\nnuxt preview\n```\n\n```text\nnuxt start\n```\n\n```text\nnuxt ship\n```\n\n```text\nnuxt yoloooo\n```\n\n```text\nnuxt start\n```\n\n```text\nnuxt start\n```\n\n```text\nnuxt dev\n```\n\n```text\nnode .output/server/index.mjs\n```\n\n```text\nnuxt preview\n```\n\n```text\nnuxt preview\n```\n\n```text\nnpm run build\n```\n\n```text\nnode .output/server/index.mjs\n```\n\n```text\nnpm run preview\n```\n\n```text\nnpm run start\n```\n\n```text\nnpm run preview\n```\n\n```text\nnode .output/server/index.mjs\n```\n\n========================================\n\nComments:\n- from this documentation nuxt.com/docs/api/commands/preview : **This command sets process.env.NODE_ENV to production** so, I think we can use this command for production. `npm run build` and then `npm run preview`\n- @aijogja if you do not preview it with the `production` environment, it will indeed not look like a production preview but rather a dev one (defeating the whole purpose). Still, it is not an actual bundle recommended for a real-world production environment.\n- \"nuxt preview\" and \"nuxt start\" are aliases. Check their CLI outputs when flagged with help like \"nuxt preview --help\". They print the same output: ` Usage: npx nuxi preview|start [--dotenv] [rootDir] ⋮ Launches nitro server for local testing after nuxi build. Use npx nuxi [command] --help to see help for each command `\n- Is it possible to have SSR with SSG? If so, do you use nuxt generate or nuxt build?\n- @Mathijs SSR is quite a superset of SSG tbh. If it's for the cost part, you could probably trigger some cloud/edge functions to make some clever work. TLDR: some more details are welcome regarding your use case and wished end goal!\n- I am using nuxt/content for blogs and I have landing pages. On top of that I have a dashboard. I can't use SSR or SSG with my dashboard pages, because there is just too much to render and it would be to expensive. So i use ssr: false (SPA) for that. Currently my entire application is ssr: false. However, for my blogs to work (nuxt/content) I need to either prerender (SSG) or use ssr: true (SSR). My landing pages are preferably SSG for performance and seo. I can't make my blogs SSG, since I want the user to search and paginate through the blogs. Meaning I wouuld have to use routeRules.\n- @Mathijs you can use SPA only for the dashboard side and SSG for the rest (make the search on the client-side with something simple, pagination will not be an issue). Feel also free to open a brand new question.\n- No you cannot use `preview` for production, because the preview will not bundle the app efficiently for that environment. Having your app working as dev or prod is totally different and could lead to actual security/performance issues. There's a reason it's called **preview** (so that it can allow us to have a quick glance at the result without waiting for the whole build step to be done).\n- hmm. refers to this doc nuxt.com/docs/getting-started/deployment the command for deployment is `node .output/server/index.mjs` which is same as the `npm run preview` command.\n- How you **run** and how you **bundle** your app are 2 different things.\n- Yarn preview shouldn't be used for production\n- There is a difference between SSG (`nuxt generate`) and SSR (`nuxt build`) tho, you don't need a NodeJS server with SSG, hence `node .output/server/index.mjs` and `npm run preview` are NOT equivalent because it depends on how you bundle your app in the first place, check my answer for more details.\n- I understand your point, in my previous answer, I assume that the Nuxt application will be deployed on a Node.js server and that the rendering mode will be \"universal rendering\" (SSR) nuxt.com/docs/guide/concepts/rendering#universal-rendering","metadata":{"transformedAt":"2026-08-18T18:33:07.856Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":136,"estimatedTokens":1255}}309{"id":"stack-68362603","source":"stackoverflow","questionId":68362603,"title":"image via social media from PWA","tags":["javascript","vue.js","nuxt.js","html2canvas","web-share"],"text":"Title: image via social media from PWA\nTags: javascript, vue.js, nuxt.js, html2canvas, web-share\nSource: Stack Overflow\n\nQuestion:\nIn my Nuxt PWA I have a function that converts my HTML to Canvas using this package. The generated image is in base 64. Now I want to be able to that image via: Whatsapp, Facebook, email, Instagram etc. I have found several packages but they all don't seem to support sharing files only URLs and Text.\n\nThis is my function:\n\n```\nshareTicket(index) {\n html2canvas(this.$refs['ticket-' + index][0], {\n backgroundColor: '#efefef',\n useCORS: true, // if the contents of screenshots, there are images, there may be a case of cross-domain, add this parameter, the cross-domain file to solve the problem\n }).then((canvas) => {\n let url = canvas.toDataURL('image/png') // finally produced image url\n\n if (navigator.) {\n navigator.({\n title: 'Title to be shared',\n text: 'Text to be shared',\n url: this.url,\n })\n }\n })\n```\n\nWhen I take out the `if (navigator.)` condition I get an error in my console that `navigator.` is not a function. I read somewhere that it only works on HTTPS so I uploaded to my staging server and tried but still got the same error.\n\nJust to be clear I want to be able to the generated image itself and not a URL.\n\n========================================\n\nTop Answer:\nI have a variation of the code below in a `()` function in an app of mine and it works fine if executed on the client.\n\n```\nconst = async() => {\n if (!('' in navigator)) {\n return;\n }\n // `element` is the HTML element you want to .\n // `backgroundColor` is the desired background color.\n const canvas = await html2canvas(element, {\n backgroundColor,\n });\n canvas.toBlob(async (blob) => {\n // Even if you want to just one file you need to \n // send them as an array of files.\n const files = [new File([blob], 'image.png', { type: blob.type })];\n const shareData = {\n text: 'Some text',\n title: 'Some title',\n files,\n };\n if (navigator.canShare(shareData)) {\n try {\n await navigator.(shareData);\n } catch (err) {\n if (err.name !== 'AbortError') {\n console.error(err.name, err.message); \n }\n }\n } else {\n console.warn('Sharing not supported', shareData); \n }\n });\n};\n```\n\n========================================\n\nCode:\n```text\nshareTicket(index) {\n html2canvas(this.$refs['ticket-' + index][0], {\n backgroundColor: '#efefef',\n useCORS: true, // if the contents of screenshots, there are images, there may be a case of cross-domain, add this parameter, the cross-domain file to solve the problem\n }).then((canvas) => {\n let url = canvas.toDataURL('image/png') // finally produced image url\n\n if (navigator.share) {\n navigator.share({\n title: 'Title to be shared',\n text: 'Text to be shared',\n url: this.url,\n })\n }\n })\n```\n\n```text\nif (navigator.share)\n```\n\n```text\nnavigator.share\n```\n\n```html\n<template>\n <div>\n <div id=\"capture\" ref=\"element\" style=\"padding: 10px; background: #f5da55\">\n <h4 style=\"color: #000\">Hello world!</h4>\n </div>\n\n <br />\n <br />\n <button @click=\"share\">share please</button>\n </div>\n</template>\n\n<script>\nimport html2canvas from 'html2canvas'\n\nexport default {\n methods: {\n share() {\n // iife here\n ;(async () => {\n if (!('share' in navigator)) {\n return\n }\n // `element` is the HTML element you want to share.\n // `backgroundColor` is the desired background color.\n const canvas = await html2canvas(this.$refs.element)\n canvas.toBlob(async (blob) => {\n // Even if you want to share just one file you need to\n // send them as an array of files.\n const files = [new File([blob], 'image.png', { type: blob.type })]\n const shareData = {\n text: 'Some text',\n title: 'Some title',\n files,\n }\n if (navigator.canShare(shareData)) {\n try {\n await navigator.share(shareData)\n } catch (err) {\n if (err.name !== 'AbortError') {\n console.error(err.name, err.message)\n }\n }\n } else {\n console.warn('Sharing not supported', shareData)\n }\n })\n })()\n },\n },\n}\n</script>\n```\n\n```text\nmethod\n```\n\n```text\nasync\n```\n\n```text\n$refs\n```\n\n```text\nv91\n```\n\n```js\nconst share = async() => {\n if (!('share' in navigator)) {\n return;\n }\n // `element` is the HTML element you want to share.\n // `backgroundColor` is the desired background color.\n const canvas = await html2canvas(element, {\n backgroundColor,\n });\n canvas.toBlob(async (blob) => {\n // Even if you want to share just one file you need to \n // send them as an array of files.\n const files = [new File([blob], 'image.png', { type: blob.type })];\n const shareData = {\n text: 'Some text',\n title: 'Some title',\n files,\n };\n if (navigator.canShare(shareData)) {\n try {\n await navigator.share(shareData);\n } catch (err) {\n if (err.name !== 'AbortError') {\n console.error(err.name, err.message); \n }\n }\n } else {\n console.warn('Sharing not supported', shareData); \n }\n });\n};\n```\n\n```text\nshare()\n```\n\n========================================\n\nComments:\n- What happens if you write this all in `if (process.client) { // insert your whole code here }`? And also, it looks like this is mainly used on mobile, did you tried it there or only on desktop?\n- Sorry I dunno what process.client means also this if for both mobile and desktop and I have tried it on both and it doesn't work.\n- This is from the Nuxt documentation, basically saying that the code should not run on the server. nuxtjs.org/docs/2.x/internals-glossary/context Following the documentation of MDN, I achieved to make the demo work properly: developer.mozilla.org/en-US/docs/Web/API/Navigator/ You want the same result as on this page, right?\n- When I wrap my code in `if (process.client)` I still get the error `navigator.` is not a function. Didn't know about it not working with a server, not sure how to run my app then. Yes please I want to be able files like described in the link you shared.\n- Have you set the package up as a client only plugin? additional help from this post\n- Sorry what package? I'm confused.\n- @Porter I'm not using any 3rd party package for this though.\n- Does not work. When I take out the condition I get TypeError: navigator.canShare is not a function. Not sure if I require a Vue/Nuxt specific solution for this.\n- Are you sure you're running this on the client (that is, in the browser, not on the server)? Also, not all browsers support the Web Level 2 API, so you need to feature-detect this (`if ('' in navigator && 'canShare' in navigator) { /* 👍 */ }`). Do you have a URL to test this?\n- @DenverCoder9 it's a Nuxt app, not sure how i'm supposed to run it. Initially I was using `yarn dev` to run my app but I even tried generating the static assets with `yarn generate` and then running `yarn start` but that didn't work either.\n- @user3718908 `yarn dev` is for local dev. If you do have `target: static`, you should `yarn generate` and `yarn start` indeed. You can even `yarn generate` and drop your `dist` directory here directly: app.netlify.com/drop\n- Thank you soo much for your time. I tried this in both the latest stable builds of firefox, chrome and edge on my Mac running BigSur and it still didn't work. However when I tried it in safari it worked. I tried on my phone as well and it worked with only chrome not firefox. Not sure what's going on here.\n- So it looks like my code worked :-) Here's a screenshot where I test this on desktop Safari. The API is also supported on the desktop by Microsoft Edge (the Chromium-based variant). It will also soon land in macOS and Windows on Chrome. It also already works on Chrome OS.\n- @DenverCoder9 yep, it was probably just the funky support + having a proper verified SSL certificate to try this out.","metadata":{"transformedAt":"2026-08-18T18:33:07.856Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":225,"estimatedTokens":2007}}310{"id":"stack-61976785","source":"stackoverflow","questionId":61976785,"title":"How do you use custom fonts with TailwindCSS and NuxtJS?","tags":["css","vue.js","fonts","tailwind-css","nuxt.js"],"text":"Title: How do you use custom fonts with TailwindCSS and NuxtJS?\nTags: css, vue.js, fonts, tailwind-css, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSo I'm building a website with NuxtJS using Tailwind CSS for my styles. I'm using the @nuxtjs/tailwindcss module.\n\nThe issue is that my fonts don't seem to be loading on the browser. The correct `font-family` is still applied by the CSS as you can see in the devtools screenshot, but the browser still renders my text with Times New Roman.\n\n--Devtools Screenshot\n\nMy fonts files are .ttf files stored in a `/assets/fonts/` folder in my project's root directory.\n\nMy `tailwind.css` file looks like this \n\n```\n@import 'tailwindcss/components';\n@import 'tailwindcss/utilities';\n\n@font-face {\n font-family: 'Montserrat';\n font-weight: 400;\n src: url('../fonts/Montserrat-Regular.ttf') format('ttf');\n}\n\n@font-face {\n font-family: 'Montserrat';\n font-weight: 700;\n src: url('../fonts/Montserrat-Bold.ttf') format('ttf');\n}\n\n@font-face {\n font-family: 'Montserrat';\n font-weight: 900;\n src: url('../fonts/Montserrat-Black.ttf') format('ttf');\n}\n```\n\nand my `tailwind.config.js` looks like this\n\n```\nmodule.exports = {\n theme: {\n fontFamily: {\n sans: ['Montserrat'],\n serif: ['Montserrat'],\n mono: ['Montserrat'],\n display: ['Montserrat'],\n body: ['Montserrat']\n },\n // Some more irrelevant theme customization\n },\n variants: {},\n plugins: []\n}\n```\n\nI wanted to completly override Tailwind's base fonts so I didn't use `extend` and I plan on cleaning this up and using an other font for some texts once I figure out how to properly do this.\n\nMy guts tell me that Tailwind is not the problem here since the Devtools actually show Montserrat as the computed font, and the webpack build does not throw any error.\n\nI've tried both answers featured in this related question, the accepted one actually being my implementation, but no good result so far.\n\nI'd be very grateful if somebody could help me !\n\nEDIT : I created a Github repo reproducing the issue, it can be found here and all steps to reproduce are in the README.MD\n\n========================================\n\nCode:\n```text\n@import 'tailwindcss/components';\n@import 'tailwindcss/utilities';\n\n@font-face {\n font-family: 'Montserrat';\n font-weight: 400;\n src: url('../fonts/Montserrat-Regular.ttf') format('ttf');\n}\n\n@font-face {\n font-family: 'Montserrat';\n font-weight: 700;\n src: url('../fonts/Montserrat-Bold.ttf') format('ttf');\n}\n\n@font-face {\n font-family: 'Montserrat';\n font-weight: 900;\n src: url('../fonts/Montserrat-Black.ttf') format('ttf');\n}\n```\n\n```text\nmodule.exports = {\n theme: {\n fontFamily: {\n sans: ['Montserrat'],\n serif: ['Montserrat'],\n mono: ['Montserrat'],\n display: ['Montserrat'],\n body: ['Montserrat']\n },\n // Some more irrelevant theme customization\n },\n variants: {},\n plugins: []\n}\n```\n\n```text\nfont-family\n```\n\n```text\n/assets/fonts/\n```\n\n```text\ntailwind.css\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nextend\n```\n\n```css\nsrc: url('../fonts/Montserrat-Regular.ttf') format('ttf');\n```\n\n```css\nsrc: url('../fonts/Montserrat-Regular.ttf') format('truetype');\n```\n\n```css\nsrc: url('../fonts/Montserrat-Regular.ttf');\n```\n\n```css\nsrc:\n url('../fonts/Montserrat-Regular.ttf') format('truetype'),\n url('../fonts/Montserrat-Regular.woff2') format('woff2'),\n url('../fonts/Montserrat-Regular.woff') format('woff')\n```\n\n```css\nsrc:\n url('../fonts/Montserrat-Regular.woff2') format('woff2'),\n url('../fonts/Montserrat-Regular.woff') format('woff')\n```\n\n```text\n@font-face\n```\n\n```text\nsrc\n```\n\n```text\ncaniuse\n```\n\n========================================\n\nComments:\n- Is font in production directory? Is loaded by browser?\n- As explained in my post (maybe nor clearly enough, my bad then), my font files are located in `/assets/fonts` at the root of my project directory. I don't know how to check if the fonts are actually loaded by the browser, all I know is that my screenshot shows that the right font shows in the \"computed\" panel but the browser still renders using Times New Roman, which would lead me to believe that the font is actually not loaded.\n- 1. I believe you are talking about sources root, but I'm asking about files after build (dist directory) to check if webpack for some reason is ignoring them. 2. You can check if files are loaded in browser in Network tab in devtools. 3. Build app and check in css source if there still are @font-face with your font present. 4. It would be best if You could provide some demo in any sandbox.\n- Oh my bad, I though you where talking about font sources. I have no CSS in my build output though, just two folders (client and server, seems normal using Nuxt), and the client one contains a fonts folder containing my built font. I'm a bit new to server side rendering stuff, especially in dev mode, but I'm a bit surprised to see that my network tab shows no download of either a CSS stylesheet or a font file . I'll try to put up some demo but I don't know of any sandbox that allows to recreate a SSR environment. I'll provide a github link soon. Thx for the help !\n- codesandbox.io I think fastest way is to find any existing nuxt demo and just change fonts like you did. But git source will do too.\n- I updated my question with a link to the Github repo. Contains the bare minimum needed. NuxtJS app serving a single index.vue file with TailwindCSS for styles, loading custom fonts.\n- Ok I will answer soon\n- I'm actually not suprised this was so simple... I am confused because I basically used the same 'ttf' format on an angular project of mine which worked perfectly fine. Thanks for the woff advice as well, I'll take a look at it ! Anyway, this works. Thank you very much for your help !\n- If \"ttf\" worked in other project then maybe font that was used in project was actually installed locally in system, so font-face was not used and you could missed it. Also it would work without using \"format('xxx')\".\n- PS if you are planning to use this repo, you have missing @nuxtjs/apollo dependency in package.json\n- I'm not planning on using the repo, it's just a copy of the main one. I tried to remove as much dependencies as possible to make it easier on you. Guess this one sliped through. Thanks again.","metadata":{"transformedAt":"2026-08-18T18:33:07.856Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":181,"estimatedTokens":1562}}311{"id":"stack-64073309","source":"stackoverflow","questionId":64073309,"title":"Parameter not allowed for this message type: code_challenge_method, how to fix it in nuxt?","tags":["vue.js","oauth-2.0","google-oauth","nuxt.js"],"text":"Title: Parameter not allowed for this message type: code_challenge_method, how to fix it in nuxt?\nTags: vue.js, oauth-2.0, google-oauth, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nin Nuxt I have the title error using auth v5. This is my current strategy:\n\nhttps://i.sstatic.net/DW06D.png\n\nThe docs (https://dev.auth.nuxtjs.org/schemes/oauth2#codechallengemethod) says that you can use \"plain\" or \"S256\" as an option, I tried both but the error persists.\n\nThe only I cant manually get it work is by copy-pasting the oAuth in the url:\n\nhttps://accounts.google.com/o/oauth2/auth/identifier?protocol=oauth2&response_type=token&client_id=MYCLIENTID&redirect_uri=https%3A%2F%2Flocalhost%3A3005%2Flogin&scope=profile%20email&state=sIpW-W_6h_QwUs0gCDV_o&flowName=GeneralOAuthFlow\n\nCompare that link to the following:\n\nhttps://accounts.google.com/o/oauth2/auth/identifier?protocol=oauth2&response_type=token&client_id=MYCLIENTID&redirect_uri=https%3A%2F%2Flocalhost%3A3005%2Flogin&scope=profile%20email&state=sIpW-W_6h_QwUs0gCDV_o&code_challenge_method=S256&code_challenge=fnyp2Ray850HEmHEwmoyQtIrPFPpHWBt4nVAz9p5Vxs&flowName=GeneralOAuthFlow\n\nThe only difference between the first and second link is that the first one actually works (I can login) and it doesn't have a challenge_method.\n\nThe second link doesn't work (it displays the google image above) but if you read the end of the link it has both the code_challenge_method & code_challenge\n\n========================================\n\nTop Answer:\nI had the same error and this setup has fixed my issues. **Note** I am using Next-auth but the parameter name is the same except for the naming convention. Set *response_type* value to **code**. Setting the *response_type* value to **token** will issue an error, so use **code** instead.\n\nhttps://i.sstatic.net/0bhKs.png\n\n========================================\n\nCode:\n```text\nresponseType: 'token id_token'\n```\n\n========================================\n\nComments:\n- hey, @Damian this solution, it's still not working.","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":41,"estimatedTokens":503}}312{"id":"stack-58051668","source":"stackoverflow","questionId":58051668,"title":"NuxtJS Auth error with property doesn't exist","tags":["typescript","nuxt.js"],"text":"Title: NuxtJS Auth error with property doesn't exist\nTags: typescript, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI've just installed *@nuxtjs/auth* on my project.\n\nI get `Property '$auth' does not exist on type 'AuthLoginPage'` class.\n\n### Method login on login class page\n\n```\nthis.$auth.loginWith('local', {\n data: {\n username: 'your_username',\n password: 'your_password'\n }\n });\n```\n\n### My nuxt.config.ts\n\n```\nmodules: [\n // Doc: https://axios.nuxtjs.org/usage\n '@nuxtjs/axios',\n '@nuxtjs/auth',\n '@nuxtjs/pwa',\n ],\n...\nauth: {\n strategies: {\n local: {\n endpoints: {\n login: {\n url: 'http://127.0.0.1:3001/users/login',\n method: 'post',\n propertyName: 'token'\n },\n logout: {\n url: 'http://127.0.0.1:3001/users/logout',\n method: 'post'\n },\n user: {\n url: 'http://127.0.0.1:3001/users/me',\n method: 'get',\n propertyName: 'user'\n }\n },\n // tokenRequired: true,\n // tokenType: 'bearer'\n }\n }\n```\n\nIt's impossible for me to use NuxtJS Auth.\n\nHave you got an idea please?\n\n========================================\n\nTop Answer:\nEdwin Rendoon Cadivid's answer works, but it's not the right way to do it. \n\nI wrote the original typings and I just submitted another PR to bundle the typings with nuxt auth directly: https://github.com/nuxt-community/auth-module/pull/486\n\nAfter that PR is merged as of `@nuxtjs/auth` v5 (which re-writes the module in typescript) all you will have to do is add `@nuxtjs/auth` to the `types` array in your tsconfig.json\n\n```\n\"types\": [\n \"@nuxt/types\", \n \"@nuxtjs/auth\" // Add this line\n ]\n```\n\nFor now, until the PR is merged run\n`npm install --save-dev @types/nuxtjs__auth`\n\nThen add `@types/nuxtjs__auth` to you're `types` array in your `tsconfig.json`\n\n```\n\"types\": [\n \"@nuxt/types\", \n \"@types/nuxtjs__auth\" // Add this line\n ]\n```\n\n========================================\n\nCode:\n```text\nthis.$auth.loginWith('local', {\n data: {\n username: 'your_username',\n password: 'your_password'\n }\n });\n```\n\n```text\nmodules: [\n // Doc: https://axios.nuxtjs.org/usage\n '@nuxtjs/axios',\n '@nuxtjs/auth',\n '@nuxtjs/pwa',\n ],\n...\nauth: {\n strategies: {\n local: {\n endpoints: {\n login: {\n url: 'http://127.0.0.1:3001/users/login',\n method: 'post',\n propertyName: 'token'\n },\n logout: {\n url: 'http://127.0.0.1:3001/users/logout',\n method: 'post'\n },\n user: {\n url: 'http://127.0.0.1:3001/users/me',\n method: 'get',\n propertyName: 'user'\n }\n },\n // tokenRequired: true,\n // tokenType: 'bearer'\n }\n }\n```\n\n```text\nProperty '$auth' does not exist on type 'AuthLoginPage'\n```\n\n```js\n<pre>\n // Type definitions for @nuxtjs/auth 4.8\n // Project: https://auth.nuxtjs.org\n // Definitions by: Ruskin Constant <https://github.com/jonnyparris>\n // Daniel Leal <https://github.com/danielgek>\n // Nick Bolles <https://github.com/NickBolles>\n // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n // TypeScript Version: 3.1\n\n import Vue, { ComponentOptions } from 'vue';\n\n export interface Storage {\n setUniversal(key: string, value: any, isJson?: boolean): string;\n getUniversal(key: string, isJson?: boolean): any;\n syncUniversal(key: string, defaultValue: any, isJson?: boolean): any;\n // Local State\n setState(key: string, val: any): string;\n getState(key: string): string;\n watchState(key: string, handler: (newValue: any) => void): any;\n // Cookies\n setCookie(key: string, val: any, options?: object): any;\n getCookie(key: string, isJson?: boolean): any;\n // Local Storage\n setLocalStorage(key: string, val: any, isJson?: boolean): any;\n getLocalStorage(key: string, isJson?: boolean): any;\n }\n\n export interface Auth<T = any> {\n ctx: any;\n $state: any;\n $storage: Storage;\n user: Partial<T>;\n loggedIn: boolean;\n loginWith(strategyName: string, ...args: any): Promise<never>;\n login(...args: any): Promise<never>;\n logout(): Promise<never>;\n fetchUser(): Promise<never>;\n fetchUserOnce(): Promise<never>;\n hasScope(scopeName: string): boolean;\n setToken(strategyName: string, token?: string): string;\n getToken(strategyName: string): string;\n syncToken(strategyName: string): string;\n onError(handler: (error: Error, name: string, endpoint: any) => void): any;\n setUser(user?: Partial<T>): any;\n reset(): Promise<never>;\n redirect(name: string): any;\n }\n\n declare module 'vue/types/options' {\n interface ComponentOptions<V extends Vue> {\n auth?: boolean | string;\n }\n }\n\n declare module 'vue/types/vue' {\n interface Vue {\n $auth: Auth;\n }\n }\n\n </pre>\n```\n\n```json\n\"typings\": \"types/index.d.ts\",\n \"files\": [\"types/*.d.ts\"],\n```\n\n```text\n\"types\": [\n \"@nuxt/types\", \n \"@nuxtjs/auth\" // Add this line\n ]\n```\n\n```text\n\"types\": [\n \"@nuxt/types\", \n \"@types/nuxtjs__auth\" // Add this line\n ]\n```\n\n```text\n@nuxtjs/auth\n```\n\n```text\n@nuxtjs/auth\n```\n\n```text\ntypes\n```\n\n```text\nnpm install --save-dev @types/nuxtjs__auth\n```\n\n```text\n@types/nuxtjs__auth\n```\n\n```text\ntypes\n```\n\n```text\ntsconfig.json\n```\n\n```text\nimport { Auth } from 'nuxtjs__auth'\n\ndeclare module 'vue/types/vue' {\n interface Vue {\n // ...\n readonly $auth: Auth\n }\n}\n```\n\n```text\nNick Bolles\n```\n\n```text\n$auth\n```\n\n```text\nVue\n```\n\n```text\ntypes/vue-shim.d.ts\n```\n\n```text\n{\n modules: [\n '@nuxtjs/axios',\n '@nuxtjs/auth-next'\n ],\n auth: {\n // Options\n }\n}\n```\n\n```text\n{\n compilerOptions: {\n \"types\": [\n \"@nuxtjs/auth-next\",\n ]\n },\n}\n```\n\n```text\n@nuxtjs/auth\n```\n\n```text\nnpm install --save-exact @nuxtjs/auth-next\n```\n\n```text\n@nuxtjs/auth-next\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ntsconfig.json\n```\n\n```text\n@nuxtjs/auth-next\n```\n\n```text\ncompilerOptions.types\n```\n\n========================================\n\nComments:\n- did u add it to nuxt config? if yes - show your config\n- @Aldarund Yes, I added the nuxt.config.ts auth config plugin.\n- did you add it into modules section of nuxt config, you showed only part of your nuxt config...? And where are u calling it? in what method?\n- @Aldarund Sorry, I forgot to add entirely the config :) I updated the first message. Have you got an idea?\n- create a repro on codesandbox, hard to say without it\n- Eagerly waiting for merging the PR but no update yet :(\n- It was merged, just as part of a different PR now: github.com/nuxt-community/auth-module/pull/…> Actually it's this one: github.com/nuxt-community/auth-module/pull/621\n- merged but not yet released. So I resorted to this one. Thanks\n- I still get it when using in `middleware: (context)=>{context.$auth}` Property '$auth' does not exist on type 'Context'\n- I still had to do option B","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":337,"estimatedTokens":1740}}313{"id":"stack-52044101","source":"stackoverflow","questionId":52044101,"title":"How to add headers on Nuxt static files response?","tags":["javascript","vue.js","cors","frontend","nuxt.js"],"text":"Title: How to add headers on Nuxt static files response?\nTags: javascript, vue.js, cors, frontend, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a json file on static folder and I'm trying to access it from another web site, but I'm having problem with the CORS. \n\nHow can I add headers (like Access-Control-Allow-Origin) on the static files response? \n\nI tried this https://github.com/nuxt/nuxt.js/issues/2554#issuecomment-363795301, but didn't work for static files.\n\n```\nmodule.exports = function (req, res, next) {\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.setHeader('Access-Control-Allow-Headers', '*');\n res.setHeader('Access-Control-Allow-Methods', '*');\n next()\n}\n```\n\n========================================\n\nTop Answer:\nIf you are using axios to make HTTP calls you might want to use Nuxt version of Axios. \nThere you can easily use option `proxy` in combination with Proxy Module\n\n========================================\n\nCode:\n```text\nmodule.exports = function (req, res, next) {\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.setHeader('Access-Control-Allow-Headers', '*');\n res.setHeader('Access-Control-Allow-Methods', '*');\n next()\n}\n```\n\n```text\nrender: {\n static: {\n setHeaders(res) {\n res.setHeader('X-Frame-Options', 'ALLOWALL')\n res.setHeader('Access-Control-Allow-Origin', '*')\n res.setHeader('Access-Control-Allow-Methods', 'GET')\n res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')\n }\n}\n```\n\n```text\nsetHeaders\n```\n\n```text\nproxy\n```\n\n========================================\n\nComments:\n- This method is not working for me in production on netlify\n- Any idea why this is only working in development and not in production?","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":63,"estimatedTokens":441}}314{"id":"stack-51542239","source":"stackoverflow","questionId":51542239,"title":"raw html in a vue js component (with nuxt)","tags":["html","vue.js","nuxt.js"],"text":"Title: raw html in a vue js component (with nuxt)\nTags: html, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI receive inside the object passed in my component a body (actu.body) with html tags inside (mostly p tags) and im wondering how to interpret them for the client side, my code is like that for now :\n\n```\n\n \n \n \n \n \n\n### {{ actu.headline }}\n\n \n\n### {{ actu.summarry }}\n\n \n \n \n \n {{ actu.body }}\n \n \n \n\nexport default {\nprops: {\nactu: {\n type: Object,\n required: true\n}\n```\n\n}\n };\n\nis there a proper way to do that with vue js ?\n\n========================================\n\nTop Answer:\nYes, use `v-html`.\n\n```\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div>\n <!-- {{ actu }} -->\n <v-parallax\n :src=\"actu.images[0].url\"\n dark\n >\n <v-layout\n align-center\n column\n justify-center\n >\n <h1 class=\"display-2 font-weight-thin mb-3\">{{ actu.headline }}</h1>\n <h4 class=\"subheading\">{{ actu.summarry }}</h4>\n </v-layout>\n </v-parallax>\n <v-card>\n <v-card-text>\n {{ actu.body }}\n </v-card-text>\n </v-card>\n </div>\n</template>\n\n\n<script>\nexport default {\nprops: {\nactu: {\n type: Object,\n required: true\n}\n```\n\n```text\n<span v-html=\"rawHtml\"></span>\n```\n\n```text\n<v-card-text v-html=\"actu.body\"></v-card-text>\n```\n\n```text\nv-html\n```\n\n========================================\n\nComments:\n- when I run `npm run lint`, warning appears `warning 'v-html' directive can lead to XSS attack vue/no-v-html`\n- yes thats right, and this is also documented in the docs from vue. So you should only use this if you can trust the source and never put in there user content.","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":107,"estimatedTokens":409}}315{"id":"stack-57857559","source":"stackoverflow","questionId":57857559,"title":"Redirect using Vue Router in Nuxt JS vuex","tags":["javascript","firebase","vue.js","vuex","nuxt.js"],"text":"Title: Redirect using Vue Router in Nuxt JS vuex\nTags: javascript, firebase, vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a login/register system as part of an app. I'm using Firebase and Vuex to handle authentication and database information. I have some actions in Nuxt JS that create the user, sign them in and log them out.\n\nI'm trying to implement a redirect after the user has been successfully registered / when they click login, my code is:\n\n```\nexport const actions = {\n\n /*\n * Create a user\n */\n createUser ({commit}, payload) {\n this.$fireAuth.createUserWithEmailAndPassword(payload.email, payload.password).then(function(firebaseUser) {\n commit('setUser', payload)\n }).catch(function(error) {\n console.log('error logging in' + error)\n });\n },\n\n /*\n * Log a user into Beacon\n */\n login ({commit}, payload) {\n this.$fireAuth.signInWithEmailAndPassword(payload.email, payload.password).then(function(firebaseUser) {\n commit('setUser', payload)\n }).catch(function(error) {\n console.log('error logging in' + error)\n });\n },\n\n /*\n * Sign a user out of Beacon\n */\n signOut ({commit}) {\n this.$fireAuth.signOut().then(() => {\n commit('setUser', null)\n }).catch(err => console.log(error))\n }\n\n}\n```\n\nI'm using Nuxt JS 2.9.2, on Vue JS 2.6.10\n\nI have a few modules.\n\nI've tried using `this.router.push('/')` and `window.location.href`, but would like to retain the SPA functionality.\n\n========================================\n\nCode:\n```text\nexport const actions = {\n\n /*\n * Create a user\n */\n createUser ({commit}, payload) {\n this.$fireAuth.createUserWithEmailAndPassword(payload.email, payload.password).then(function(firebaseUser) {\n commit('setUser', payload)\n }).catch(function(error) {\n console.log('error logging in' + error)\n });\n },\n\n /*\n * Log a user into Beacon\n */\n login ({commit}, payload) {\n this.$fireAuth.signInWithEmailAndPassword(payload.email, payload.password).then(function(firebaseUser) {\n commit('setUser', payload)\n }).catch(function(error) {\n console.log('error logging in' + error)\n });\n },\n\n /*\n * Sign a user out of Beacon\n */\n signOut ({commit}) {\n this.$fireAuth.signOut().then(() => {\n commit('setUser', null)\n }).catch(err => console.log(error))\n }\n\n}\n```\n\n```text\nthis.router.push('/')\n```\n\n```text\nwindow.location.href\n```\n\n```text\n$nuxt.$router.push\n```\n\n```text\nthis.$router.push\n```\n\n========================================\n\nComments:\n- What's wrong with `this.$router.push` or `this.$router.replace`?\n- What's the problem you're having? You don't really ask any questions.\n- Just want to add that if you use an external function (like outside of mutations/actions) but still in the same Vuex file, you need to pass it the `router` from within the mutation/action, like `externalFunction(this.app.router)` otherwise, you could not reach it properly.\n- we can access `$nuxt.$router.push` in `actions`?","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":115,"estimatedTokens":734}}316{"id":"stack-53821094","source":"stackoverflow","questionId":53821094,"title":"How use Vue.set() in NuxtJs application?","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: How use Vue.set() in NuxtJs application?\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to set a property, by using Vue.set() in Nuxtjs application.\n\n```\neditPost(post) {\n Vue.$set(post, 'edit', true)\n}\n```\n\nGot error: *Vue is not defined*\n\n========================================\n\nTop Answer:\nSometimes you may want to assign a number of properties to an existing object, for example using Object.assign() or _.extend(). However, new properties added to the object will not trigger changes. In such cases, create a fresh object with properties from both the original object and the mixin object:\n\n// instead of `Object.assign(this.someObject, { a: 1, b: 2 })`\nthis.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })\n\n========================================\n\nCode:\n```text\neditPost(post) {\n Vue.$set(post, 'edit', true)\n}\n```\n\n```text\neditPost(post) {\n this.$set(post, 'edit', true)\n}\n```\n\n```text\nthis\n```\n\n```text\nVue.\n```\n\n```text\nObject.assign(this.someObject, { a: 1, b: 2 })\n```\n\n========================================\n\nComments:\n- `import Vue from 'vue'` at the top of `script`.\n- @DrewBaker in store you can use Vue.set","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":55,"estimatedTokens":296}}317{"id":"stack-76190074","source":"stackoverflow","questionId":76190074,"title":"How to add custom service worker to Nuxt 3 with vite-pwa?","tags":["nuxt.js","progressive-web-apps","vite","nuxt3.js"],"text":"Title: How to add custom service worker to Nuxt 3 with vite-pwa?\nTags: nuxt.js, progressive-web-apps, vite, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to glue together a Nuxt 3 PWA with `vite-plugin-pwa`, more specifically `@vite-pwa/nuxt`. I installed the module and set up basic configuration (I basically followed this video)\n\n### What I want\n\nThe first feature I would like to implement is sending Push Notifications to users at fixed time. They should receive the Push Notifications even if they are not in the app. That's why I added the PWA module.\n\n### What I do not understand\n\n**I don't know how to add my custom service worker.** If I understand it correctly, I could write a service worker, that just sends Push Notifications with the Notification API to my app. No need for services like OneSignal (right?).\n\nAs I understand the documentation Vite PWA uses google's workbox under the hood and per default it generates a service worker. If you set `injectRegister: 'script'` it should inject a service worker registration in the head of my app (like described here).\n\nNow when I search the source code via the developer tools I cannot find any serviceWorker script. Strangely enough, when I go to the application tab in the dev tools, I can see that a service worker `dev-sw.js` is registered. **How did this get added?**\n\n\n\nI think I have to set a mode in the configuration to tell workbox not to generate the service worker registration for me. This mode should be called injectManifest, as described here and here. But again, how do I add this to my code?\n\nAs suggested in the documentation I also had a look at the elk repo. But unfortunately they take a different approach and currently do not use vite-pwa/nuxt.\n\n**How can I add my custom service worker to send push notifications?**\n\n**Does anybody have experience with PWAs in Nuxt 3 and specifically working with service workers and sending Push Notifications?**\n\n========================================\n\nCode:\n```text\nvite-plugin-pwa\n```\n\n```text\n@vite-pwa/nuxt\n```\n\n```text\ninjectRegister: 'script'\n```\n\n```text\ndev-sw.js\n```\n\n```js\nimport { clientsClaim } from 'workbox-core'\nimport { precacheAndRoute, cleanupOutdatedCaches, createHandlerBoundToURL } from 'workbox-precaching';\nimport { registerRoute, NavigationRoute } from 'workbox-routing';\n\nself.skipWaiting();\nclientsClaim();\nprecacheAndRoute(self.__WB_MANIFEST);\ncleanupOutdatedCaches();\n\n//You can remove this code if you aren't precaching anything, or leave it in and live with the warning message\ntry {\n const handler = createHandlerBoundToURL('/');\n const route = new NavigationRoute(handler);\n registerRoute(route);\n} catch (error) {\n console.warn('Error while registering cache route', { error });\n}\n\n//Your service-worker code here.\n```\n\n```text\nvite-pwa\n```\n\n```text\n@vite-pwa/nuxt\n```\n\n```text\nworkbox-core\n```\n\n```text\nworkbox-precaching\n```\n\n```text\nworkbox-routing\n```\n\n```text\nsw.js\n```\n\n```text\npublic\n```\n\n```text\npwa.strategies\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\ninjectManifest\n```\n\n```text\n@vite-pwa/nuxt\n```\n\n```text\ndev-sw.js\n```\n\n```text\ndev-sw.js\n```\n\n```text\n@vite-pwa/nuxt\n```\n\n```text\npwa\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n/sw.js\n```\n\n========================================\n\nComments:\n- I have the same question. Did you find a solution for this?\n- Thanks for figuring this out - worked for me!\n- THANK YOU! I just spent all day trying to work this out, stumbling across this post was a small miracle. Many thanks! 🙏","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":144,"estimatedTokens":879}}318{"id":"stack-49866867","source":"stackoverflow","questionId":49866867,"title":"NUXT - Route with dynamic path - multiple parameters","tags":["nuxt.js"],"text":"Title: NUXT - Route with dynamic path - multiple parameters\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a route path like the below\n\n**path: '/board/:type(\\d{2}):subtype(\\d{2}):id(\\d+)'**\n\nso this is some thing like this\n\nhttp://localhost:3000/board/112233333333\n\nHere in the above case\n\n**11** is dynamic value for **type** ( max two digits )\n\n**22** is dynamic value for **sub type** ( max two digits )\n\n**33333333** is dynamic value for **id**.\n\nCould any one please let me know how do I create a folder structure for this one ? If not possible what is the best idea to handle this case ?\n\n========================================\n\nCode:\n```text\nexport default {\n validate ({ params }) {\n return /^([0-9]{12,12})$/.test(params.id)\n } \n}\n```\n\n```text\ncreated(){\n\n var _id = this.$route.params.id;\n var regex = /^([0-9]{2,2})([0-9]{2,2})([0-9]{8,8})$/;\n var contents = _id.match(regex);\n\n this.type = contents[1];\n this.subtype = contents[2];\n this.id = contents[3]; \n}\n```\n\n```text\n/* template code */\n<template>\n <section>\n <h3>in board _id</h3> \n <div>\n <div>type = {{type}}</div>\n <div>subtype = {{subtype}}</div>\n <div>id = {{id}}</div>\n <div>urlParam = {{$route.params}}</div>\n </div>\n </section>\n</template>\n\n/* script */\n<script>\nexport default {\n /* variables */\n data(){\n return{\n type : null,\n subtype : null,\n id : null\n }\n },\n /* route validation */\n validate ({ params }) {\n return /^([0-9]{12,12})$/.test(params.id)\n },\n /* extracting url params */\n created(){\n var _id = this.$route.params.id;\n var regex = /^([0-9]{2,2})([0-9]{2,2})([0-9]{8,8})$/;\n var contents = _id.match(regex);\n this.type = contents[1];\n this.subtype = contents[2];\n this.id = contents[3]; \n }\n}\n</script>\n```\n\n```text\nhttp://localhost:3000/board/112233333333\n```\n\n```text\nvalidate()\n```\n\n```text\n_id.vue\n```\n\n```text\nvalidate()\n```\n\n```text\nparams.id\n```\n\n```text\nvalidate()\n```\n\n```text\n112233333333\n```\n\n```text\n/^([0-9]{12,12})$/.test(params.id)\n```\n\n```text\ntrue\n```\n\n```text\nfalse\n```\n\n```text\ntrue\n```\n\n```text\nfalse\n```\n\n```text\ncreated()\n```\n\n```text\nthis.$route.params.id\n```\n\n```text\nthis.$route.params.id\n```\n\n```text\ncontents[0]\n```\n\n```text\n_id.vue\n```\n\n========================================\n\nComments:\n- Thanks for your answer . Last value \"33333333\" length is not fixed . Sorry I didn't mention it in the question . It has dynamic length from size 1 to Max integer size . But you gave me idea for the implementation . Do you have any quick fix for the last one ?\n- try this regex /^([0-9]{2,2})([0-9]{2,2})([0-9]{1})$/; -- this will expect the last match to have minimum length 1 and maximum is as you wish.\n- Thank You divine for the solution .\n- small correction , right regular expression is /^([0-9]{2,2})([0-9]{2,2})([0-9]{1,99})$/","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":164,"estimatedTokens":739}}319{"id":"stack-49952420","source":"stackoverflow","questionId":49952420,"title":"How to use * (asterisk) in NuxtJs route?","tags":["vue.js","vuejs2","vue-router","nuxt.js"],"text":"Title: How to use * (asterisk) in NuxtJs route?\nTags: vue.js, vuejs2, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn a normal Vue (not Nuxt) project generated by vue-cli, using `*` in vue-router like this works:\n\n```\nexport default new Router({\n routes: [\n {\n path: \"/about\",\n name: \"about\",\n component: About,\n children: [\n {\n path: \"*\",\n component: About\n }\n ]\n }\n ]\n});\n```\n\nAll these routes works:\n\n- `/about`\n\n- `/about/123`\n\n- `/about/123/abc/123/abc`\n\nIs there a way to do this in NuxtJs ? In Nuxt, routes are generated automatically from the files in `pages` folder. but `*` is an invalid character for file/folder name.\n\n========================================\n\nCode:\n```js\nexport default new Router({\n routes: [\n {\n path: \"/about\",\n name: \"about\",\n component: About,\n children: [\n {\n path: \"*\",\n component: About\n }\n ]\n }\n ]\n});\n```\n\n```text\n*\n```\n\n```text\n/about\n```\n\n```text\n/about/123\n```\n\n```text\n/about/123/abc/123/abc\n```\n\n```text\npages\n```\n\n```text\n*\n```\n\n```text\n-| pages/\n---| index.vue\n---| users-[group]/\n-----| [id].vue\n```\n\n```text\n/users-[group]/[id].vue\n```\n\n```text\npages/about/_.vue\n```\n\n```text\npages/about/_/abc/_/abc.vue\n```\n\n```text\n_\n```\n\n```text\n[var]\n```\n\n```text\nroute.params.var\n```\n\n```text\nroute.params.id\n```\n\n```text\n_\n```\n\n```text\n/about/*\n```\n\n```text\nabout/123/abc/123/abc\n```\n\n========================================\n\nComments:\n- thanks. it works . may i know how did you know this? i can't seem to find it anywhere\n- @JacobGoh Sorry, I don't know. Nuxt documentation is terrible, I've just worked with Nuxt for awhile now.\n- @JacobGoh Found it in the documentation, it's not super clear, but you can see an example here\n- Thanks. I'm actually asking this question because I am curious about how to solve this question stackoverflow.com/questions/49951479/… . I think ur method would solve the problem and you can answer it.\n- @Ohgodwhy how to achieve this in Nuxt 3?\n- @devzakir Updated for Nuxt 3.\n- In Nuxt 3 the catchall syntax is `[...].vue`","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":137,"estimatedTokens":519}}320{"id":"stack-59752101","source":"stackoverflow","questionId":59752101,"title":"Detect click outside element in nuxt","tags":["nuxt.js"],"text":"Title: Detect click outside element in nuxt\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a nuxt project. I need to write a click-outside directive by which I can detect outside clicks of elements to close them. How can I implement it?\n\n========================================\n\nTop Answer:\nThis is a common JS issue, you can try to solve it with this: https://stackoverflow.com/a/36696086/4239703\n\nYou can register the handler on mounted() lifecycle hook for example.\n\n========================================\n\nCode:\n```js\nimport Vue from 'vue';\n\nVue.directive('click-outside', {\n bind: function (el, binding, vnode) {\n el.clickOutsideEvent = function (event) {\n // here I check that click was outside the el and his childrens\n if (!(el == event.target || el.contains(event.target))) {\n // and if it did, call method provided in attribute value\n vnode.context[binding.expression](event);\n }\n };\n document.body.addEventListener('click', el.clickOutsideEvent)\n },\n unbind: function (el) {\n document.body.removeEventListener('click', el.clickOutsideEvent)\n },\n});\n```\n\n```js\n<div v-click-outside=\"closeDropdown\"></div>\n```\n\n```text\nimport Vue from 'vue'\n \nVue.directive('click-outside', {\n bind: function (el, binding, vnode) {\n el.clickOutsideEvent = function (event) {\n // here I check that click was outside the el and his children\n if (!(el == event.target || el.contains(event.target))) {\n // and if it did, change data from directive\n vnode.context.isDropdwonMenuVisible = false;\n }\n };\n document.body.addEventListener('click', el.clickOutsideEvent)\n },\n unbind: function (el) {\n document.body.removeEventListener('click', el.clickOutsideEvent)\n },\n});\n\n\n<a v-click-outside>Link</a>\n\n\ndata() {\n return {\n isDropdwonMenuVisible: true,\n };\n },\n```\n\n```text\nplugins: [\n '~/plugins/click-outside.js'\n]\n```\n\n```text\nv-on:focusout=\"\"\n```\n\n========================================\n\nComments:\n- Actually I editted it before the answer. So I don't see any problem here. The answer is voted towice after editing the question. But thanks for informing me. I double checked it\n- actually I would like to make it like a directive to use it in different components.\n- This is giving me the error: ``` v-click-outside.js?015b:9 Uncaught TypeError: vnode.context[binding.expression] is not a function at HTMLBodyElement.el.clickOutsideEvent ```\n- It is maybe worth mentioning: If the element targeted with the \"v-click-outside\" directive contains a , that click handler needs the .stop modifier to make it \"stopPropagation\", like so . Otherwise this will not work correctly.","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":88,"estimatedTokens":669}}321{"id":"stack-74038573","source":"stackoverflow","questionId":74038573,"title":"Can we use Nuxt as SPA only?","tags":["vue.js","nuxt.js","single-page-application","nuxt3.js"],"text":"Title: Can we use Nuxt as SPA only?\nTags: vue.js, nuxt.js, single-page-application, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am currently using Angular + nodejs as my main tech stack...\n\nI am interested in Vue, had a few simple projects with that, and saw a few videos about Nuxt3.\nDoes Nuxt3 support SPA applications (with nodejs API), or not?\n\nIf not, will it support SPA in the future?\n\n========================================\n\nCode:\n```js\ndefineNuxtConfig({\n ssr: false\n})\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- But what command do you need for creating the spa? `$ npm run generate` or `$ npm run build`?\n- @katerlouis `build` is for an SSR app, since SPA can be fully static you don't need a server to render it on demand. The good one to use is `generate` (it will build it at build-time when pushing your code).\n- But the generate command will generate all pages file to html, this is more like SSG than SPA. With SPA mode, we only need 01 file `index.html`, not all route pages.","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":31,"estimatedTokens":261}}322{"id":"stack-60308981","source":"stackoverflow","questionId":60308981,"title":"Refresh required to detect authentication state using nuxt auth module","tags":["vue.js","vuejs2","vuex","nuxt.js"],"text":"Title: Refresh required to detect authentication state using nuxt auth module\nTags: vue.js, vuejs2, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nMy app is unable to detect the state change that occurs when a user logs in without completely refreshing the page. Upon refreshing everything displays correctly. I am using Nuxt and its included auth module documented here - https://auth.nuxtjs.org/.\n\nHere is the v-if statement that is unable to detect the state change:\n\n```\n\n \n Hello, {{ $auth.$state.user.name }}\n \n \n \n \n Sign In\n \n \n```\n\nHere is the login method in my login page.\n\n```\nmethods: {\n async onLogin() {\n try{\n\n this.$auth.loginWith(\"local\", {\n data: {\n email: this.email,\n password: this.password\n }\n });\n\n this.$router.push(\"/\");\n\n }catch(err){\n console.log(err);\n }\n\n }\n }\n```\n\nI tried fetching the state via a computed property but got the same result. I can see the vuex store data change to indicate I am correctly logged in/out in the 'Application' tab in Chrome Dev Tools but the Vue Dev seems to constantly indicate I'm logged in.. Not sure if its just buggy though..\n\nI also encounter the same problem in reverse when logging out. Here's the method:\n\n```\nasync onLogout() {\n try{\n await this.$auth.logout();\n }catch(err){\n console.log(err);\n }\n}\n```\n\nI am happy to provide further details.\n\n========================================\n\nTop Answer:\nSometimes Vue's reactivity system falls short and you just need to manually trigger a re-render and the simplest way to do so is by wrapping your function logic in `setTimeout()`\n\n```\nsetTimeout(async () => {\n await this.$auth.logout();\n}, 0);\n```\n\n========================================\n\nCode:\n```text\n<template v-if=\"$auth.$state.loggedIn\">\n <nuxt-link\n to=\"/profile\"\n >\n Hello, {{ $auth.$state.user.name }}\n </nuxt-link>\n </template>\n <template v-else>\n <nuxt-link\n to=\"/logIn\"\n >\n Sign In\n </nuxt-link>\n </template>\n```\n\n```text\nmethods: {\n async onLogin() {\n try{\n\n this.$auth.loginWith(\"local\", {\n data: {\n email: this.email,\n password: this.password\n }\n });\n\n this.$router.push(\"/\");\n\n }catch(err){\n console.log(err);\n }\n\n }\n }\n```\n\n```text\nasync onLogout() {\n try{\n await this.$auth.logout();\n }catch(err){\n console.log(err);\n }\n}\n```\n\n```text\nexport const getters = {\n isAuthenticated(state) {\n return state.auth.loggedIn\n },\n loggedInUser(state) {\n return state.auth.user\n },\n};\n```\n\n```text\nstore/index.js\n```\n\n```text\nmiddleware: 'auth'\n```\n\n```text\nimport { mapGetters } from 'vuex'\n```\n\n```text\n...mapGetters(['isAuthenticated', 'loggedInUser']),\n```\n\n```js\nsetTimeout(async () => {\n await this.$auth.logout();\n}, 0);\n```\n\n```text\nsetTimeout()\n```\n\n========================================\n\nComments:\n- This does not solve the problem that if you clear out the cookies and localstorage and click a few more pages in the app under SPA, it does not check authentication again, therefore logged out users are still accessing pages they should not.\n- Actually it does , if you are using middleware:auth and the mapGetters in some layout and uses this layout for all auth pages it checks if you're authenticated for all these pages ubder this middleware when visited . there for when deleting the localstotage it redirect you back to login page but you should define the auth stratigy in nuxt.config.js\n- I know I'm nearly 3 years late but isAuthenticated is still returning true when I'm logged out. I logged in, opened the app in two tabs and when I logged out of one the other doesn't get logged out and can process axios requests until I've refreshed the page.","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":168,"estimatedTokens":925}}323{"id":"stack-57358490","source":"stackoverflow","questionId":57358490,"title":"How to use nuxt-link tag in Buefy?","tags":["nuxt.js","bulma","buefy"],"text":"Title: How to use nuxt-link tag in Buefy?\nTags: nuxt.js, bulma, buefy\nSource: Stack Overflow\n\nQuestion:\nIn Buefy navBar component item element have\n\n```\n\n job\n\n```\n\nIt render standart `a` html tag. When clicked, page reloaded. I want use `nuxt-link` Nuxt tag whithout reloading page.\n\nThis code works, but i got broken css design Bulma navbar.\n\n```\n\n \n Job\n \n\n```\n\n========================================\n\nCode:\n```text\n<b-navbar-item href=\"/job\">\n job\n</b-navbar-item>\n```\n\n```text\n<b-navbar-item >\n <nuxt-link to=\"/job\">\n Job\n </nuxt-link>\n</b-navbar-item>\n```\n\n```text\na\n```\n\n```text\nnuxt-link\n```\n\n```text\n<nuxt-link to=\"/job\" class=\"navbar-item\">\n Job\n</nuxt-link>\n```\n\n```text\n<b-navbar-item tag=\"nuxt-link\" to=\"/job\">\n job\n</b-navbar-item>\n```\n\n```text\ntag\n```\n\n========================================\n\nComments:\n- which one better? or whatever?\n- None is better than the other. It's a question of preference. If you need functionality of buefy navbar, go with it. This component is well written. If you don't need some many functionalities, you can go with your own implementation...","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":71,"estimatedTokens":281}}324{"id":"stack-75823927","source":"stackoverflow","questionId":75823927,"title":"Custom Auto Imports in Nuxt 3 (Auto Import Pinia Store)","tags":["vue.js","nuxt.js","nuxt3.js","pinia"],"text":"Title: Custom Auto Imports in Nuxt 3 (Auto Import Pinia Store)\nTags: vue.js, nuxt.js, nuxt3.js, pinia\nSource: Stack Overflow\n\nQuestion:\nIs there a way to set custom auto imports in Nuxt 3? I use Pinia and my stores are in the root directory under /stores.\nFor example, if I want to use the store from /stores/auth.store.ts in a component, I always have to import the store like this:\n\n`import { useCourseStore } from '~~/stores/course.store';`.\n\n========================================\n\nTop Answer:\nTristan's Answer pointed in the right direction, in the meantime the nuxt.config.ts syntax has changed a little:\n\n```\n// nuxt.config.ts\nexport default defineNuxtConfig({\n // ... other options\n modules: ['@pinia/nuxt'],\n pinia: {\n storesDirs: ['./stores/**', './custom-folder/stores/**'],\n },\n})\n```\n\nSource: https://pinia.vuejs.org/ssr/nuxt.html#auto-imports\n\n========================================\n\nCode:\n```text\nimport { useCourseStore } from '~~/stores/course.store';\n```\n\n```text\nexport default defineNuxtConfig({\n // your config...\n modules: [\n [\n '@pinia/nuxt',\n { autoImports: ['defineStore'] },\n ],\n ],\n});\n```\n\n```text\nexport default defineNuxtConfig({\n // your config\n imports: {\n dirs: ['stores'],\n },\n});\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n// nuxt.config.ts\nexport default defineNuxtConfig({\n // ... other options\n modules: ['@pinia/nuxt'],\n pinia: {\n storesDirs: ['./stores/**', './custom-folder/stores/**'],\n },\n})\n```\n\n========================================\n\nComments:\n- The Docs say \"It also automatically imports all stores defined withing your stores folder.\" but my Store is not found out of the box 🤔\n- Just me being curious (and also frustrated after couple of days tryna find reason why nuxt.config.ts > pinia > autoImports was not longer working after upgrading my nuxt version): How did you realize it had been moved to the modules apart? I haven't been able to find a trace of clue at the nuxt official docs.","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":76,"estimatedTokens":494}}325{"id":"stack-51523175","source":"stackoverflow","questionId":51523175,"title":"Using Vuex with Nuxt and Vue-Native-Websocket","tags":["vue.js","vuex","nuxt.js"],"text":"Title: Using Vuex with Nuxt and Vue-Native-Websocket\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to fill my vuex store with data from websocket. I'm using Nuxt. For handling websocket I'm using vue-native-websocket package. Connection to websocket is successful, but commiting to the store doesn't work, it fires an error on every socket event `Uncaught TypeError: this.store[n] is not a function`\n\nAccording to Nuxt and vue-native-websocket docs, I've using them as following:\n\nPlugin native-websocket.js:\n\n```\nimport Vue from 'vue'\nimport VueNativeSock from 'vue-native-websocket'\nimport store from '~/store'\n\nVue.use(VueNativeSock, 'wss://dev.example.com/websocket/ws/connect', { store: store })\n```\n\nnuxt.config.js\n\n```\nplugins: [\n {src: '~plugins/native-websocket.js', ssr: false}\n],\n```\n\nAs the connection is established, I draw a conclusion that the package is connected right, so it's something about store and I can't get what's wrong\n\nUPD: After some workaround I've found out that logging store inside native-websocket.js returns \n\n```\nstore() {\n return new __WEBPACK_IMPORTED_MODULE_1_vuex__[\"default\"].Store({\n state: {...my store\n```\n\nand commiting to it returns `__WEBPACK_IMPORTED_MODULE_2__store__.default.commit is not a function`\nSo it's something about webpack as I can see\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\nimport VueNativeSock from 'vue-native-websocket'\nimport store from '~/store'\n\nVue.use(VueNativeSock, 'wss://dev.example.com/websocket/ws/connect', { store: store })\n```\n\n```text\nplugins: [\n {src: '~plugins/native-websocket.js', ssr: false}\n],\n```\n\n```text\nstore() {\n return new __WEBPACK_IMPORTED_MODULE_1_vuex__[\"default\"].Store({\n state: {...my store\n```\n\n```text\nUncaught TypeError: this.store[n] is not a function\n```\n\n```text\n__WEBPACK_IMPORTED_MODULE_2__store__.default.commit is not a function\n```\n\n```text\nimport Vue from 'vue'\nimport VueNativeSock from 'vue-native-websocket'\n\nexport default ({ store }, inject) => {\n Vue.use(VueNativeSock, 'wss://dev.example.com/websocket/ws/connect', { store: store })\n}\n```\n\n========================================\n\nComments:\n- Use a callback as the 3rd argument instead, `passToStoreHandler: function (eventName, event) {`, inside of here log out `this.store` what is the value\n- @Ohgodwhy I've tried just now, console is clear, callback doesn't fire `{ passToStoreHandler: function(eventName, event) { console.log(this.store); console.log('test') }}`\n- @Ohgodwhy Sorry, I've forgot pass the store to that object. Now console.log returns my `store()`, but there is no error only if callback is passed to third argument object. No commits are made to store anyway\n- Maybe try building the commit yourself and committing to the store. Does that work?\n- @Ohgodwhy Tried `this.store.commit('incrementCounter')` inside of `passToStoreHandler`. Got `this.store.commit is not a function`","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":88,"estimatedTokens":734}}326{"id":"stack-51040586","source":"stackoverflow","questionId":51040586,"title":"Adding js files to nuxt config","tags":["webpack","vue.js","requirejs","config","nuxt.js"],"text":"Title: Adding js files to nuxt config\nTags: webpack, vue.js, requirejs, config, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSomeone designed the front end of my web page and now I am trying to use all the .css and .js files globally for all my pages in nuxtjs. But I am failing to include the files correctly. \n\nThis is one of the files I am trying to include: *jquery.themepunch.tools.min.js*. I get this error:\n\n`{\n statusCode: 404, \n path: '/~/assets/revolution/js/jquery.themepunch.tools.min.js',\n message: 'This page could not be found' \n}`\n\nI added the path to the file into my nuxt.js.config, but I can't figure out what I am missing here. Here is my config file:\n\n```\nconst webpack = require('webpack')\n\nmodule.exports = {\n head: {\n title: 'test-webpage',\n\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: 'test page' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ],\n script: [\n {src: '~/assets/revolution/js/jquery.themepunch.tools.min.js'}\n ]\n },\n\n build: {\n vendor: ['jquery', 'bootstrap'],\n plugins: [\n // set shortcuts as global for bootstrap\n new webpack.ProvidePlugin({\n $: 'jquery',\n jQuery: 'jquery',\n 'window.jQuery': 'jquery'\n })\n ]\n },\n}\n```\n\n========================================\n\nCode:\n```text\nconst webpack = require('webpack')\n\nmodule.exports = {\n head: {\n title: 'test-webpage',\n\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: 'test page' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ],\n script: [\n {src: '~/assets/revolution/js/jquery.themepunch.tools.min.js'}\n ]\n },\n\n build: {\n vendor: ['jquery', 'bootstrap'],\n plugins: [\n // set shortcuts as global for bootstrap\n new webpack.ProvidePlugin({\n $: 'jquery',\n jQuery: 'jquery',\n 'window.jQuery': 'jquery'\n })\n ]\n },\n}\n```\n\n```text\n{\n statusCode: 404, \n path: '/~/assets/revolution/js/jquery.themepunch.tools.min.js',\n message: 'This page could not be found' \n}\n```\n\n```text\n{ src: '/urpathinsidestaticfolder/jquery.themepunch.tools.min.js' }\n```\n\n========================================\n\nComments:\n- Hey Are you able to use jquery plugins in nuxtJS? I'm trying adding bxslider, and I added all CSS nad JS. but the getting bxslider is not a function. even the script is added into the page. I tried calling the plugin from console and it works.. I added my count into mounted function.. Any clue is much appreaciated\n- Never thought of considering ~ as an alias in this context. Thank you. Solved my problem.\n- @Aldarund, what if my nuxt app is supporting build for several themes and I need to include some scripts for one theme and for other build with a different theme and need different scripts? Does that means that every build will include everything that is located in static folder?\n- @31415926 if u add reference to.it into nuxt config then yes. Basically it just adds script tag to that file in your static folder and that's all\n- @Aldarund, thx man. I have another question though: If I use head in config to include a static js file it would be imported in the page first and only after that all other scripts like vendors and app... my problem is that my script controls bootstrap theme and requires jquery but jquery is included after my script (I assume bootstrap-vue module does it) How to deal with that?\n- @31415926 bootstrap Vue don't use jquery","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":109,"estimatedTokens":907}}327{"id":"stack-74949150","source":"stackoverflow","questionId":74949150,"title":"images from static folder in nuxt 3 doesn't show","tags":["vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: images from static folder in nuxt 3 doesn't show\nTags: vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt 3\n\nand this is directories structure\n\nhttps://i.sstatic.net/k09i3.png\n\nimages are loaded like this\n\n```\n\n```\n\nI've also tried (start without `/` )\n\n```\n\n```\n\nand it didn't worked again\n\nWhat's the problem ?\n\n========================================\n\nCode:\n```text\n<img src=\"/images/index/pic-left.svg\" />\n```\n\n```text\n<img src=\"images/index/pic-left.svg\" />\n```\n\n```text\n/\n```\n\n```text\npublic\n```\n\n```text\nstatic\n```\n\n```text\n/images/index/pic-left.svg\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":53,"estimatedTokens":151}}328{"id":"stack-68308060","source":"stackoverflow","questionId":68308060,"title":"How to use Nuxt $auth inside an axios plugin (How to add Token to all axios requests)","tags":["authentication","plugins","axios","nuxt.js"],"text":"Title: How to use Nuxt $auth inside an axios plugin (How to add Token to all axios requests)\nTags: authentication, plugins, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIm looking to use $auth inside my Nuxt project, specially inside an axios plugin.\n\nHere is my code:\n\n**plugins/api.js**\n\n```\nexport default function ({ $axios }, inject) {\n const api = $axios.create({\n headers: {\n common: {\n Accept: 'text/plain, */*',\n },\n },\n })\n\n // Set baseURL to something different\n api.setBaseURL('http://localhost:4100/')\n\n // Inject to context as $api\n inject('api', api)\n}\n```\n\nNow the problem comes when I try to use $auth from @nuxtjs/auth-next package.\n\nAs stated in the docs:\n\nThis module globally injects $auth instance, meaning that you can\naccess it anywhere using this.$auth. For plugins, asyncData, fetch,\nnuxtServerInit and Middleware, you can access it from context.$auth.\n\nI tried the following:\n\nThis results in $auth being undefined\n\nexport default function ({ $axios, $auth }, inject) {\n\nThis one was near\n\nexport default function ({ $axios, app }, inject) {\nconsole.log(app) //This one logs $auth in the object logged\nconsole.log(app.$auth) // I don't understand why but this one returns undefined\n\nMy main goal here is to make use of `this.$auth.strategy.token.get()`and pass it (if the token exists of course) to the headers of every request made using this.$api\n\nI have been looking for similar questions and answers but none has helped me to solve this, I could just add the token every time I write this.$api but that would increase the code unnecessarily.\n\nThanks in advance to all the people for your time and help.\n\n**EDIT:**\n\nOkay, now I made a test. and the next code is actually logging the $auth object correctly, it seems some time is needed to make it work but now Im afraid that using setTimeout could cause an error because I can't know exactly how much time is needed for $auth to be available.\n\n```\nexport default function ({ $axios, app }, inject) {\n setTimeout(() => {\n console.log('After timeout', app.$auth)\n }, 50)\n```\n\n**EDIT 2:**\n\nSo now I have made more tests, and using 0 milliseconds instead of 50 works too, so I will use setTimeout with 0 milliseconds for now, I hope anyone find a better solution or explain why $auth is not available before using setTimeout so I can decide what to do with my code.\n\n**EDIT 3:**\n\nAfter trying to wrap all my previous code inside setTimeout I noticed that the code fails, so that isn't a solution.\n\n========================================\n\nTop Answer:\nAlso Nuxt Auth itself has provided a solution for this issue:\nhttps://auth.nuxtjs.org/recipes/extend/\n\n========================================\n\nCode:\n```text\nexport default function ({ $axios }, inject) {\n const api = $axios.create({\n headers: {\n common: {\n Accept: 'text/plain, */*',\n },\n },\n })\n\n // Set baseURL to something different\n api.setBaseURL('http://localhost:4100/')\n\n // Inject to context as $api\n inject('api', api)\n}\n```\n\n```text\nexport default function ({ $axios, app }, inject) {\n setTimeout(() => {\n console.log('After timeout', app.$auth)\n }, 50)\n```\n\n```text\nthis.$auth.strategy.token.get()\n```\n\n```text\nexport default function ({ $axios, app }, inject) {\n // At this point app.$auth is undefined. (Unless you use setTimeout but that is not a solution)\n\n //Create axios instance\n const api = $axios.create({\n headers: {\n common: {\n Accept: 'application/json', //accept json\n },\n },\n })\n // Here is the magic, onRequest is an interceptor, so every request made will go trough this, and then we try to access app.$auth inside it, it is defined\n api.onRequest((config) => {\n // Here we check if user is logged in\n if (app.$auth.loggedIn) {\n // If the user is logged in we can now get the token, we get something like `Bearer yourTokenJ9F0JFODJ` but we only need the string without the word **Bearer**, So we split the string using the space as a separator and we access the second position of the array **[1]**\n\n const token = app.$auth.strategy.token.get().split(' ')[1]\n api.setToken(token, 'Bearer') // Here we specify the token and now it works!!\n }\n })\n\n // Set baseURL to something different\n api.setBaseURL('http://localhost:4100/')\n\n // Inject to context as $api\n inject('api', api)\n}\n```\n\n========================================\n\nComments:\n- Try `store.$auth`\n- @kissu thanks for your reply. I have tried it and its undefined, when I log store it is showing that is has the $auth property but when I try to access it, it is undefined. So it's the same problem again.\n- This was extremely helpful thank you! I ran into some issues, but also I managed to do this without having to inject a new instance. Using the `this.$axios` from my VueX frontend store code worked. I also had to make sure that my plugin was client-side by naming it with `.client.js` instead of just `.js`. And that the plugin was listed in both nuxt's top level plugins config AND in the `auth.plugins` array in the nuxt.config file.","metadata":{"transformedAt":"2026-08-18T18:33:07.857Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":149,"estimatedTokens":1264}}329{"id":"stack-69837637","source":"stackoverflow","questionId":69837637,"title":"Dynamic assets in Nuxt / vite","tags":["javascript","nuxt.js","require","vite"],"text":"Title: Dynamic assets in Nuxt / vite\nTags: javascript, nuxt.js, require, vite\nSource: Stack Overflow\n\nQuestion:\nI can load images dynamically from a folder in Nuxt (+ webpack) simply with a method like:\n\n```\ngetServiceIcon(iconName) {\n return require ('../../static/images/svg/services/' + iconName + '.svg');\n}\n```\n\nI moved to Vite, and `require` is not defined here (using rollup). How can I solve this, with nuxt / vite? Any idea?\n\n========================================\n\nCode:\n```text\ngetServiceIcon(iconName) {\n return require ('../../static/images/svg/services/' + iconName + '.svg');\n}\n```\n\n```text\nrequire\n```\n\n```js\nconst getServiceIcon = async iconName => {\n const module = await import(/* @vite-ignore */ `../../static/images/svg/services/${iconName}.svg`)\n return module.default.replace(/^\\/@fs/, '')\n}\n```\n\n```text\nimport()\n```\n\n========================================\n\nComments:\n- You're using Nuxt3? github.com/nuxt/framework/discussions/868\n- Nope, 2.15.8. Ty, looking into it tho.\n- Then, you can maybe ask your question down in the related repo: github.com/nuxt/vite/issues?q=is%3Aissue+images+\n- Facing this error - `Uncaught (in promise) TypeError: Failed to fetch dynamically imported module`\n- Why the @vite-ignore ?\n- @Tofandel To prevent the asset from being automatically bundled.","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":48,"estimatedTokens":328}}330{"id":"stack-71249845","source":"stackoverflow","questionId":71249845,"title":"nuxt build vs generate","tags":["vue.js","nuxt.js","server-side-rendering"],"text":"Title: nuxt build vs generate\nTags: vue.js, nuxt.js, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nI'm not sure when to use what.\n\nwith `nuxt build` you get two directories(`client` & `server`) that means you are actually deploying node.js server(i.e. express, right?)\n\nwith `nuxt generate` you get `.html`\n\nIt seems both ways you can have good SEO which nuxt aims at. And to me, `nuxt generate` option seems more consize since it doesn't envolve server.\n\nWhat am I missing here? Why should I use `nuxt build` and get server code mixed up?\n\n========================================\n\nCode:\n```text\nnuxt build\n```\n\n```text\nclient\n```\n\n```text\nserver\n```\n\n```text\nnuxt generate\n```\n\n```text\n.html\n```\n\n```text\nnuxt generate\n```\n\n```text\nnuxt build\n```\n\n```text\nnuxt build\n```\n\n```text\nnuxt generate\n```\n\n========================================\n\nComments:\n- Does this answer your question? What's the real difference between target: 'static' and target: 'server' in Nuxt 2.14 universal mode?\n- as an addition you can say that nuxt generate will not exist anymore from nuxt 3 on. github.com/nuxt/framework/discussions/515\n- in nuxt.config.ts add \"ssr: false, target: 'static' \", and then use nuxt generate","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":60,"estimatedTokens":303}}331{"id":"stack-66421096","source":"stackoverflow","questionId":66421096,"title":"How to use JQuery in Nuxt.js","tags":["jquery","vue.js","nuxt.js"],"text":"Title: How to use JQuery in Nuxt.js\nTags: jquery, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\ni want to use JQuery in function computed() in my component:\n\n```\ncomputed: {\n bgStyle() {\n var $bg_wr = $('.bg-wr'),\n }\n}\n```\n\nFor this in nuxt.config.js i tried to connect JQuery:\n\n```\nhead: {\n script: [\n { src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js' },\n ]\n}\n```\n\nBut it doesn't work. I get error '$ is not defined'.\nWhat i do wrong?\n\n========================================\n\nTop Answer:\nin Nuxt3\n\nFirst you need to install jquery in your project\n\n```\nnpm i jquery\n```\n\nThen in the file `~/plugins/jquery.js` add the following codes:\n\n```\nimport $ from 'jquery'\nwindow.jQuery = window.$ = $\nexport default jQuery;\n```\n\nAnd finally add the following code to the `nuxt.config.ts`\n\n```\nplugins: [\n { src: \"~/plugins/jquery\", mode: \"client\" },\n],\n```\n\nSample\n\n```\n\nonMounted(()=>{\n console.log($('body'));\n})\n\n```\n\n========================================\n\nCode:\n```text\ncomputed: {\n bgStyle() {\n var $bg_wr = $('.bg-wr'),\n }\n}\n```\n\n```text\nhead: {\n script: [\n { src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js' },\n ]\n}\n```\n\n```text\nmethod\n```\n\n```text\nnpm i jquery\n```\n\n```text\nimport $ from 'jquery'\nwindow.jQuery = window.$ = $\nexport default jQuery;\n```\n\n```text\nplugins: [\n { src: \"~/plugins/jquery\", mode: \"client\" },\n],\n```\n\n```text\n<script setup>\nonMounted(()=>{\n console.log($('body'));\n})\n</script>\n```\n\n```text\n~/plugins/jquery.js\n```\n\n```text\nnuxt.config.ts\n```\n\n========================================\n\nComments:\n- No worries. Also it's generally not necessary / helpful / good to use jQuery with Vue/Nuxt unless it's absolutely necessary. For example, if you need to use some existing library\n- @shob yes i agree with you, but i use slider :(\n- You have a lot of sliders in the non-jquery environment tbh. Here are a few: github.com/vuejs/awesome-vue#slider Those are standalone, I will not even talk about the CSS frameworks that have some backed into them like Boostrap, Buefy, Vuetify and so on... Drop jQuery and use some JS/Vue ones. :)","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":126,"estimatedTokens":534}}332{"id":"stack-75862614","source":"stackoverflow","questionId":75862614,"title":"How to auto import pinia stores in nuxt","tags":["vue.js","nuxt.js","pinia"],"text":"Title: How to auto import pinia stores in nuxt\nTags: vue.js, nuxt.js, pinia\nSource: Stack Overflow\n\nQuestion:\nCurrently I am doing something like this to import stores in components\n\n```\nimport { useSomeStore } from \"~/store/someStore\";\nconst store = useSomeStore();\n```\n\nWhat I would like to achieve is skip the import and just use the store\n\nWhat I have done is add\n\n```\n// nuxt.config.ts\nmodules: [\n [\n \"@pinia/nuxt\",\n {\n autoImports: [\"defineStore\", \"acceptHMRUpdate\"],\n },\n ],\n],\nimports: {\n dirs: [\"stores\"],\n},\n```\n\nin my nuxt config but I'm still getting useSomeStore is undefined, what am I doing wrong in this case?\n\nThe store:\n\n```\n// store/someStore.ts\nexport const useSomeStore = defineStore(\"some-store\", {\n state: () => ({ hello: \"there\" }),\n});\n```\n\n========================================\n\nTop Answer:\nI tried everything but none of them worked,\nthe only way it worked for me was adding them as presets to nuxt.config file.\n\n### Here is an example\n\nAdd your stores like code below to `nuxt.config.ts` :\n\n```\nexport default defineNuxtConfig({ \n imports: {\n presets: [\n {\n from: '~~/stores/aaa',\n imports: ['useAaaStore']\n },\n {\n from: '~~/stores/bbb',\n imports: ['useBbbStore']\n },\n {\n from: '~~/stores/ccc',\n imports: ['useCccStore']\n }\n ] \n }\n})\n```\n\nthen you can use stores inside any .vue file without importing them.\n\n========================================\n\nCode:\n```text\nimport { useSomeStore } from \"~/store/someStore\";\nconst store = useSomeStore();\n```\n\n```text\n// nuxt.config.ts\nmodules: [\n [\n \"@pinia/nuxt\",\n {\n autoImports: [\"defineStore\", \"acceptHMRUpdate\"],\n },\n ],\n],\nimports: {\n dirs: [\"stores\"],\n},\n```\n\n```text\n// store/someStore.ts\nexport const useSomeStore = defineStore(\"some-store\", {\n state: () => ({ hello: \"there\" }),\n});\n```\n\n```text\nimport { useSomeStore } from \"~/store/someStore\";\n```\n\n```text\nimports: {\n dirs: ['stores']\n}\n```\n\n```js\nexport default defineNuxtConfig({\n modules: [\n [\n \"@pinia/nuxt\",\n {\n autoImports: [\"defineStore\", \"acceptHMRUpdate\"],\n },\n ],\n ],\n imports: {\n dirs: ['store']\n }\n});\n```\n\n```text\n/store\n```\n\n```text\n/stores\n```\n\n```text\n/store\n```\n\n```text\n/stores\n```\n\n```text\n// nuxt.config.ts\nexport default defineNuxtConfig({\n // ... other options\n modules: ['@pinia/nuxt'],\n pinia: {\n storesDirs: ['./stores/**', './custom-folder/stores/**'],\n },\n})\n```\n\n```text\n@pinia/nuxt\n```\n\n```text\nusePinia()\n```\n\n```text\ngetActivePinia()\n```\n\n```text\ndefineStore()\n```\n\n```text\nstoreToRefs()\n```\n\n```text\nacceptHMRUpdate()\n```\n\n```text\nstores\n```\n\n```text\nstoresDirs\n```\n\n```text\nsrcDir\n```\n\n```text\nexport default defineNuxtConfig({ \n imports: {\n presets: [\n {\n from: '~~/stores/aaa',\n imports: ['useAaaStore']\n },\n {\n from: '~~/stores/bbb',\n imports: ['useBbbStore']\n },\n {\n from: '~~/stores/ccc',\n imports: ['useCccStore']\n }\n ] \n }\n})\n```\n\n```text\nnuxt.config.ts\n```\n\n```bash\nnpm run dev\n```\n\n```json\n\"dependencies\": {\n \"@pinia/nuxt\": \"^0.9.0\",\n \"nuxt\": \"^3.15.0\",\n \"pinia\": \"^2.3.0\",\n \"vue\": \"latest\",\n \"vue-router\": \"latest\"\n }\n```\n\n```text\nuseSomeStore\n```\n\n```text\nuseSometore\n```\n\n```text\nuseOtherStore\n```\n\n```text\nnuxt.config.ts\n```\n\n========================================\n\nComments:\n- Having `useSomeStore` `undefined` is not the same as not having `defineStore` imported. You would have a `TypeError defineStore is not a function` at runtime if it was the case. Also, does the Typescript compiler complains about `defineStore` or not?\n- it doesn't but eslint does, do you know whats the best way to fix it?\n- Some clarification here. It's best practice to put Pinia stores in the folder storeS, vuex stores where put in the folder store without S..\n- This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review\n- @Faris Hi, I rewrite the answer. please check. If I provided anything that require clarification please let me know.","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":257,"estimatedTokens":1038}}333{"id":"stack-55449096","source":"stackoverflow","questionId":55449096,"title":"Intercepting network errors on apollo-module using Nuxt","tags":["vue.js","apollo","nuxt.js","apollo-client","vue-apollo"],"text":"Title: Intercepting network errors on apollo-module using Nuxt\nTags: vue.js, apollo, nuxt.js, apollo-client, vue-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm using `nuxt` with `apollo-module` and I need to intercept possible network errors (401/403's to be more specific) so I can show some error modal and log out my user. In the documentation I see that inside the `nuxt.config.js` you can do like:\n\n```\napollo: {\n tokenName: 'Authorization',\n authenticationType: 'Bearer',\n errorHandler(error) { do something }\n }\n...\n```\n\nBut inside that config file, I can't access the app features that I need (like a errors modal or my router, for instance). Is there any way to archive it?\n\n========================================\n\nCode:\n```text\napollo: {\n tokenName: 'Authorization',\n authenticationType: 'Bearer',\n errorHandler(error) { do something }\n }\n...\n```\n\n```text\nnuxt\n```\n\n```text\napollo-module\n```\n\n```text\nnuxt.config.js\n```\n\n```text\napollo: {\n clientConfigs: {\n default: '~/apollox/client-configs/default.js'\n }\n },\n```\n\n```text\nimport { onError } from 'apollo-link-error'\n\nexport default function(ctx) {\n const errorLink = onError(({ graphQLErrors, networkError }) => {\n\n })\n return {\n link: errorLink,\n\n // required\n httpEndpoint: ctx.app.$env.GRAPHQL_URL,\n\n httpLinkOptions: {\n credentials: 'same-origin'\n },\n }\n}\n```\n\n========================================\n\nComments:\n- Worked perfectly! Thanks :)\n- Thanks so much. Btw I think you meant to write `apollo` instead of `apollox` in `default: '~/apollox/client-configs/default.js'` ?\n- you can name the files however you want","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":76,"estimatedTokens":411}}334{"id":"stack-62868495","source":"stackoverflow","questionId":62868495,"title":"VueJS difference between methods and functions?","tags":["vue.js","nuxt.js"],"text":"Title: VueJS difference between methods and functions?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI didn't manage to find much on this, what's the difference between using a method and declaring a function in the script tag?\n\n**example.vue**\n\n```\n\nexport default{\n methods: {\n testfunction1(){\n ...\n }\n },\n mounted(){\n this.testfunction1();\n }\n}\n\n```\n\ncompared to\n\n```\n\nexport default{\n methods: {\n ...\n },\n mounted(){\n testFunction1();\n }\n}\n\nfunction testFunction1(){\n ...\n}\n\n```\n\nPS: If they're both legit, what are their uses cases? - When to use both?\n\n========================================\n\nCode:\n```html\n<script>\nexport default{\n methods: {\n testfunction1(){\n ...\n }\n },\n mounted(){\n this.testfunction1();\n }\n}\n</script>\n```\n\n```html\n<script>\nexport default{\n methods: {\n ...\n },\n mounted(){\n testFunction1();\n }\n}\n\nfunction testFunction1(){\n ...\n}\n</script>\n```\n\n```js\nfunction testFunction() {\n console.log(this.someDataProperty)\n // \"this\" is the module scope and someDataProperty will not be defined\n}\n\nexport default {\n data: () => ({ someDataProperty: 'whatever' }),\n mounted () {\n testFunction()\n }\n}\n```\n\n```html\n<ChildComponent ref=\"child\"/>\n```\n\n```js\nthis.$refs.child.someMethod()\n```\n\n```html\n<button @click=\"someMethod()\">Click me!</button>\n```\n\n```text\ntestFunction\n```\n\n```text\nmethods\n```\n\n```text\nthis\n```\n\n```text\nmethods\n```\n\n```text\nmethods\n```\n\n========================================\n\nComments:\n- Right! Great point. So will there be a use case for non-method functions? Should I separate them as \"helper\" functions if they do not need access to `this` and only include them in methods as required? Underlying question - What would be a good/more correct way to structure my code?\n- That's how I've used them in the past, ie *helpers*, *utility*, etc. It's pretty subjective but if you want to keep your component's API clean, moving junk out of `methods` is one way to do so. It might also help with unit testing if you can test your helper functions in isolation\n- You can also directly use the method in the same component's template: `` and even pass inline variables of a `v-for` as method parameters: ``\n- @ssc-hrep3 excellent point. If you don't mind, I'll add that to the answer\n- Just go for it :)","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":134,"estimatedTokens":583}}335{"id":"stack-61407335","source":"stackoverflow","questionId":61407335,"title":"Tailwind's directive @apply not working on Nuxt","tags":["css","nuxt.js","tailwind-css"],"text":"Title: Tailwind's directive @apply not working on Nuxt\nTags: css, nuxt.js, tailwind-css\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use Tailwind in my brand new project, every utilitie works fine but the @apply one can't even compile.\n\nHere is the error message:\n\n```\nSyntax Error: SyntaxError friendly-errors 08:12:30\n\n(5:5) `@apply` cannot be used with `.lg\\:mt-0` because `.lg\\:mt-0` either cannot be found, or its actual definition includes a pseudo-selector like :hover, :active, etc. If you're sure that `.lg\\:mt-0` exists, make sure that any `@import` statements are being properly processed *before* Tailwind CSS sees your CSS, as `@apply` can only be used for classes in the same CSS tree.\n\n 3 | @import 'tailwindcss/components';\n 4 | .navbar-item-link {\n> 5 | @apply text-xs mt-1 lg:mt-0 px-3 no-underline text-gray-600 rounded-full border-solid border border-gray-100 hover:border-blue-best-100;\n | ^\n 6 | }\n 7 | /* purgecss end ignore */\n```\n\nMy tailwind.css file:\n\n```\n/* purgecss start ignore */\n@import 'tailwindcss/base';\n@import 'tailwindcss/components';\n.navbar-item-link {\n @apply text-xs mt-1 lg:mt-0 px-3 no-underline text-gray-600 rounded-full border-solid border border-gray-100 hover:border-blue-best-100;\n}\n/* purgecss end ignore */\n\n@import 'tailwindcss/utilities';\n```\n\nI already have installed postcss cli and using the postcss.config.js like so:\n\n```\nmodule.exports = {\n plugins: [\n require(\"postcss-import\"),\n require(\"tailwindcss\"),\n require(\"autoprefixer\")\n ]\n};\n```\n\nBut none of this works.\n\n========================================\n\nCode:\n```text\nSyntax Error: SyntaxError friendly-errors 08:12:30\n\n(5:5) `@apply` cannot be used with `.lg\\:mt-0` because `.lg\\:mt-0` either cannot be found, or its actual definition includes a pseudo-selector like :hover, :active, etc. If you're sure that `.lg\\:mt-0` exists, make sure that any `@import` statements are being properly processed *before* Tailwind CSS sees your CSS, as `@apply` can only be used for classes in the same CSS tree.\n\n 3 | @import 'tailwindcss/components';\n 4 | .navbar-item-link {\n> 5 | @apply text-xs mt-1 lg:mt-0 px-3 no-underline text-gray-600 rounded-full border-solid border border-gray-100 hover:border-blue-best-100;\n | ^\n 6 | }\n 7 | /* purgecss end ignore */\n```\n\n```text\n/* purgecss start ignore */\n@import 'tailwindcss/base';\n@import 'tailwindcss/components';\n.navbar-item-link {\n @apply text-xs mt-1 lg:mt-0 px-3 no-underline text-gray-600 rounded-full border-solid border border-gray-100 hover:border-blue-best-100;\n}\n/* purgecss end ignore */\n\n@import 'tailwindcss/utilities';\n```\n\n```text\nmodule.exports = {\n plugins: [\n require(\"postcss-import\"),\n require(\"tailwindcss\"),\n require(\"autoprefixer\")\n ]\n};\n```\n\n```text\n.navbar-item-link {\n @apply text-xs mt-1 lg:mt-0 px-3 no-underline text-gray-600 rounded-full border-solid border border-gray-100 hover:border-blue-best-100;\n}\n```\n\n```text\n// Normal State\n.navbar-item-link {\n @apply text-xs mt-1 px-3 no-underline text-gray-600 rounded-full border-solid border border-gray-100;\n}\n\n// Hover State\nnavbar-item-link:hover{\n @apply border-blue-best-100;\n}\n\n// Large Screen\n@screen lg {\n .navbar-item-link{\n @apply mt-0;\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":112,"estimatedTokens":868}}336{"id":"stack-55463025","source":"stackoverflow","questionId":55463025,"title":"created hook for vuex / nuxtClientInit?","tags":["vue.js","vuex","nuxt.js"],"text":"Title: created hook for vuex / nuxtClientInit?\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI was wondering whats the best way to do something like `nuxtClientInit`. I'm trying to load the Auth State as early as possible on the client and save it in my vuex store but not on the server side. It would be great if vuex had something like the `created` hook for components but that doesn't exist to my knowledge.\n\nHow could I achieve this behavior? One way could be calling an action from a layout but is that the best way?\n\n========================================\n\nCode:\n```text\nnuxtClientInit\n```\n\n```text\ncreated\n```\n\n```text\n//nuxt-client-init.client.js\nexport default async context => {\n await context.store.dispatch('nuxtClientInit', context)\n}\n```\n\n```text\n//nuxt.config.js\n plugins: [\n '~/plugins/nuxt-client-init.client.js'\n ],\n```\n\n```text\n//store/index.js\nexport const actions = {\n nuxtClientInit({ commit }, { req }) {\n const autho = localStorage.getItem('auth._token.local') //or whatever yours is called\n commit('SET_AUTHO', autho)\n console.log('From nuxtClientInit - '+autho)\n }\n}\n```\n\n```text\n'{ src: '~/plugins/nuxt-client-init.js', mode: 'client' }'\n```\n\n```text\n'{ src: '~/plugins/nuxt-client-init.js', ssr: false }'\n```\n\n========================================\n\nComments:\n- you can add this into the main `App.vue` `created` method, or the base component to that\n- @DerekPollard There is no App.vue in nuxt.\n- Thanks, that seems like the best solution!","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":59,"estimatedTokens":377}}337{"id":"stack-65482176","source":"stackoverflow","questionId":65482176,"title":"Tailwind group-hover not working (even with default variants)","tags":["nuxt.js","tailwind-css"],"text":"Title: Tailwind group-hover not working (even with default variants)\nTags: nuxt.js, tailwind-css\nSource: Stack Overflow\n\nQuestion:\nA basic use of Tailwind's `group-hover` is not working for me. I'm simply trying to change text color, which isn't supposed to require any special configuration.\n\nAm I forgetting something?\n\nFor reference my project is a Vue (Nuxt.js) app, and all other Tailwind features are working for me. I've used TW group-hover on other projects without issue.\n\n**FAILS:**\nTried the following on a basic welcome page in my app.\n\n```\n\n Hover me\n Hover me\n\n```\n\n**THIS WORKS:** The same code works fine in Codepen https://codepen.io/MarsAndBack/pen/MWjroVZ\n\n**ALSO, WORKS:** The same `group-hover` method *works* in my other projects.\n\n**`tailwind.config.js`:**\n\n```\nmodule.exports = {\n variants: {},\n plugins: [\n require('@tailwindcss/custom-forms')\n ],\n purge: {\n enabled: process.env.NODE_ENV === 'production',\n content: [\n 'components/**/*.vue',\n 'layouts/**/*.vue',\n 'pages/**/*.vue',\n 'plugins/**/*.js',\n 'nuxt.config.js'\n ]\n },\n theme: {\n extend: {\n colors: {\n brandGreen: {\n light: '#5bb751',\n default: '#5bb751',\n dark: '#3b7935',\n darker: '#33602e'\n }\n\n }\n },\n screens: {\n 'xs': '480px'\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\n<div class=\"group\">\n <div class=\"group-hover:text-gray-300\">Hover me</div>\n <div class=\"group-hover:text-red-300\">Hover me</div>\n</div>\n```\n\n```text\nmodule.exports = {\n variants: {},\n plugins: [\n require('@tailwindcss/custom-forms')\n ],\n purge: {\n enabled: process.env.NODE_ENV === 'production',\n content: [\n 'components/**/*.vue',\n 'layouts/**/*.vue',\n 'pages/**/*.vue',\n 'plugins/**/*.js',\n 'nuxt.config.js'\n ]\n },\n theme: {\n extend: {\n colors: {\n brandGreen: {\n light: '#5bb751',\n default: '#5bb751',\n dark: '#3b7935',\n darker: '#33602e'\n }\n\n }\n },\n screens: {\n 'xs': '480px'\n }\n }\n}\n```\n\n```text\ngroup-hover\n```\n\n```text\ngroup-hover\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nmodule.exports = {\n\n // ...\n\n variants: {\n textColor: ['group-hover'],\n }\n\n // ...\n}\n```\n\n```text\ngroup-hover\n```\n\n```text\ngroup-hover\n```\n\n```text\ntextColor\n```\n\n========================================\n\nComments:\n- Looking back on this now, I wonder if the empty `variants: {}` was the original culprit? Maybe removing that line would make basic group-hover implementation work as expected.\n- I have the exact same problem. I tried that but it didn't work. It use to work perfectly, then seldomly (would work on some element but not all) and now, it's not working at all...\n- Well, all I can advise is that while you trial-and-error, keep in mind when you are relying on A) hot reload vs B) re-starting the app vs C) re-building the app. Usually when I experience intermittent bugs in CSS, it's because I'm doing something different in this regard.","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":150,"estimatedTokens":738}}338{"id":"stack-54887555","source":"stackoverflow","questionId":54887555,"title":"Nuxt dynamic route return 404 after page is reloaded","tags":["javascript","vue.js","vuejs2","vue-router","nuxt.js"],"text":"Title: Nuxt dynamic route return 404 after page is reloaded\nTags: javascript, vue.js, vuejs2, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHello everyone I'm working on a project that uses nuxt js and I'm just new to this framework. I've configured it to use **spa** mode, fyi I did not change or add anything in my nuxt config just the default. And below is how I've setup my pages.\n\n*pages/users/index.vue* - shows list or users\n\n*pages/users/_id.vue* - show specific user\n\nI've deployed my project using *npm run build* and *npm run start* command. The dist directory is then hosted in a nginx server.\n\nThe issue is that when i navigate to */user/id* using nuxt link the page is rendered properly, but when I access the page url directly or refresh the page I get nginx 404 page not found. \n\nI've read about nuxt generate to generate pre rendered pages but is this good to use when dealing on hundreds of records? \n\nAny help, advice, would be much appriciated.\n\nThanks\n\n========================================\n\nTop Answer:\nAt the very beginning you should understand what problems help you solve nuxt.\n\nyou can create three types of applications:\n\n- static page\n\nOn the basis of the routing, nuxt generate html files, which are SEO-frendly. This works, for example, for business card pages (main page + several subpages). You get ready-made html files e.g. index.html, contact.html etc.\n\n- SPA\n\napplications that do not require SEO, but have dynamic paths and interface. Does not use server side rendering. Some methods are unavailable, but still use some of the benefits of nuxt. For example, dynamic routing or many options available in the configuration in nuxt.\n\n- Universal\n\nallows you to enjoy all the benefits of nuxt.js. With the help of dedicated website methods (fetch, asyncData, nuxtServerInit etc.), it allows you to prepare data on the server side to generate them on the browser side so that they are SEO-friendly.\n\nTherefore, if you need to use dynamic routing, you have to choose between SPA and Universal mode. Check what commands you should USE\n\n========================================\n\nCode:\n```text\nexport default {\n generate: {\n fallback: \"custom_sap_fallbackpage.html\"\n }\n}\n```\n\n```text\nlocation / {\n try_files $uri /custom_sap_fallbackpage.html;\n}\n```\n\n```text\nuniversal\n```\n\n```text\nnuxt generate\n```\n\n```text\ndist\n```\n\n```text\nNuxt\n```\n\n```text\ntarget: static\n```\n\n```text\nfallback: true\n```\n\n```text\nNetlify\n```\n\n```text\nspa\n```\n\n========================================\n\nComments:\n- This answer is incorrect in a few places. First of all, your entire first point is wrong. There is a `routes` function in the `generate` property precisely for dynamically determining routes. It's the predecessor of the `target: static` functionality and does the same thing. That beings us to the next issue, SSR is note the only way to achieve SEO. You can use either of the two methods I just described for static apps. See stackoverflow.com/questions/63061720/… for more info on SEO in Nuxt","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":95,"estimatedTokens":759}}339{"id":"stack-61662857","source":"stackoverflow","questionId":61662857,"title":"Serve static assets with an efficient cache policy - Nuxt.js + GAE","tags":["google-app-engine","caching","nuxt.js","cache-control","lighthouse"],"text":"Title: Serve static assets with an efficient cache policy - Nuxt.js + GAE\nTags: google-app-engine, caching, nuxt.js, cache-control, lighthouse\nSource: Stack Overflow\n\nQuestion:\nI get the following from **Lighthouse**:\n\nhttps://i.sstatic.net/OnDex.png\n\nHow do I change the Cache TTL on a **Nuxt.js** SSR website? I found some answers but nothing about Nuxt.js...\n\n**IMPORTANT**: Deployed in Google App Engine\n\n========================================\n\nTop Answer:\nYou can serve your static folder with custom cache policy following the render configuration.\n\nAs an example:\n\n```\nrender: {\n // Setting up cache for 'static' directory - a year in milliseconds\n // https://web.dev/uses-long-cache-ttl\n static: {\n maxAge: 60 * 60 * 24 * 365 * 1000,\n },\n},\n```\n\n========================================\n\nCode:\n```yaml\nhandlers:\n - url: /_nuxt\n static_dir: .nuxt/dist/client\n expiration: 4d 5h\n secure: always\n```\n\n```yaml\ndefault_expiration: 4d 5h\n```\n\n```text\nhandlers.expiration\n```\n\n```text\napp.yaml\n```\n\n```text\ndefault_expiration\n```\n\n```text\nd\n```\n\n```text\nh\n```\n\n```text\nm\n```\n\n```text\ns\n```\n\n```js\nrender: {\n // Setting up cache for 'static' directory - a year in milliseconds\n // https://web.dev/uses-long-cache-ttl\n static: {\n maxAge: 60 * 60 * 24 * 365 * 1000,\n },\n},\n```\n\n========================================\n\nComments:\n- Does this answer your question? How to add headers on Nuxt static files response?\n- Nope, because that speak about the static folder, and is not the case :( thanks anyway\n- Thanks for the answer, but the question doesn't talk about the static folder.\n- Just a note that you may want to change to `static: false;` if using GAE's CDN.\n- Thanks. Good point to keep in mind","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":91,"estimatedTokens":430}}340{"id":"stack-49454604","source":"stackoverflow","questionId":49454604,"title":"Persisted state from VueX and NuxtJS","tags":["vuex","nuxt.js","adonis.js"],"text":"Title: Persisted state from VueX and NuxtJS\nTags: vuex, nuxt.js, adonis.js\nSource: Stack Overflow\n\nQuestion:\nI use vuex-persistedstate package (https://github.com/robinvdvleuten/vuex-persistedstate) to persist data state on browser.\n\nI use Adonuxt (a mix between NuxtJS and AdonisJS).\n\nIn VueX actions, I have this action:\n\n```\nnuxtClientInit ({commit}) {\n // I want get here state auth saved by persistedstate package\n }\n```\n\nThis action is called by plugin:\n\nlocalstorage.js\n\n```\nexport default async (context) => {\n await context.store.dispatch('nuxtClientInit', context)\n}\n```\n\nnuxt.js plugin (config)\n\n```\n{\n src: '~/plugins/localstorage.js',\n ssr: false\n }\n```\n\nI want get state to configure Axios with the user token:\n\n```\nthis.$axios.setToken(auth.jwt.token, 'Bearer')\n```\n\nI have the impression nuxtClientInit() is called before persistedstate package, so `state.auth` is null but it can observable in console:\n\n========================================\n\nTop Answer:\ncsr+ssr cookie\n\nYou can choose any one of the below library\n\n1 .vuex-persistedstate\n\n2 .vuex-persist\n\nvuex-persistedstate usage\n\nhttps://www.npmjs.com/package/vuex-persistedstate\n\n**plugins/persistedstate.js**\n\n```\nimport createPersistedState from 'vuex-persistedstate'\nimport * as Cookies from 'js-cookie'\nimport cookie from 'cookie'\n\nexport default ({store, req, isDev}) => {\n createPersistedState({\n key: 'your_key',\n paths: ['state1', 'state2',...so_on],\n storage: {\n getItem: (key) => process.client ? Cookies.getJSON(key) : cookie.parse(req.headers.cookie||'')[key],\n setItem: (key, value) => Cookies.set(key, value, { expires: 365, secure: !isDev }),\n removeItem: (key) => Cookies.remove(key)\n }\n })(store)\n}\n```\n\n**nuxt.config.js**\n\n```\nplugins: [\n { src: '~plugins/persistedstate.js' }\n ]\n```\n\nvuex-persist\n\nhttps://www.npmjs.com/package/vuex-persist\n\n```\n// ~/plugins/vuex-persist.js\nimport * as Cookies from 'js-cookie'\nimport cookie from 'cookie'\n\nimport VuexPersistence from 'vuex-persist'\n\nexport default ({ store, req, isDev }) => {\n new VuexPersistence({\n key:'test',\n reducer: (state) => ({}),\n restoreState: (key, storage) =>process.client ? Cookies.getJSON(key) : cookie.parse(req.headers.cookie||'')[key],\n saveState: (key, state, storage) =>\n Cookies.set(key, value, { expires: 365, secure: !isDev }),\n\n }).plugin(store);\n}\n```\n\nnuxt.config.js\n\n```\nplugins: [\n { src: '~plugins/vuex-persist.js' }\n ]\n```\n\n========================================\n\nCode:\n```text\nnuxtClientInit ({commit}) {\n // I want get here state auth saved by persistedstate package\n }\n```\n\n```text\nexport default async (context) => {\n await context.store.dispatch('nuxtClientInit', context)\n}\n```\n\n```text\n{\n src: '~/plugins/localstorage.js',\n ssr: false\n }\n```\n\n```text\nthis.$axios.setToken(auth.jwt.token, 'Bearer')\n```\n\n```text\nstate.auth\n```\n\n```text\nroot/\n ├ src/\n ├ pages/\n .\n .\n ├ src/\n └ plugins/\n └ localstorage.js/\n```\n\n```text\n{src:'~/src/plugins/localstorage.js', srr: false}\n```\n\n```text\nimport createPersistedState from 'vuex-persistedstate'\nimport * as Cookies from 'js-cookie'\nimport cookie from 'cookie'\n\nexport default ({store, req, isDev}) => {\n createPersistedState({\n key: 'your_key',\n paths: ['state1', 'state2',...so_on],\n storage: {\n getItem: (key) => process.client ? Cookies.getJSON(key) : cookie.parse(req.headers.cookie||'')[key],\n setItem: (key, value) => Cookies.set(key, value, { expires: 365, secure: !isDev }),\n removeItem: (key) => Cookies.remove(key)\n }\n })(store)\n}\n```\n\n```text\nplugins: [\n { src: '~plugins/persistedstate.js' }\n ]\n```\n\n```text\n// ~/plugins/vuex-persist.js\nimport * as Cookies from 'js-cookie'\nimport cookie from 'cookie'\n\nimport VuexPersistence from 'vuex-persist'\n\nexport default ({ store, req, isDev }) => {\n new VuexPersistence({\n key:'test',\n reducer: (state) => ({}),\n restoreState: (key, storage) =>process.client ? Cookies.getJSON(key) : cookie.parse(req.headers.cookie||'')[key],\n saveState: (key, state, storage) =>\n Cookies.set(key, value, { expires: 365, secure: !isDev }),\n\n }).plugin(store);\n}\n```\n\n```text\nplugins: [\n { src: '~plugins/vuex-persist.js' }\n ]\n```\n\n========================================\n\nComments:\n- It's very good, been using this package for years. Just one things - in case of `nuxt` I had an issue with dependencies relying on vue 3 (and `nuxt` right now is using `vue 2`), which got resolved after specifying `vuex` version explicitly: `npm install vuex@3.4.0 --save`\n- More precise instructions here: npmjs.com/package/vuex-persist#tips-for-nuxt","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":217,"estimatedTokens":1154}}341{"id":"stack-59608684","source":"stackoverflow","questionId":59608684,"title":"How to add/mock the Nuxt Auth library when testing components in Nuxt with Jest","tags":["unit-testing","vue.js","jestjs","nuxt.js"],"text":"Title: How to add/mock the Nuxt Auth library when testing components in Nuxt with Jest\nTags: unit-testing, vue.js, jestjs, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nJS newbie here.\n\nI have generated a Nuxt app and have implemented the `@nuxt/auth` middleware globally in my `nuxt.config.js`. It's working as expected in my app.\n\nNow I would like to test some of my components that reference the `$auth` object.\n\n```\n// ~/components/hello_component.vue\n\n \n \n \n\n### Hi, {{ userName }}\n\n \n \n\nexport default {\n data () {\n userName: \"Archduke Chocula\"\n }\n}\n\n```\n\nI have a test that looks like this:\n\n```\n// ~/spec/components/hello_component.spec.js\n\nimport { mount } from '@vue/test-utils'\nimport Hello from '@/components/hello_component.vue'\n\ndescribe('Hello Component', () => {\n test('is a Vue instance', () => {\n const wrapper = mount(Hello)\n expect(wrapper.isVueInstance()).toBeTruthy()\n })\n})\n```\n\nWhich causes the following error\n\n```\nError in render: \"TypeError: Cannot read property 'loggedIn' of undefined\"\n```\n\nSo clearly I need to define auth somewhere, so my questions are:\n\n- Where and how should I add this dependency to my tests (per test? globally for all tests?)?\n\n- How can I mock the response of the `loggedIn` method so that I can test scenarios where I'm either logged in/out?\n\n- Is there a way to mock the Nuxt environment in my tests so that I can test my components etc as if they were mounted in Nuxt? Is that a even a good idea?\n\nThanks in advance for any help!\n\n========================================\n\nCode:\n```text\n// ~/components/hello_component.vue\n\n<template>\n <div>\n <div v-if=\"$auth.loggedIn\">\n <h1>Hi, {{ userName }}</h1>\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n data () {\n userName: \"Archduke Chocula\"\n }\n}\n</script>\n```\n\n```text\n// ~/spec/components/hello_component.spec.js\n\nimport { mount } from '@vue/test-utils'\nimport Hello from '@/components/hello_component.vue'\n\ndescribe('Hello Component', () => {\n test('is a Vue instance', () => {\n const wrapper = mount(Hello)\n expect(wrapper.isVueInstance()).toBeTruthy()\n })\n})\n```\n\n```text\nError in render: \"TypeError: Cannot read property 'loggedIn' of undefined\"\n```\n\n```text\n@nuxt/auth\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n$auth\n```\n\n```text\nloggedIn\n```\n\n```text\nimport { mount } from '@vue/test-utils'\nimport Hello from '@/components/hello_component.vue'\n\nconst authMock = {\n loggedIn: true\n};\n\ndescribe('Hello Component', () => {\n test('is a Vue instance', () => {\n const wrapper = mount(Hello, {\n mocks: {\n $auth: authMock\n }\n })\n expect(wrapper.isVueInstance()).toBeTruthy()\n })\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":139,"estimatedTokens":662}}342{"id":"stack-70262605","source":"stackoverflow","questionId":70262605,"title":"Understanding lazy load and hydration in nuxt","tags":["vue.js","nuxt.js"],"text":"Title: Understanding lazy load and hydration in nuxt\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\n### First question\n\nWhen I'm using Lazy load with nuxt and `components: true`\n\nFor example\n\n```\n \n \n\n \n \n\n \n \n\n```\n\nThe v-if should be on the component in order to lazy load or it will work when parent has the condition, if it will work with the parent the component must start with `Lazy`?\n\n### Second question\n\nI am using vue-lazy-hydration package in order to decrease my Time to Interactive and\nTotal Blocking Time.\nWhen (LazyHydrate when-idle) take action I don't understand when the browser is idle.\n\n========================================\n\nCode:\n```html\n<div v-if=\"condition\"> <!-- 1 -->\n <LazyComponent v-if=\"condition\"/>\n</div>\n<div v-if=\"condition\"> <!-- 2 -->\n <LazyComponent/>\n</div>\n<div v-if=\"condition\"> <!-- 3 -->\n <Component/>\n</div>\n```\n\n```text\ncomponents: true\n```\n\n```text\nLazy\n```\n\n```text\nv-if\n```\n\n```text\nv-if\n```\n\n```text\nlazy\n```\n\n```text\nv-if\n```\n\n```text\nv-if\n```\n\n```text\nv-if\n```\n\n========================================\n\nComments:\n- why lazy pretty much every component that you want to import is a bad idea?\n- and if vue-lazy-hydration not compatible with nuxt you have and suggestion how i can decrease my Time to interactive and total blocking time, ty for your help\n- @nadav I actually said the opposite here, `lazy` as much as you can. Only some things cannot be lazy-loaded. Mostly the ones that you need straight away. Also, if you ever have a bug related to this, you could test by eagerly loading it (with no `lazy` prefix). As of what to do to decrease some metrics, it's a broad question and it may come from a lot of things. Maybe give a look to my previous answer. Not directly an answer but still valid opinion. Otherwise, you could also try Nuxt3, but beware because it's still in beta.\n- @kissu Can you please clear one thing for me that is if we add the `v-if` condition inside lazy component like `` then what is the difference between `` and ``.. ?\n- @KishanBhensadadiya nowadays Nuxt does have server components so that would be a better solution overall (official and supported). As for the initial question, I'd say it depends what is the start of the condition but probably a huge mess in terms of hydration and not a lot of benefits (or some visual glitches until the UI is hydrated).\n- @kissu Thanks for clearing up. So the `` is also fine without Lazy keyword as this will not give more benefit as you said right? Apology but I need to clear the lazy load features and what the actual benefits of it\n- @KishanBhensadadiya I'm just saying that hydration by itself is complex, Nuxt is a meta-framework helping in that regard. Meanwhile, it's not trivial to explain such principles in a few lines of a StackOverflow comment haha. Give a read to Nuxt server components and do your own testing regarding the hydration. It may take some time but you'll probably understand how it works + how to handle the whole thing with time.\n- @kissu Yes, I'll surely do this. By the way thanks for the time to give me the answer!","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":89,"estimatedTokens":771}}343{"id":"stack-59485231","source":"stackoverflow","questionId":59485231,"title":"Push a custom error message to ValidationObserver","tags":["nuxt.js","vee-validate"],"text":"Title: Push a custom error message to ValidationObserver\nTags: nuxt.js, vee-validate\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt + veeValidate 3.x\n\nMy plugin looks like this:\n\n```\nimport Vue from 'vue'\nimport {\n ValidationObserver,\n ValidationProvider,\n extend\n} from 'vee-validate'\nimport { required, email, min, confirmed } from 'vee-validate/dist/rules'\n\nextend('required', {\n ...required,\n message: 'This field is required'\n})\nextend('email', email)\nextend('min', min)\nextend('confirmed', confirmed)\nVue.component('ValidationProvider', ValidationProvider)\nVue.component('ValidationObserver', ValidationObserver)\n```\n\nAdded as a plugin into `nuxt.config.js` `plugins: [{ src: '~/plugins/vee-validate.js', ssr: false }, ..`\nThe template looks like this:\n\n```\n \n \n \n \n {{ errors[0] }}\n \n \n\n```\n\nThe validation works perfectly this way:\n\n```\nmethods: {\n async submit() {\n const isValid = await this.$refs.registrationForm.validate()\n if (isValid) {\n this.register()\n ....\n```\n\nBut I may get some errors from the API side during the execution of `this.register()` (Ex: error: email is already exists). How do I push received errors into validating errors array (if there such)? the old way as `this.errors.add()` doesn't work (of course) anymore. I've read about ErrorBag, but I just dont understand how do I import/export it in the plugin\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\nimport {\n ValidationObserver,\n ValidationProvider,\n extend\n} from 'vee-validate'\nimport { required, email, min, confirmed } from 'vee-validate/dist/rules'\n\nextend('required', {\n ...required,\n message: 'This field is required'\n})\nextend('email', email)\nextend('min', min)\nextend('confirmed', confirmed)\nVue.component('ValidationProvider', ValidationProvider)\nVue.component('ValidationObserver', ValidationObserver)\n```\n\n```text\n<ValidationObserver ref=\"registrationForm\"> \n <ValidationProvider rules=\"required|email\" name=\"Email Address\" v-slot=\"{ errors }\">\n <div>\n <input type=\"text\" v-model.lazy=\"user.email\"/>\n <span class=form-errors\">{{ errors[0] }}</span>\n </div>\n </ValidationProvider>\n</ValidationObserver>\n```\n\n```text\nmethods: {\n async submit() {\n const isValid = await this.$refs.registrationForm.validate()\n if (isValid) {\n this.register()\n ....\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nplugins: [{ src: '~/plugins/vee-validate.js', ssr: false }, ..\n```\n\n```text\nthis.register()\n```\n\n```text\nthis.errors.add()\n```\n\n```text\nthis.$refs.registrationForm.setErrors({ email: ['Your email does\\'t look good enough! Try again!'] })\n```\n\n```text\ncatch (error) {\n this.$refs.registrationForm.setErrors(error.response.data.errors)\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.858Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":124,"estimatedTokens":678}}344{"id":"stack-59292564","source":"stackoverflow","questionId":59292564,"title":"Nuxt.js npm run build results in some JS files being not found","tags":["vue.js","webpack","nuxt.js","code-splitting"],"text":"Title: Nuxt.js npm run build results in some JS files being not found\nTags: vue.js, webpack, nuxt.js, code-splitting\nSource: Stack Overflow\n\nQuestion:\nI have a Nuxt.js `^2.10.2` App. \n\nWhen I do `npm run dev`, the project builds perfectly.\n\nWhen I do `npm run build` then `npm run start`. some JS files are getting 404 error.\n\nhttps://i.sstatic.net/dpwcS.png\n\n```\nERROR\n\nRequest URL: http://localhost:3000/_nuxt/vendors.pages/account.pages/ca.pages/cart.pages/category/_id/\nindex.pages/checkout/_step/index.pages/.f705ad4d.1-0-128.js\nRequest Method: GET\nStatus Code: 404 Not Found\nRemote Address: 127.0.0.1:3000\nReferrer Policy: no-referrer-when-downgrade\n```\n\nThe file exists on my project in `dist/_nuxt/vendor.pages/......` with the correct filename `.f705ad4d.1-0-128.js`\n\nmy `nuxt.config.js` \n\n```\nbuild: {,\n filenames: {\n app: '[name].' + version + '.js',\n chunk: '[name].' + version + '.js',\n vendor: '[name].' + version + '.js',\n manifest: '[name].' + version + '.js',\n },\n}\n```\n\nWhat am I doing wrong? As other files are loaded as normal.\n\n========================================\n\nCode:\n```text\nERROR\n\nRequest URL: http://localhost:3000/_nuxt/vendors.pages/account.pages/ca.pages/cart.pages/category/_id/\nindex.pages/checkout/_step/index.pages/.f705ad4d.1-0-128.js\nRequest Method: GET\nStatus Code: 404 Not Found\nRemote Address: 127.0.0.1:3000\nReferrer Policy: no-referrer-when-downgrade\n```\n\n```text\nbuild: {,\n filenames: {\n app: '[name].' + version + '.js',\n chunk: '[name].' + version + '.js',\n vendor: '[name].' + version + '.js',\n manifest: '[name].' + version + '.js',\n },\n}\n```\n\n```text\n^2.10.2\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run start\n```\n\n```text\ndist/_nuxt/vendor.pages/......\n```\n\n```text\n.f705ad4d.1-0-128.js\n```\n\n```text\nnuxt.config.js\n```\n\n```js\nbuild: {\n filenames: {\n app: ({ isDev }) => isDev ? '[name].js' : '[chunkhash].js',\n chunk: ({ isDev }) => isDev ? '[name].js' : '[chunkhash].js',\n css: ({ isDev }) => isDev ? '[name].css' : '[contenthash].css',\n img: ({ isDev }) => isDev ? '[path][name].[ext]' : 'img/[hash:7].[ext]',\n font: ({ isDev }) => isDev ? '[path][name].[ext]' : 'fonts/[hash:7].[ext]',\n video: ({ isDev }) => isDev ? '[path][name].[ext]' : 'videos/[hash:7].[ext]'\n }\n}\n```\n\n```js\nbuild: {\n filenames: {\n chunk: ({ isDev }) => isDev ? '[name].js' : '[chunkhash].js'\n }\n}\n```\n\n```text\n.\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- Does it have to start with a . ? Can you browse out to the path?\n- basically if I change the file name it works. Not sure why this file has no name though. need to investigate.\n- I had issues with the `npm run dev`, but the production build was fine. After setting up chunk names, everything works.\n- @Garine you just saved us days worth of headbanging. Thanks a lot man.","metadata":{"transformedAt":"2026-08-18T18:33:07.859Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":130,"estimatedTokens":722}}345{"id":"stack-67318524","source":"stackoverflow","questionId":67318524,"title":"Pulumi (TypeScript, AWS): How to upload multiple files to S3 incl. nested files in directories for static website hosting","tags":["amazon-web-services","amazon-s3","nuxt.js","pulumi","static-site-generation"],"text":"Title: Pulumi (TypeScript, AWS): How to upload multiple files to S3 incl. nested files in directories for static website hosting\nTags: amazon-web-services, amazon-s3, nuxt.js, pulumi, static-site-generation\nSource: Stack Overflow\n\nQuestion:\nIn the Create an AWS S3 Website in Under 5 Minutes YT video and Host a Static Website on Amazon S3 Pulumi tutorial there are great explanations how to create a website hosting on S3 using Pulumi.\n\nIn the example code Pulumi's Bucket and BucketObject are used. The first creates a S3 Bucket and the latter creates the objects, which are mostly an `index.html` for public access like this:\n\n```\nconst aws = require(\"@pulumi/aws\");\nconst pulumi = require(\"@pulumi/pulumi\");\nconst mime = require(\"mime\");\n\n// Create an S3 bucket\nlet siteBucket = new aws.s3.Bucket(\"s3-website-bucket\");\n\nlet siteDir = \"www\"; // directory for content files\n\n// For each file in the directory, create an S3 object stored in `siteBucket`\nfor (let item of require(\"fs\").readdirSync(siteDir)) {\n let filePath = require(\"path\").join(siteDir, item);\n let object = new aws.s3.BucketObject(item, {\n bucket: siteBucket,\n source: new pulumi.asset.FileAsset(filePath), // use FileAsset to point to a file\n contentType: mime.getType(filePath) || undefined, // set the MIME type of the file\n });\n}\n\nexports.bucketName = siteBucket.bucket; // create a stack export for bucket name\n```\n\nNow using a Vue.js / Nuxt.js based app I need to upload multiple generated files, which are located inside the `dist` directory of my project root. They are produced by a `npm run build` and result in the following files:\n\n```\n$ find dist\ndist\ndist/favicon.ico\ndist/index.html\ndist/.nojekyll\ndist/200.html\ndist/_nuxt\ndist/_nuxt/LICENSES\ndist/_nuxt/static\ndist/_nuxt/static/1619685747\ndist/_nuxt/static/1619685747/manifest.js\ndist/_nuxt/static/1619685747/payload.js\ndist/_nuxt/f3a11f3.js\ndist/_nuxt/f179782.js\ndist/_nuxt/fonts\ndist/_nuxt/fonts/element-icons.4520188.ttf\ndist/_nuxt/fonts/element-icons.313f7da.woff\ndist/_nuxt/c25b1a7.js\ndist/_nuxt/84fe6d0.js\ndist/_nuxt/a93ae32.js\ndist/_nuxt/7b77d06.js\n```\n\nMy problem here is that these files also incorporate files nested in subdirectories, which itself coult also be subdirectories - e.g. `dist/_nuxt/fonts/element-icons.4520188.ttf`. The provided approach in the tutorials doesn't evaluate subdirectories and I don't know how to do that with Pulumi/TypeScript.\n\n========================================\n\nTop Answer:\nI agree with \"jonashackt\" that an AWS cli command is faster and tidier than using pulumi to traverse through a giant directory. But in my case it was still the superiour solution so here we go:\n\n```\nimport * as pulumi from \"@pulumi/pulumi\";\nimport * as aws from \"@pulumi/aws\";\nimport * as awsx from \"@pulumi/awsx\";\n\nconst sourceFolder = \"../my-project\";\nconst bucketName = \"myproject.example.com\";\n\nconst fs = require(\"fs\");\nconst path = require(\"path\");\nconst mime = require(\"mime\");\n\nlet siteBucket = new aws.s3.Bucket(bucketName, {\n bucket: bucketName,\n website: {\n indexDocument: \"index.html\",\n }\n});\n\nlet createdFolders: string[] = [];\nfunction recursiveFolderStructure(dist: string){\n for(let item of fs.readdirSync(dist)) {\n let filePath = path.join(dist, item);\n let relativePath = dist.slice(sourceFolder.length).replace(/\\\\/g, '/');\n let mimeType = mime.getType(filePath) || undefined;\n if(mimeType){\n new aws.s3.BucketObject(relativePath.length ? relativePath+'/'+item : item, {\n acl: \"public-read\",\n bucket: siteBucket,\n source: new pulumi.asset.FileAsset(filePath),\n contentType: mimeType,\n });\n }else{\n if(relativePath.length && !createdFolders.includes(relativePath)){\n new aws.s3.BucketObject(relativePath, {\n acl: \"public-read\",\n bucket: siteBucket,\n key: relativePath+'/',\n contentType: \"application/x-directory\",\n });\n createdFolders.push(relativePath);\n }\n recursiveFolderStructure(filePath);\n }\n }\n}\nrecursiveFolderStructure(sourceFolder);\n\nexports.bucketName = siteBucket.bucket;\nexport const bucketEndpoint = pulumi.interpolate`http://${siteBucket.websiteEndpoint}`;\nconsole.log(bucketEndpoint);\n```\n\nYou just have to change the two variables at the top (sourcefolder and bucketname). By the way I have not thought so much about the code. I can tell there is room for improvement. Feel free to change or suggest cleaner ways. I can tell it works and might save you a few minutes.\n\n========================================\n\nCode:\n```text\nconst aws = require(\"@pulumi/aws\");\nconst pulumi = require(\"@pulumi/pulumi\");\nconst mime = require(\"mime\");\n\n// Create an S3 bucket\nlet siteBucket = new aws.s3.Bucket(\"s3-website-bucket\");\n\nlet siteDir = \"www\"; // directory for content files\n\n// For each file in the directory, create an S3 object stored in `siteBucket`\nfor (let item of require(\"fs\").readdirSync(siteDir)) {\n let filePath = require(\"path\").join(siteDir, item);\n let object = new aws.s3.BucketObject(item, {\n bucket: siteBucket,\n source: new pulumi.asset.FileAsset(filePath), // use FileAsset to point to a file\n contentType: mime.getType(filePath) || undefined, // set the MIME type of the file\n });\n}\n\nexports.bucketName = siteBucket.bucket; // create a stack export for bucket name\n```\n\n```text\n$ find dist\ndist\ndist/favicon.ico\ndist/index.html\ndist/.nojekyll\ndist/200.html\ndist/_nuxt\ndist/_nuxt/LICENSES\ndist/_nuxt/static\ndist/_nuxt/static/1619685747\ndist/_nuxt/static/1619685747/manifest.js\ndist/_nuxt/static/1619685747/payload.js\ndist/_nuxt/f3a11f3.js\ndist/_nuxt/f179782.js\ndist/_nuxt/fonts\ndist/_nuxt/fonts/element-icons.4520188.ttf\ndist/_nuxt/fonts/element-icons.313f7da.woff\ndist/_nuxt/c25b1a7.js\ndist/_nuxt/84fe6d0.js\ndist/_nuxt/a93ae32.js\ndist/_nuxt/7b77d06.js\n```\n\n```text\nindex.html\n```\n\n```text\ndist\n```\n\n```text\nnpm run build\n```\n\n```text\ndist/_nuxt/fonts/element-icons.4520188.ttf\n```\n\n```text\nfunction createS3BucketFolder(dirName: string) {\n new aws.s3.BucketObject(dirName, {\n bucket: nuxtBucket,\n acl: \"public-read\",\n key: dirName + \"/\", // an appended '/' will create a S3 Bucket prefix (see https://stackoverflow.com/a/57479653/4964553)\n contentType: \"application/x-directory\" // this content type is also needed for the S3 Bucket prefix\n // no source needed here!\n })\n}\n```\n\n```text\nimport * as aws from \"@pulumi/aws\";\n\n// Create an AWS resource (S3 Bucket)\nconst nuxtBucket = new aws.s3.Bucket(\"microservice-ui-nuxt-js-hosting-bucket\", {\n acl: \"public-read\",\n website: {\n indexDocument: \"index.html\",\n }\n});\n\n// Export the name of the bucket\nexport const bucketName = nuxtBucket.id;\n```\n\n```text\naws s3 sync ../dist/ s3://$(pulumi stack output bucketName) --acl public-read\n```\n\n```text\nBucketObject\n```\n\n```text\n\"/\"\n```\n\n```text\nkey\n```\n\n```text\npublic-read\n```\n\n```text\n$(pulumi stack output bucketName)\n```\n\n```text\n--acl public-read\n```\n\n```text\nimport * as pulumi from \"@pulumi/pulumi\";\nimport * as aws from \"@pulumi/aws\";\nimport * as awsx from \"@pulumi/awsx\";\n\nconst sourceFolder = \"../my-project\";\nconst bucketName = \"myproject.example.com\";\n\nconst fs = require(\"fs\");\nconst path = require(\"path\");\nconst mime = require(\"mime\");\n\n\nlet siteBucket = new aws.s3.Bucket(bucketName, {\n bucket: bucketName,\n website: {\n indexDocument: \"index.html\",\n }\n});\n\nlet createdFolders: string[] = [];\nfunction recursiveFolderStructure(dist: string){\n for(let item of fs.readdirSync(dist)) {\n let filePath = path.join(dist, item);\n let relativePath = dist.slice(sourceFolder.length).replace(/\\\\/g, '/');\n let mimeType = mime.getType(filePath) || undefined;\n if(mimeType){\n new aws.s3.BucketObject(relativePath.length ? relativePath+'/'+item : item, {\n acl: \"public-read\",\n bucket: siteBucket,\n source: new pulumi.asset.FileAsset(filePath),\n contentType: mimeType,\n });\n }else{\n if(relativePath.length && !createdFolders.includes(relativePath)){\n new aws.s3.BucketObject(relativePath, {\n acl: \"public-read\",\n bucket: siteBucket,\n key: relativePath+'/',\n contentType: \"application/x-directory\",\n });\n createdFolders.push(relativePath);\n }\n recursiveFolderStructure(filePath);\n }\n }\n}\nrecursiveFolderStructure(sourceFolder);\n\nexports.bucketName = siteBucket.bucket;\nexport const bucketEndpoint = pulumi.interpolate`http://${siteBucket.websiteEndpoint}`;\nconsole.log(bucketEndpoint);\n```\n\n```js\nimport * as aws from \"@pulumi/aws\";\nimport * as synced from \"@pulumi/synced-folder\";\n\nconst bucket = new aws.s3.Bucket(\"my-bucket\", {\n acl: aws.s3.PublicReadAcl,\n website: {\n indexDocument: \"index.html\",\n },\n});\n\nconst folder = new synced.S3BucketFolder(\"synced-folder\", {\n path: \"./my-folder\",\n bucketName: bucket.bucket,\n acl: aws.s3.PublicReadAcl,\n\n // Set this property to false to fall back to the cloud-provider CLI.\n managedObjects: false,\n});\n```\n\n```text\naws s3 sync\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.860Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":319,"estimatedTokens":2236}}346{"id":"stack-57651428","source":"stackoverflow","questionId":57651428,"title":"NuxtJs generate for dynamic websites?","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: NuxtJs generate for dynamic websites?\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm creating a simple demo app with NuxtJs. The homepage shows static content that is not changed very often. There is another route for showing a list of users: `/users`. And one for showing user's details: `/user/id`.\n\nNow my question is what's the difference between `nuxt generate` and `nuxt build`? which one should I use? \n\nI think `nuxt generate` page will not render dynamic routes like `users` and `user/id`, Am I right? If I am right, then `generate` command will generate a pre-rendered HTML for homepage only. So using `generate` is always better than using `build` right ?\n\n========================================\n\nTop Answer:\nThere are three different deployment and generation options in Nuxt.\n\n**Universal Mode**\n\nIn this mode you build your project and then you ship it to a node.js server, the first view is always rendered dynamically on the server and then turns into SPA, and works in the client. That's great for SEO, and for consuming API's but you cannot upload it to any hosting, for example on a shared VPS.\n\nSo - Node.js Host is required here.\n\n**SPA**\n\nWell basically how Vue.js works by default, virtually **no SEO at all**, you can upload it on a shared VPS hosting, because it's just an index.html and build.js file and it's working entirely on the client-side (in the browser).\n\nWe can go for a static hosting here.\n\n**Static App**\n\nThis is where Nuxt.js shines, because this mode will generate an index.html file and the corresponding js/css assets for each route you have in the dist folder, and you can then just take those numerous files, and upload them to any hosting, you don't need a server here, because your first views are already pre-rendered, unlike Universal where the node server should pre-render the first view. So you get SSR here, and your main concert as far as I understand is if you get SPA too, and that's the best part as in Universal mode, after the first request the app continues in SPA mode, how great is that eh?\n\nAnyways there are some things you should take into consideration, that if you want to generate index.html for dynamic content you need to make something that's kinda a mood killer. You need to add this to `nuxt-config.js`\n\n```\ngenerate: {\n routes: () => {\n return [\n '/posts/1'\n ]\n } \n }\n```\n\nYou can also use axios to make http request and return array here. Or even export default array from a file and include it here, where you combine all your dynamic routes. It's a one time job, but if you add new crud in your backend, that would add up 1 more request to run on executing nuxt generate that should be described in nuxt-config.\n\nSo that's the reason I would prefer to pay more for a server, but to host a Universal App, instead static generated, because that's the part that doesn't make it really great for consuming API's in my personal opinion, but it is a great future anyways.\n\n========================================\n\nCode:\n```text\n/users\n```\n\n```text\n/user/id\n```\n\n```text\nnuxt generate\n```\n\n```text\nnuxt build\n```\n\n```text\nnuxt generate\n```\n\n```text\nusers\n```\n\n```text\nuser/id\n```\n\n```text\ngenerate\n```\n\n```text\ngenerate\n```\n\n```text\nbuild\n```\n\n```text\nexport default {\n generate: {\n fallback: \"custom_sap_fallbackpage.html\"\n }\n}\n```\n\n```text\nlocation / {\n try_files $uri /custom_sap_fallbackpage.html;\n}\n```\n\n```text\nuniversal\n```\n\n```text\nnuxt generate\n```\n\n```text\nnuxt build\n```\n\n```text\nNuxt\n```\n\n```text\ntarget: static\n```\n\n```text\nNetlify\n```\n\n```text\nnuxt generate\n```\n\n```text\n/users\n```\n\n```text\n/user/:id\n```\n\n```text\nnuxt build\n```\n\n```text\nnuxt generate\n```\n\n```text\nnuxt generate\n```\n\n```text\nnuxt build\n```\n\n```text\nspa\n```\n\n```text\nnuxt generate\n```\n\n```text\nspa\n```\n\n```text\nnuxt build\n```\n\n```text\nnpm generate\n```\n\n```text\nnpm build\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnpm build\n```\n\n```text\ngenerate: {\n routes: () => {\n return [\n '/posts/1'\n ]\n } \n }\n```\n\n```text\nnuxt-config.js\n```\n\n========================================\n\nComments:\n- The generate fallback tip and nginx config totally did it for me, thanks a lot @Franci\n- Glad to help. : )","metadata":{"transformedAt":"2026-08-18T18:33:07.860Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":208,"estimatedTokens":1052}}347{"id":"stack-61910664","source":"stackoverflow","questionId":61910664,"title":"Nuxt js high CPU usage in dev environment","tags":["node.js","docker","webpack","nuxt.js"],"text":"Title: Nuxt js high CPU usage in dev environment\nTags: node.js, docker, webpack, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSince few updates my app front part in docker container doesn't work well\nIt use above 100% of Docker CPU, 60/70% of my laptop CPU (fans run at 100%)\nAnd the HMR is very slow\n\nThis issue doesn't appear on production and on others laptops\n\nI tried many things from different forums similar issues but nothing work\n\nI reseted Docker to factory defaults settings, allowed more memory and CPU\nI updated my dependencies\nI removed and restored my node modules\n\nI don't know what i should check to fix this issue\n\n`MacOS Catalina 10.15.4`\n\n`Node v13.12.0`\n\nMy package.json\n\n```\n{\n \"name\": \"front\",\n \"version\": \"1.0.1\",\n \"description\": \"My first-class Nuxt.js project\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"HOST=0.0.0.0 PORT=8080 nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint\": \"eslint --ext .js,.vue .\",\n \"precommit\": \"npm run lint\"\n },\n \"config\": {\n \"nuxt\": {\n \"host\": \"0.0.0.0\",\n \"port\": \"8080\"\n }\n },\n \"dependencies\": {\n \"@fullcalendar/core\": \"^4.3.1\",\n \"@fullcalendar/daygrid\": \"^4.3.0\",\n \"@fullcalendar/interaction\": \"^4.3.0\",\n \"@fullcalendar/timegrid\": \"^4.3.0\",\n \"@fullcalendar/vue\": \"^4.3.1\",\n \"@nuxt/webpack\": \"^2.11.0\",\n \"@nuxtjs/auth\": \"^4.5.3\",\n \"@nuxtjs/axios\": \"^5.4.1\",\n \"@nuxtjs/google-analytics\": \"^2.2.0\",\n \"@nuxtjs/google-tag-manager\": \"^2.1.4\",\n \"@nuxtjs/gtm\": \"^2.2.3\",\n \"@nuxtjs/pwa\": \"^2.6.0\",\n \"@nuxtjs/robots\": \"^2.0.0\",\n \"@nuxtjs/router\": \"^1.3.2\",\n \"@nuxtjs/sitemap\": \"^0.2.2\",\n \"algoliasearch\": \"^4.1.0\",\n \"cross-env\": \"^5.2.0\",\n \"cxlt-vue2-toastr\": \"^1.1.0\",\n \"date-fns\": \"^1.30.1\",\n \"debug\": \"^4.1.1\",\n \"gsap\": \"^2.1.3\",\n \"jquery\": \"^3.4.1\",\n \"libphonenumber-js\": \"^1.7.14\",\n \"moment\": \"^2.24.0\",\n \"node-sass\": \"^4.13.1\",\n \"nuxt\": \"^2.11.0\",\n \"nuxt-facebook-pixel-module\": \"^1.3.0\",\n \"nuxt-google-maps-module\": \"^1.6.0\",\n \"nuxt-jsonld\": \"^1.4.5\",\n \"nuxt-token-auth\": \"^1.0.2\",\n \"nuxt-user-agent\": \"^1.2.2\",\n \"sass-loader\": \"^7.1.0\",\n \"vee-validate\": \"^2.2.0\",\n \"vue\": \"^2.6.11\",\n \"vue-gallery\": \"^2.0.0\",\n \"vue-i18n\": \"^8.10.0\",\n \"vue-infinite-scroll\": \"^2.0.2\",\n \"vue-instantsearch\": \"^2.7.0\",\n \"vue-js-modal\": \"^1.3.33\",\n \"vue-lazyload\": \"^1.2.6\",\n \"vue-mq\": \"^1.0.1\",\n \"vue-multiselect\": \"^2.1.6\",\n \"vue-read-more\": \"^1.1.1\",\n \"vue-scrollto\": \"^2.15.0\",\n \"vue-sticky\": \"^3.3.4\",\n \"vue-tawk\": \"^1.0.1\",\n \"vue-upload-component\": \"^2.8.20\",\n \"vue-wait\": \"^1.3.3\",\n \"vue2-dropzone\": \"^3.5.8\",\n \"vue2-leaflet\": \"^1.2.3\",\n \"vuedraggable\": \"^2.20.0\",\n \"vuejs-datepicker\": \"^1.5.4\",\n \"vuejs-paginate\": \"^2.1.0\",\n \"vueperslides\": \"^2.7.0\"\n },\n \"devDependencies\": {\n \"babel-eslint\": \"^8.2.1\",\n \"eslint\": \"^5.16.0\",\n \"eslint-config-standard\": \"^12.0.0\",\n \"eslint-loader\": \"^2.1.2\",\n \"eslint-plugin-import\": \"^2.16.0\",\n \"eslint-plugin-node\": \"^8.0.1\",\n \"eslint-plugin-promise\": \"^4.0.1\",\n \"eslint-plugin-standard\": \"^4.0.0\",\n \"eslint-plugin-vue\": \"^4.7.1\",\n \"nodemon\": \"^1.18.10\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n \"name\": \"front\",\n \"version\": \"1.0.1\",\n \"description\": \"My first-class Nuxt.js project\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"HOST=0.0.0.0 PORT=8080 nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint\": \"eslint --ext .js,.vue .\",\n \"precommit\": \"npm run lint\"\n },\n \"config\": {\n \"nuxt\": {\n \"host\": \"0.0.0.0\",\n \"port\": \"8080\"\n }\n },\n \"dependencies\": {\n \"@fullcalendar/core\": \"^4.3.1\",\n \"@fullcalendar/daygrid\": \"^4.3.0\",\n \"@fullcalendar/interaction\": \"^4.3.0\",\n \"@fullcalendar/timegrid\": \"^4.3.0\",\n \"@fullcalendar/vue\": \"^4.3.1\",\n \"@nuxt/webpack\": \"^2.11.0\",\n \"@nuxtjs/auth\": \"^4.5.3\",\n \"@nuxtjs/axios\": \"^5.4.1\",\n \"@nuxtjs/google-analytics\": \"^2.2.0\",\n \"@nuxtjs/google-tag-manager\": \"^2.1.4\",\n \"@nuxtjs/gtm\": \"^2.2.3\",\n \"@nuxtjs/pwa\": \"^2.6.0\",\n \"@nuxtjs/robots\": \"^2.0.0\",\n \"@nuxtjs/router\": \"^1.3.2\",\n \"@nuxtjs/sitemap\": \"^0.2.2\",\n \"algoliasearch\": \"^4.1.0\",\n \"cross-env\": \"^5.2.0\",\n \"cxlt-vue2-toastr\": \"^1.1.0\",\n \"date-fns\": \"^1.30.1\",\n \"debug\": \"^4.1.1\",\n \"gsap\": \"^2.1.3\",\n \"jquery\": \"^3.4.1\",\n \"libphonenumber-js\": \"^1.7.14\",\n \"moment\": \"^2.24.0\",\n \"node-sass\": \"^4.13.1\",\n \"nuxt\": \"^2.11.0\",\n \"nuxt-facebook-pixel-module\": \"^1.3.0\",\n \"nuxt-google-maps-module\": \"^1.6.0\",\n \"nuxt-jsonld\": \"^1.4.5\",\n \"nuxt-token-auth\": \"^1.0.2\",\n \"nuxt-user-agent\": \"^1.2.2\",\n \"sass-loader\": \"^7.1.0\",\n \"vee-validate\": \"^2.2.0\",\n \"vue\": \"^2.6.11\",\n \"vue-gallery\": \"^2.0.0\",\n \"vue-i18n\": \"^8.10.0\",\n \"vue-infinite-scroll\": \"^2.0.2\",\n \"vue-instantsearch\": \"^2.7.0\",\n \"vue-js-modal\": \"^1.3.33\",\n \"vue-lazyload\": \"^1.2.6\",\n \"vue-mq\": \"^1.0.1\",\n \"vue-multiselect\": \"^2.1.6\",\n \"vue-read-more\": \"^1.1.1\",\n \"vue-scrollto\": \"^2.15.0\",\n \"vue-sticky\": \"^3.3.4\",\n \"vue-tawk\": \"^1.0.1\",\n \"vue-upload-component\": \"^2.8.20\",\n \"vue-wait\": \"^1.3.3\",\n \"vue2-dropzone\": \"^3.5.8\",\n \"vue2-leaflet\": \"^1.2.3\",\n \"vuedraggable\": \"^2.20.0\",\n \"vuejs-datepicker\": \"^1.5.4\",\n \"vuejs-paginate\": \"^2.1.0\",\n \"vueperslides\": \"^2.7.0\"\n },\n \"devDependencies\": {\n \"babel-eslint\": \"^8.2.1\",\n \"eslint\": \"^5.16.0\",\n \"eslint-config-standard\": \"^12.0.0\",\n \"eslint-loader\": \"^2.1.2\",\n \"eslint-plugin-import\": \"^2.16.0\",\n \"eslint-plugin-node\": \"^8.0.1\",\n \"eslint-plugin-promise\": \"^4.0.1\",\n \"eslint-plugin-standard\": \"^4.0.0\",\n \"eslint-plugin-vue\": \"^4.7.1\",\n \"nodemon\": \"^1.18.10\"\n }\n}\n```\n\n```text\nMacOS Catalina 10.15.4\n```\n\n```text\nNode v13.12.0\n```\n\n```text\nmodule.exports = {\n //...\n watchOptions: {\n ignored: /node_modules/\n }\n};\n```\n\n```text\nwatchers: {\n webpack: {\n ignored: /node_modules/\n }\n }\n```\n\n========================================\n\nComments:\n- There are known performance issues with host-directory bind mounts on Docker Desktop for Mac. For a browser-based application, a native Node installation might work better than trying to use Docker to simulate a native development environment.\n- Thanks, the PC fan was driving me crazy (was very loud). The nuxt.js option saved my day","metadata":{"transformedAt":"2026-08-18T18:33:07.860Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":240,"estimatedTokens":1545}}348{"id":"stack-71591902","source":"stackoverflow","questionId":71591902,"title":"Stylelint error in Nuxt (class based): Unexpected empty source (no-empty-source)","tags":["vue.js","nuxt.js","eslint","stylelint"],"text":"Title: Stylelint error in Nuxt (class based): Unexpected empty source (no-empty-source)\nTags: vue.js, nuxt.js, eslint, stylelint\nSource: Stack Overflow\n\nQuestion:\nI get this Stylelint error suddenly in two of my components, I don't know why.\n\n```\nUnexpected empty source (no-empty-source)\n```\n\nI created a third component and removed content to the point where there is no content left, and the error still shows for that component too.\nSo what can the issue be?\nI tried to understand this eslint documentation page , but I don't understand much of it, it does not explain what a \"source\" is.\n\nHere is the simplified component (which is not used in the project):\n\n```\n\n ok\n\nimport { Component, Vue } from 'nuxt-property-decorator';\n@Component\nexport default class NewComponent extends Vue {}\n\n```\n\nI get:\n\n```\ncomponents/common/NewComponent.vue\n 12:31 × Unexpected empty source no-empty-source\n```\n\n========================================\n\nCode:\n```text\nUnexpected empty source (no-empty-source)\n```\n\n```html\n<template>\n <p>ok</p>\n</template>\n\n<script lang=\"ts\">\nimport { Component, Vue } from 'nuxt-property-decorator';\n@Component\nexport default class NewComponent extends Vue {}\n</script>\n\n<style lang=\"postcss\" scoped></style>\n```\n\n```text\ncomponents/common/NewComponent.vue\n 12:31 × Unexpected empty source no-empty-source\n```\n\n```text\nstyle\n```\n\n========================================\n\nComments:\n- Line 12 column 31. Might be the empty block. Also is the error Stylelint or ESlint?\n- @kissu yes you're right it is a \"StylelintError\" (i updated the text)\n- Do you have some CSS so?\n- @kissuu Yes, sorry for late reply. It was the empty CSS block!\n- It works for SonarQube, too. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:07.860Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":72,"estimatedTokens":425}}349{"id":"stack-63719727","source":"stackoverflow","questionId":63719727,"title":"NuxtJS Static generated HTML page does not load Javascript when calling /index.html","tags":["javascript","vue.js","nuxt.js","server-side-rendering"],"text":"Title: NuxtJS Static generated HTML page does not load Javascript when calling /index.html\nTags: javascript, vue.js, nuxt.js, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nI'm working on a nuxtjs project which will be generated for static usage. Of course it uses Javascript for e.g. the Navigation, some forms and more.\n\nWhen I am using the page with *npm run dev* everything works fine.\n\nAfter exporting with *npm run build && npm run generate* I deploy the generated content from /dist to my server (cdn requested by user, in that case Google Cloud Storage) I can use the page without any problems if I dont add the *index.html* suffix.\n\nExample:\n\nVisiting https://page.com/subpage/ works fine\n\nbut\n\nVisiting https://page.com/subpage/index.html not really.\n\nYes it renders the content with CSS and DOM, but Javascript is not working at all. In the Dev-Tools of Google Chrome I can see that in both cases the javascript seems to be loaded, but not called in the second scenario. See attached Screenshots. Both were similar.\n\nhttps://i.sstatic.net/DpEFg.png\n\nMy nuxt-Config is almost empty regarding render, build-configurations. I just disabled ressourceHints and that's all. I'm not sure if this is an issue with the router only accepting the folder itself containing the index.html.. The router paths are generated dynamically by nuxtLinks.\n\nAny ideas?\n\n========================================\n\nCode:\n```text\nrouter: {\n extendRoutes(routes) {\n routes.forEach((route) => {\n // When options.generate.subFolders is true (default)\n const alias =\n route.path.length > 1 ? `${route.path}/index.html` : '/index.html'\n // When options.generate.subFolders is false\n // const normalizedRoute = route.path.replace(/\\/$/, '') // Remove trailing slashes if they exist\n // const alias =\n // route.path.length > 1 ? `${normalizedRoute}.html` : '/index.html'\n route.alias = alias\n })\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.860Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":46,"estimatedTokens":486}}350{"id":"stack-49891068","source":"stackoverflow","questionId":49891068,"title":"Nuxt.js: How to override scrollBehaviour for a single route change","tags":["javascript","scroll","vue.js","vue-router","nuxt.js"],"text":"Title: Nuxt.js: How to override scrollBehaviour for a single route change\nTags: javascript, scroll, vue.js, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a nuxt-page where I scroll to the top on every router change. We defined this in the nuxt.config.js\n\n```\nscrollBehavior (to, from, savedPosition) {\n return ({ x: 0, y: 0 })\n}\n```\n\nNow I have one single Navigation link which is a little special: «Contact» does not lead to a new page with just the contact information, but instead it should go to the footer where the contact details are written on every page.\nSo I added a link (not a nuxtlink) to link to the `#contact` anchor in the footer.\n\n```\n\n Contact\n \n```\n\nThis does not work though because it registers a route change and sets the page to the top again. (At least that is my assumption).\nI tried to execute some function to set the scrollTop property but then I see a flicker, where it scrolls a bit but is then reset to the top:\n\n```\n\n \n Contact\n \n \n```\n\nAnd I declared a method (closing nav works):\n\n```\ncloseNavAndScroll () {\n this.closeNavMenu()\n window.scrollTop(400)\n}\n```\n\nSo I thought I find some information here:\nhttps://nuxtjs.org/api/configuration-router#scrollBehavior\n\nBut as far as I could understand there is only a declaration for setting the scrollBehaviour for all routes.\nCan I somehow say whenever the route includes `#contact` I don't want the app to mess with my scroll position?\n\nThanks for any help on this.\n\nCheers\n\n========================================\n\nCode:\n```text\nscrollBehavior (to, from, savedPosition) {\n return ({ x: 0, y: 0 })\n}\n```\n\n```text\n<a class=\"Submenu__link Submenu__link--contact\" href=\"#contact\">\n Contact\n </a>\n```\n\n```text\n<li class=\"Submenu__item\">\n <a @click=\"closeNavAndScroll\" class=\"Submenu__link Submenu__link--contact\" href=\"#contact\">\n Contact\n </a>\n </li>\n```\n\n```text\ncloseNavAndScroll () {\n this.closeNavMenu()\n window.scrollTop(400)\n}\n```\n\n```text\n#contact\n```\n\n```text\n#contact\n```\n\n```text\nscrollBehavior (to, from, savedPosition) {\n if (to.hash) {\n return {selector: to.hash}\n } else {\n return {x: 0, y: 0}\n }\n}\n```\n\n```text\n#contact\n```\n\n========================================\n\nComments:\n- See also reddit.com/r/vuejs/comments/5okcgo/… where they add `if (savedPosition) { return savedPosition }`\n- Hello, in case you have time to look at this, than you","metadata":{"transformedAt":"2026-08-18T18:33:07.860Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":109,"estimatedTokens":597}}351{"id":"stack-61648561","source":"stackoverflow","questionId":61648561,"title":"Disable scrolling and handle Close method for Sidebar in BootstrapVue","tags":["vue.js","nuxt.js","bootstrap-vue"],"text":"Title: Disable scrolling and handle Close method for Sidebar in BootstrapVue\nTags: vue.js, nuxt.js, bootstrap-vue\nSource: Stack Overflow\n\nQuestion:\nI would like to ask 2 questions about **Sidebar** in **BootstrapVue**.\n\n- **Disable scrolling** after opened Sidebar\n\n- How to **handle closing method** when click outside the Sidebar (**Backdrop**)\n\nI'm using https://bootstrap-vue.org/docs/components/sidebar\n\nhttps://i.sstatic.net/kQn2z.png\n\n```\n\n \n Toggle sSidebar\n \n \n \n Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis\n in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.\n \n\n \n \n \n \n\n```\n\n**Thank you and appreciate.**\n\n========================================\n\nCode:\n```text\n<template>\n <div>\n <b-button v-b-toggle.sidebar-backdrop>Toggle sSidebar</b-button>\n <b-sidebar\n id=\"sidebar-backdrop\"\n title=\"Sidebar with backdrop\"\n backdrop\n shadow\n >\n <div class=\"px-3 py-2\">\n <p>\n Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis\n in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.\n </p>\n <b-img src=\"https://picsum.photos/500/500/?image=54\" fluid thumbnail></b-img>\n </div>\n </b-sidebar>\n </div>\n</template>\n```\n\n```js\nnew Vue({\n el: '#app',\n methods: {\n toggleBodyScrollbar(visible) {\n const body = document.getElementsByTagName('body')[0];\n\n if(visible)\n body.classList.add(\"overflow-hidden\");\n else\n body.classList.remove(\"overflow-hidden\");\n }\n }\n})\n```\n\n```html\n<link href=\"https://unpkg.com/bootstrap@4.4.1/dist/css/bootstrap.min.css\" rel=\"stylesheet\" />\n<link href=\"https://unpkg.com/bootstrap-vue@2.13.0/dist/bootstrap-vue.css\" rel=\"stylesheet\" />\n\n<script src=\"https://unpkg.com/babel-polyfill/dist/polyfill.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js\"></script>\n<script src=\"https://unpkg.com/bootstrap-vue@2.13.0/dist/bootstrap-vue.js\"></script>\n\n<div id=\"app\">\n <b-sidebar id=\"sidebar-1\" title=\"Sidebar\" shadow backdrop @change=\"toggleBodyScrollbar\">\n <div class=\"px-3 py-2\">\n <p>\n Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis\n in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.\n </p>\n <b-img src=\"https://picsum.photos/500/500/?image=54\" fluid thumbnail></b-img>\n </div>\n </b-sidebar>\n \n <p v-for=\"i in 10\">Some content</p>\n <b-button v-b-toggle.sidebar-1>Toggle Sidebar</b-button>\n <p v-for=\"i in 10\">Some content</p>\n</div>\n```\n\n```text\noverflow-hidden\n```\n\n```text\n@change\n```\n\n```text\n@hidden\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.860Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":112,"estimatedTokens":686}}352{"id":"stack-60163870","source":"stackoverflow","questionId":60163870,"title":"Auth not accessible in vuex-module after page reload or direct access","tags":["vue.js","vuex","nuxt.js"],"text":"Title: Auth not accessible in vuex-module after page reload or direct access\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have an authentication on my nuxt web-app, using the nuxt/auth module. I also use modular vuex stores to handle different states. After I login, everything is fine and I can navigate through the app normally. But when I try to reload the page or access it directly through a URL, the user is not accessible, thus, the whole web-app becomes unusable. I try to access the user object with `this.context.rootState.auth.user`, which is null after page-reload or direct access. Strangely enough, this only happens in production.\n\nI already tried to add an if-guard, but sadly the getter is not reactive. Probably because it´s a nested object. This is my current getter:\n\n```\nget someGetter() {\n if (!this.context.rootState.auth.user) {\n return []\n }\n const userId = this.context.rootState.auth.user.id as string\n const arr = []\n for (const item of this.items) {\n // Using userId to add something to arr\n }\n return arr\n }\n```\n\nIs there a way to force nuxt to finish the authentication before initialising the vuex-modules, or to make this getter reactive, so it will trigger again, when the user object is accessible?\n\nThis is what my auth-config looks like in nuxt.config.ts:\n\n```\nauth: {\n strategies: {\n local: {\n _scheme: '@/auth/local-scheme',\n endpoints: {\n login: {\n url: '/api/authenticate',\n method: 'post',\n propertyName: false\n },\n logout: { url: '/api/logout', method: 'post' },\n user: { url: '/api/users/profile', propertyName: false }\n }\n },\n // This dummy setting is required so we can extend the default local scheme\n dummy: {\n _scheme: 'local'\n }\n },\n redirect: {\n logout: '/login'\n }\n}\n```\n\n**EDIT**\n\nI resolved this by following Raihan Kabir´s answer. Using vuex-persistedstate in an auth-plugin, which is triggered every time the server renders the page. The plugin saves the userId in a cookie, so the store can use it as a fallback, if the auth-module isn´t ready.\n\n========================================\n\nCode:\n```text\nget someGetter() {\n if (!this.context.rootState.auth.user) {\n return []\n }\n const userId = this.context.rootState.auth.user.id as string\n const arr = []\n for (const item of this.items) {\n // Using userId to add something to arr\n }\n return arr\n }\n```\n\n```text\nauth: {\n strategies: {\n local: {\n _scheme: '@/auth/local-scheme',\n endpoints: {\n login: {\n url: '/api/authenticate',\n method: 'post',\n propertyName: false\n },\n logout: { url: '/api/logout', method: 'post' },\n user: { url: '/api/users/profile', propertyName: false }\n }\n },\n // This dummy setting is required so we can extend the default local scheme\n dummy: {\n _scheme: 'local'\n }\n },\n redirect: {\n logout: '/login'\n }\n}\n```\n\n```text\nthis.context.rootState.auth.user\n```\n\n```text\nexport const actions = {\n // This one runs on the beginning of reload/refresh\n nuxtServerInit ({ commit }, { req }) {\n if (req.headers.cookie) {\n const parsed = cookieparser.parse(req.headers.cookie)\n try {\n // get user id that you would set on auth as Cookie\n user_id = parsed.uid\n } catch (err) {\n // error here...\n }\n }\n\n // perform login and store info on vuex store\n commit('authUserOnReload', user_id)\n },\n}\n\n// Define Mutations\nexport const mutations = {\n authUserOnReload (state, user_id) {\n // perform login here and store user\n }\n}\n```\n\n```text\nvuex\n```\n\n```text\nvuex\n```\n\n```text\nuser_id\n```\n\n```text\nvuex\n```\n\n```text\nindex.js\n```\n\n========================================\n\nComments:\n- Same problem here.","metadata":{"transformedAt":"2026-08-18T18:33:07.860Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":155,"estimatedTokens":955}}353{"id":"stack-60940012","source":"stackoverflow","questionId":60940012,"title":"Set Session ID Cookie in Nuxt Auth","tags":["django","nuxt.js"],"text":"Title: Set Session ID Cookie in Nuxt Auth\nTags: django, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have the following set up in my nuxt.config.js file:\n\n```\nauth: {\nredirect: {\n login: '/accounts/login',\n logout: '/',\n callback: '/accounts/login',\n home: '/'\n},\nstrategies: {\n local: {\n endpoints: {\n login: { url: 'http://localhost:8000/api/login2/', method: 'post' },\n user: {url: 'http://localhost:8000/api/user/', method: 'get', propertyName: 'user' },\n tokenRequired: false,\n tokenType: false\n }\n }\n},\nlocalStorage: false,\ncookie: true\n},\n```\n\nI am using django sessions for my authentication backend, which means that upon a successful login, i will have received a session-id in my response cookie. When i authenticate with nuxt however, i see the cookie in the response, but the cookie is not saved to be used in further requests. Any idea what else i need to be doing?\n\n========================================\n\nTop Answer:\nThe cookie is sent by the server but the client won't read it, until you set the property `withCredentials` in your client request (about withCredentials read here)\n\nTo fix your problem you have to extend your auth config with `withCredentials` property.\n\n```\nendpoints: {\n login: { \n url: 'http://localhost:8000/api/login2/', \n method: 'post'\n withCredentials: true \n }\n }\n```\n\nAlso don't forget to set CORS policies on your server as well to support cookie exchange\n\nExample from ExpressJS\n\n```\napp.use(cors({ credentials: true, origin: \"http://localhost:8000\" }))\n```\n\nMore information about this issue on auth-module github\n\n========================================\n\nCode:\n```text\nauth: {\nredirect: {\n login: '/accounts/login',\n logout: '/',\n callback: '/accounts/login',\n home: '/'\n},\nstrategies: {\n local: {\n endpoints: {\n login: { url: 'http://localhost:8000/api/login2/', method: 'post' },\n user: {url: 'http://localhost:8000/api/user/', method: 'get', propertyName: 'user' },\n tokenRequired: false,\n tokenType: false\n }\n }\n},\nlocalStorage: false,\ncookie: true\n},\n```\n\n```text\nimport state from \"./state\";\nimport * as actions from \"./actions\";\nimport * as mutations from \"./mutations\";\nimport * as getters from \"./getters\";\n\nexport default {\n state,\n getters,\n mutations,\n actions,\n modules: {},\n};\n```\n\n```text\nexport default () => ({\n user: null,\n isAuthenticated: false,\n});\n```\n\n```text\nexport async function nuxtServerInit({ commit }, { _req, res }) {\n await this.$axios\n .$get(\"/api/users/profile\")\n .then((response) => {\n commit(\"setUser\", response);\n commit(\"setAuthenticated\", true);\n })\n .catch((error) => {\n commit(\"setErrors\", [error]); // not covered in this demo\n commit(\"setUser\", null);\n commit(\"setAuthenticated\", false);\n res.setHeader(\"Set-Cookie\", [\n `session=false; expires=Thu, 01 Jan 1970 00:00:00 GMT`,\n `authUser=false; expires=Thu, 01 Jan 1970 00:00:00 GMT`,\n ]);\n });\n}\n```\n\n```text\nexport const setUser = (state, payload) => (state.user = payload);\nexport const setAuthenticated = (state, payload) =>\n (state.isAuthenticated = payload);\n```\n\n```text\nexport const getUser = (state) => state.user;\nexport const isAuthenticated = (state) => state.isAuthenticated;\n```\n\n```text\nexport default function ({ app, redirect, _route, _req }) {\n if (!app.store.state.user || !app.store.state.isAuthenticated) {\n return redirect(\"/auth/login\");\n }\n}\n```\n\n```text\nexport default function ({ app, redirect, _req }) {\n if (app.store.state.user) {\n if (app.store.state.user.roles.includes(\"customer\")) {\n return redirect({\n name: \"panel\",\n params: { username: app.store.state.user.username },\n });\n } else if (app.store.state.user.roles.includes(\"admin\")) {\n return redirect(\"/admin/dashboard\");\n } else {\n return redirect({\n name: \"panel\",\n });\n }\n } else {\n return redirect(\"/\");\n }\n}\n```\n\n```text\nasync userLogin() {\n if (this.form.username !== \"\" && this.form.password !== \"\") {\n await this.$axios\n .post(\"/api/auth/login\", this.form)\n .then((response) => {\n this.$store.commit(\"setUser\", response.data);\n this.$store.commit(\"setAuthenticated\", true);\n this.$cookies.set(\"authUser\", JSON.stringify(response.data), {\n maxAge: 60 * 60 * 24 * 7,\n });\n if (this.$route.query.redirect) {\n this.$router.push(this.$route.query.redirect);\n }\n this.$router.push(\"/panel\");\n })\n .catch((e) => {\n this.$toast\n .error(\"Error logging in\", { icon: \"error\" })\n .goAway(800);\n```\n\n```js\nendpoints: {\n login: { \n url: 'http://localhost:8000/api/login2/', \n method: 'post'\n withCredentials: true \n }\n }\n```\n\n```js\napp.use(cors({ credentials: true, origin: \"http://localhost:8000\" }))\n```\n\n```text\nwithCredentials\n```\n\n```text\nwithCredentials\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.860Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":210,"estimatedTokens":1228}}354{"id":"stack-62174248","source":"stackoverflow","questionId":62174248,"title":"Access route in store.js (Vuex/Nuxt)","tags":["nuxt.js"],"text":"Title: Access route in store.js (Vuex/Nuxt)\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHow can I access the route in the store.js file? \n\nI want access to `path` and `fullPath` in store.js.\n\n========================================\n\nTop Answer:\nin your store, try with:\n\n```\nthis.app.router;\n// for example :\nthis.app.router.push('/');\n```\n\nIn this case:\n\n```\nconst correntPathInfo = this.app.router.currentRoute;\nconsole.log(correntPathInfo);\n```\n\nCheck this `issues` doc:\n\n- https://github.com/nuxt/nuxt.js/issues/1384#issuecomment-348274658\n\n========================================\n\nCode:\n```text\npath\n```\n\n```text\nfullPath\n```\n\n```text\nfullPath\n```\n\n```text\nthis.$router.currentRoute.fullPath\n```\n\n```text\nthis.$router.currentRoute.query\n```\n\n```js\nthis.app.router;\n// for example :\nthis.app.router.push('/');\n```\n\n```js\nconst correntPathInfo = this.app.router.currentRoute;\nconsole.log(correntPathInfo);\n```\n\n```text\nissues\n```\n\n========================================\n\nComments:\n- Why you need that? Viex has no path?\n- `this` is undefined inside store, how is this a proper answer?","metadata":{"transformedAt":"2026-08-18T18:33:07.860Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":74,"estimatedTokens":274}}355{"id":"stack-51849489","source":"stackoverflow","questionId":51849489,"title":"Nginx returns 400 error in Safari","tags":["ajax","nginx","safari","axios","nuxt.js"],"text":"Title: Nginx returns 400 error in Safari\nTags: ajax, nginx, safari, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying send form with `Content-type: multipart/form-data`. All works fine in the Chrome, FF, Edge but not in Safari. It gets 400 from nginx\n\nUsed Laravel + Nuxtjs + Axios\n\nAfter enabling error_log debug in the nginx conf I see \n\n`[info] 11687#11687: *1 client prematurely closed stream: only 767 out of 907 bytes of request body received`\n\n========================================\n\nCode:\n```text\nContent-type: multipart/form-data\n```\n\n```text\n[info] 11687#11687: *1 client prematurely closed stream: only 767 out of 907 bytes of request body received\n```\n\n```text\n$('#myForm').find(\"input[type='file']\").each(function(){\n if ($(this).get(0).files.length === 0) {$(this).remove();}\n});\nvar fData = new FormData($('#myForm')[0]);\n```\n\n========================================\n\nComments:\n- Are you using self signed certificate? Can you disclose the endpoint config?\n- No. I found a problem. The problem was submitting form without file","metadata":{"transformedAt":"2026-08-18T18:33:07.860Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":36,"estimatedTokens":264}}356{"id":"stack-58763577","source":"stackoverflow","questionId":58763577,"title":"Disable default nuxt.js routing","tags":["javascript","nuxt.js"],"text":"Title: Disable default nuxt.js routing\nTags: javascript, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to disable the default routing of nuxt?\n\nI have an spa, which should run on different subfolders/urls, but somehow the js is not kicking in properly. And i think because nuxt takes over the routing.\n\nOr do you have other ideas how to get this running?\n\n========================================\n\nCode:\n```text\nrouter.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.860Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":17,"estimatedTokens":109}}357{"id":"stack-54958289","source":"stackoverflow","questionId":54958289,"title":"How to create an optional param in nested routes in Nuxt.js?","tags":["vue.js","vuejs2","vue-router","nuxt.js"],"text":"Title: How to create an optional param in nested routes in Nuxt.js?\nTags: vue.js, vuejs2, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nin a nuxt.js app, I have nested routes like this:\n`route-1/route-2/route-3`\n\nI want to add an optional param after `route-1` to render the same old route but with extra info(item id or something like that), which mean it will map to 2 route formats\n\n`route-1/:param/route-2/route-3` or `route-1/route-2/route-3`\n\nwithout duplicate my folder structure \n\nif I add a file with the param name it will be a required param and I will have to duplicate the folder structure without this param to handle the 2 scenarios\n\n========================================\n\nCode:\n```text\nroute-1/route-2/route-3\n```\n\n```text\nroute-1\n```\n\n```text\nroute-1/:param/route-2/route-3\n```\n\n```text\nroute-1/route-2/route-3\n```\n\n```text\npages/\n--| search/\n----| index.vue\n--| index.vue\n```\n\n```text\n// nuxt.config.js\n\nexport default {\n router: {\n middleware: [...],\n extendRoutes (routes, resolve) {\n routes.push({\n name: 'search-category',\n path: '/search/:category',\n component: resolve(__dirname, 'pages/search/index.vue'),\n chunkName: 'pages/search/_category/index'\n })\n }\n }\n}\n```\n\n```text\n// nuxt.config.js\n\nexport default {\n router: {\n middleware: [...],\n extendRoutes (routes, resolve) {\n routes.push({\n name: 'my-new-route',\n path: '/route-1/:param/route-2/route-3',\n component: resolve(__dirname, 'pages/same-route/index.vue'),\n chunkName: 'pages/same-route/_param/index'\n })\n }\n }\n}\n```\n\n```text\n// nuxt.config.js\n\nexport default {\n i18n: {\n pages: {\n 'search/index': { // <-- route in pages tree\n es: '/buscar',\n en: '/search'\n },\n 'search/_category/index': { // <-- dynamic route configured\n es: '/buscar/:category',\n en: '/search/:category'\n }\n }\n }\n}\n```\n\n```text\n/search\n```\n\n```text\n/search/my-category\n```\n\n```text\nmy-category\n```\n\n```text\n$route.params.category\n```\n\n```text\nchunkName\n```\n\n```text\nnuxtI18n\n```\n\n========================================\n\nComments:\n- Did you resolve this ?\n- in my case, I changed the implementation of my feature to avoid this situation, but the only solution I found in my mind is to extend my routes inside a js file and not depend on the Nuxt.js way to define my routes.\n- yeah, I solved this situation by the same idea but I forgot to write the solution. Good job @lmfresneda\n- For anyone looking to achieve the same thing in Nuxt 3, here's how you do it – stackoverflow.com/questions/77135909/…","metadata":{"transformedAt":"2026-08-18T18:33:07.860Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":128,"estimatedTokens":657}}358{"id":"stack-58848910","source":"stackoverflow","questionId":58848910,"title":"How can I access HEAD data in component with nuxt?","tags":["vue.js","nuxt.js","vue-meta"],"text":"Title: How can I access HEAD data in component with nuxt?\nTags: vue.js, nuxt.js, vue-meta\nSource: Stack Overflow\n\nQuestion:\nIn a page, I set head title like this:\n\n```\n...\n\nexport default {\n head() {\n return {\n title: this.post.name\n }\n }\n}\n\n```\n\nHow can I get this data in another component?\n\nI tried with `this.$metaInfo` but my component where I need to get data is in the layout outside ``...\n\nAlso, If the current route is in a child page with populated head, it's override the parent title. So, how do I do?\n\n========================================\n\nTop Answer:\nyou can walk up the component tree until you reach the page-component\n\n```\nmetaInfoTitle() {\n let curr = this\n let title = null\n do {\n title = curr?.$metaInfo?.title\n curr = curr.$parent\n } while (!title && curr)\n return title\n},\n```\n\n========================================\n\nCode:\n```html\n...\n<script>\nexport default {\n head() {\n return {\n title: this.post.name\n }\n }\n}\n</script>\n```\n\n```text\nthis.$metaInfo\n```\n\n```text\n<nuxt />\n```\n\n```text\nexport const state = {\n title: 'Default Title'\n}\n\nexport const mutations = {\n SET_TITLE (state, title) {\n state.title= title\n }\n}\n```\n\n```text\n<template>\n <div></div>\n</template>\n\n<script>\nexport default {\n head () {\n return {\n title: this.title\n }\n },\n mounted () {\n this.$store.commit('SET_TITLE', this.$metaInfo.title)\n }\n}\n</script>\n```\n\n```text\n<template>\n <div></div>\n</template>\n\n<script>\nimport { mapState } from 'vuex'\nexport default {\n computed: {\n ...mapState({\n title: state => state.title\n })\n }\n}\n</script>\n```\n\n```text\nthis.$metaInfo\n```\n\n```text\nstore\n```\n\n```text\nmetaInfoTitle() {\n let curr = this\n let title = null\n do {\n title = curr?.$metaInfo?.title\n curr = curr.$parent\n } while (!title && curr)\n return title\n},\n```\n\n========================================\n\nComments:\n- Thanks for your response! But I want to avoid using vuex, and writing in all page a mounted instruction just for that. I think this pattern duplicate code with same concern. Another solution I found is write a middleware that handle route.meta and populate the store. But again, it looks overcomplicated...\n- Also, what's happen for sub-route? If parent route and child route commit to store, is there conflit?\n- Hey @ManUtopiK, you can avoid duplicating code in all component **mounted** methods just moving this for a vue **mixins** and adding in the pages you need. Talking about the sub-routes, in this context the vuex will be rewritten using the last page. Did you think about adding a **prop** for the title in the child components that you need this and just pass $metaInfo.title in this? May can be an option for you also.","metadata":{"transformedAt":"2026-08-18T18:33:07.860Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":141,"estimatedTokens":676}}359{"id":"stack-52099638","source":"stackoverflow","questionId":52099638,"title":"Nuxt/Vue reactive body attributes","tags":["vue.js","vuex","nuxt.js"],"text":"Title: Nuxt/Vue reactive body attributes\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to add the class `menu-opened` on the `body` tag when I click on the menu burger div.\n\n**My div**\n\n```\n\n```\n\n**The openMenu method**\n\n```\nmethods: {\n openMenu() {\n console.log('open menu launch')\n this.$store.dispatch('menu/setMenu', true)\n }\n }\n```\n\n**My store**\n\n```\nstate = {\n isMenuOpen: false\n}\n\nactions = {\n setMenu({ commit }, value) {\n commit('SET_MENU_OPEN_STATUS', value)\n }\n}\n\nmutations= {\n SET_MENU_OPEN_STATUS(state, newState){\n state.isMenuOpen = newState\n }\n}\n```\n\nOn my template, i got this code to add the class on the body based on the state of the isMenuOpen value : \n\n```\nexport default {\n data() {\n return {\n menuState: this.$store.state.isMenuOpen\n }\n },\n head () {\n return {\n bodyAttrs: {\n class: this.menuState ? 'menu-opened' : ''\n }\n }\n }\n}\n```\n\n My store is working well, the value change when I click on my div, but it's not adding the class, like if the head function is not reactive...\n\nThanks for your help\n\n========================================\n\nTop Answer:\nYou could do something like this:\n\n**My div**\n\n```\n\n```\n\n**The openMenu method**\n\n```\nmethods: {\n openMenu() {\n console.log('open menu launch')\n this.$refs.myDiv.closest('body').classList.add(\"menu-opened\")\n }\n }\n```\n\nAnd then you need to implement similar functionality for the close-menu button, only using:\n\n```\nthis.$refs.myDiv.closest('body').classList.remove(\"menu-opened\")\n```\n\n========================================\n\nCode:\n```text\n<div v-on:click=\"openMenu\"></div>\n```\n\n```text\nmethods: {\n openMenu() {\n console.log('open menu launch')\n this.$store.dispatch('menu/setMenu', true)\n }\n }\n```\n\n```text\nstate = {\n isMenuOpen: false\n}\n\nactions = {\n setMenu({ commit }, value) {\n commit('SET_MENU_OPEN_STATUS', value)\n }\n}\n\nmutations= {\n SET_MENU_OPEN_STATUS(state, newState){\n state.isMenuOpen = newState\n }\n}\n```\n\n```text\nexport default {\n data() {\n return {\n menuState: this.$store.state.isMenuOpen\n }\n },\n head () {\n return {\n bodyAttrs: {\n class: this.menuState ? 'menu-opened' : ''\n }\n }\n }\n}\n```\n\n```text\nmenu-opened\n```\n\n```text\nbody\n```\n\n```text\nexport default {\n data() {\n return {\n menuState: this.$store.state.isMenuOpen\n }\n },\n head () {\n return {\n bodyAttrs: {\n class: this.isMenuOpen ? 'menu-opened' : ''\n }\n }\n },\n computed: {\n isMenuOpen () {\n return this.$store.state.isMenuOpen\n }\n },\n watch: {\n isMenuOpen () {\n this.head()\n }\n }\n}\n```\n\n```text\nconst bodyElement = document.querySelector('body')\nbodyElement.classList.add('a');\nbodyElement.classList.remove('b');\nbodyElement.classList.toggle('c');\n```\n\n```text\nhead()\n```\n\n```text\nwatcher\n```\n\n```text\nmounted\n```\n\n```text\nbeforeDestroy\n```\n\n```text\n<div v-on:click=\"openMenu\" ref=\"myDiv\"></div>\n```\n\n```text\nmethods: {\n openMenu() {\n console.log('open menu launch')\n this.$refs.myDiv.closest('body').classList.add(\"menu-opened\")\n }\n }\n```\n\n```text\nthis.$refs.myDiv.closest('body').classList.remove(\"menu-opened\")\n```\n\n========================================\n\nComments:\n- Can you show the code / template that includes ``?\n- This is the nuxt HTML model here : fr.nuxtjs.org/guide/views/#document\n- If i place this on a layout, i get `this.head is not a function` as an error and rendering fails\n- Calling `this.head()` has no effect.\n- This is great answer, but works only in nuxt. In question there is nuxt/vue, so if it is disliked then only because of users of pure vue.\n- It's an old question , but i managed to do this in Nuxt like your answer, i'm updating the values in the store and use the store values in default.vue to update the bodyAttrs... i just have one issue , there is a latency when updating the classes , i can see that the values are updating in DevTools but the classes are not updating at the same time ... i use the same values from the store on three places to update the classes ... i created a gif for better understanding... anyone has a clue what am i doing wrong ... gifyu.com/image/FjPD","metadata":{"transformedAt":"2026-08-18T18:33:07.861Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":230,"estimatedTokens":1061}}360{"id":"stack-76783532","source":"stackoverflow","questionId":76783532,"title":"Vite: Is there a possibility to exclude code elements from being built?","tags":["javascript","vue.js","nuxt.js","vite"],"text":"Title: Vite: Is there a possibility to exclude code elements from being built?\nTags: javascript, vue.js, nuxt.js, vite\nSource: Stack Overflow\n\nQuestion:\nI'm looking for a \"feature\" in Vite which will allow me to exclude some code from being built. As far as I remember in webpack there was a feature when you could create some comments like:\n\n```\n###SOMETHING\n`###END_SOMETHING\n```\n\nand this code between ###SOMETHING and ###END_SOMETHING wasn't included in output files during build process. Is there relative feature available in Vite or maybe there is another way to perform such a action? Basically code between these \"tags\" needs to be in file and working during vite dev`, but it needs to be omitted by `vite build`.\n\nI've found rollup settings but it only includes whole files.\n\n========================================\n\nCode:\n```js\n###SOMETHING\n<code goes here>\n###END_SOMETHING\n```\n\n```text\nvite dev\n```\n\n```text\nvite build\n```\n\n```text\nif (import.meta.env.DEV) {\n // code runs in vite dev\n}\n```\n\n```text\nimport.meta.env\n```\n\n```text\nvite dev\n```\n\n```text\nvite build\n```\n\n```text\n--mode\n```\n\n```text\nimport.meta.env.DEV\n```\n\n========================================\n\nComments:\n- are you thinking about `/*` and `*/`?\n- No no, I don't want code to be commented, I want it to be working, but just omitted while built.\n- what does it mean? If you don't include code in the build it won't work.\n- As I said in the post, code needs to be there in source file and needs to be working during `vite dev`, it just needs to be omitted while using `vite build`. I've updated the post so it's now more clear what do I mean. :)\n- There's also the `dropLabels` option in esbuild, but for some reason it doesn't seem to work with the current version of Vite. I posted a separate (but related) question about this here: Can I get Vite to drop certain lines of code using the 'dropLabels' option?\n- Thank you, it should do the job. :)\n- If it is also necessary to exclude some imports in some build environments (specifically in SSR or non-SSR contexts), the plugin `vite-plugin-iso-import` will make that possible: github.com/bluwy/vite-plugin-iso-import\n- But this will generate a `if (false)` in production code!\n- @Paper_Folding which allows the bundler to optimize the whole block away during treeshaking\n- Okay, I also find another way, because mostly I'm using console to logging, setting `build.rolldownOptions.output.minify.compress.dropConsole` to `true` also suits my need.","metadata":{"transformedAt":"2026-08-18T18:33:07.861Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":72,"estimatedTokens":622}}361{"id":"stack-64603780","source":"stackoverflow","questionId":64603780,"title":"How to fix this error [Vue warn]: Unknown custom element: in unit testing with Jest","tags":["vue.js","nuxt.js"],"text":"Title: How to fix this error [Vue warn]: Unknown custom element: in unit testing with Jest\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a problem running the npm run test. The error is\n\n```\n[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the \"name\" option.\n```\n\nSidebarCMS.spect.js\n\n```\nimport { shallowMount } from \"@vue/test-utils\";\nimport SidebarCMS from \"../layouts/SidebarCMS\";\n\nconst factory = () => {\n return shallowMount(SidebarCMS, {});\n};\n\ndescribe(\"SidebarCMS\", () => {\n\n test(\"renders properly\", () => {\n const wrapper = factory();\n expect(wrapper.html()).toMatchSnapshot();\n });\n});\n```\n\nCan anyone help me?\n\n========================================\n\nTop Answer:\nThe accepted answer from Naren works, but does not account for all use cases.\n\n**Use case 1:**\n\nI don't need to access inner elements of the NuxtLink.\n=> Stubbing is a good option, so this leads to the answert from Naren:\n\n```\nconst wrapper = shallowMount(SidebarCMS, {\n props,\n global: {\n stubs: {\n 'nuxt-link': true,\n },\n },\n});\n```\n\n**Use case 2:**\n\nI want to access inner elements of the NuxtLink for some reasons.\n=> Stubbing won't work, instead we can define a custom component in the test file:\n\nNote: We still need to list NuxtLink in the stubs and set it to false:\n\n```\nwrapper = shallowMount(SidebarCMS, {\n props,\n global: {\n stubs: {\n 'nuxt-link': false,\n },\n components: {\n 'nuxt-link': {\n template: '',\n },\n },\n },\n});\n```\n\nWhat this does is replacing the nuxt-link with the template you define for it. Used html elements inside are kept, the attributes (like classes or the \"to\" attribute) are automatically applied.\n\nThis means, given the following usage of nuxt-link\n\n```\nItemContent\n```\n\n, the output of wrapper.html will then be\n\n```\nItemContent\n```\n\n========================================\n\nCode:\n```text\n[Vue warn]: Unknown custom element: <nuxt-link> - did you register the component correctly? For recursive components, make sure to provide the \"name\" option.\n```\n\n```text\nimport { shallowMount } from \"@vue/test-utils\";\nimport SidebarCMS from \"../layouts/SidebarCMS\";\n\nconst factory = () => {\n return shallowMount(SidebarCMS, {});\n};\n\ndescribe(\"SidebarCMS\", () => {\n\n test(\"renders properly\", () => {\n const wrapper = factory();\n expect(wrapper.html()).toMatchSnapshot();\n });\n});\n```\n\n```text\nconst factory = () => {\n return shallowMount(SidebarCMS, {\n stubs: {\n 'nuxt-link': true,\n 'any-other-child': true\n }\n });\n};\n```\n\n```text\nstub\n```\n\n```text\nconst wrapper = shallowMount(SidebarCMS, {\n props,\n global: {\n stubs: {\n 'nuxt-link': true,\n },\n },\n});\n```\n\n```text\nwrapper = shallowMount(SidebarCMS, {\n props,\n global: {\n stubs: {\n 'nuxt-link': false,\n },\n components: {\n 'nuxt-link': {\n template: '<a><slot/></a>',\n },\n },\n },\n});\n```\n\n```text\n<nuxt-link\n to=\"www.example.com\"\n class=\"item-class\"\n><div>ItemContent</div></nuxt-link>\n```\n\n```text\n<a to=\"www.example.com\" class=\"item-class\"><div>ItemContent</div></a>\n```\n\n========================================\n\nComments:\n- Omg, finally something that works. I have been looking everywhere!","metadata":{"transformedAt":"2026-08-18T18:33:07.861Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":171,"estimatedTokens":806}}362{"id":"stack-57406531","source":"stackoverflow","questionId":57406531,"title":"nuxt link is updating route, but not changing contents","tags":["vue-router","nuxt.js"],"text":"Title: nuxt link is updating route, but not changing contents\nTags: vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using nuxt version 2.8.1 for my website. Everything works fine, except nuxt-link on some pages.\nI have a page, **/drinks** which is the listing page for *drinks* and **/drinks/{slug}** which is the *detail page*.\n\nI first noticed the problem, in **/drinks**. None of the nuxt-link was working in that page. It got solved when I removed code that displays\nvalidation error message from the form that is in separate component.\n\n```\n{{ errors ? errors.first('name') : '' }}\n```\n\nSo, everything works on this page now. But, the *detail page* still has this problem. There is no components using validation in this page. No erros or warnings, in nuxt console, or browser console. Links just doesn't work. It updates the url, but, contents are not changed at all.\n\nchanging nuxt link to anchor tags works.\n\nAnother thing is, if I click any *drinks* in listing page to go to *detail page*, it works fine. Every link works. But, if I reload that page, or go to that *detail page* directly with URL, then *nuxt link* doesn't work.\n\nI don't know, what is the problem exactly. How can, using *vee validation* in one component affect *nuxt link* in other components? And why is it not working?\n\n========================================\n\nCode:\n```text\n<span class='text-danger small'>{{ errors ? errors.first('name') : '' }}</span>\n```\n\n========================================\n\nComments:\n- Please provide a minimal, reproducible example.\n- Helped me a big time. Now I need to figure out all the places where I do not have ssr. How to do it?","metadata":{"transformedAt":"2026-08-18T18:33:07.861Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":35,"estimatedTokens":414}}363{"id":"stack-69793553","source":"stackoverflow","questionId":69793553,"title":"Vue event handler sometimes getting $event object passed and sometimes not","tags":["vue.js","nuxt.js"],"text":"Title: Vue event handler sometimes getting $event object passed and sometimes not\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a situation like this: In a component called \"ProductForm\" I have a method \"addToCart\", which will add some product to a cart in an online shop. This is called via button click event.\n\nNow I added a new child component \"GiftUpsell\", which is essentially just an additional \"Add to Cart\" button. But it should additionally add another product, passed as parameter to handleAddToCart.\n\nSo I modified the handleAddToCart method in ProductForm to accept an optional parameter, as below, and I pass this parameter via an event from the child component \"GiftUpsell\":\n\nProductForm.vue\n\n```\n\n Add to Cart\n \n\nimport GiftUpsell from '~/components/GiftUpsell'\n\nexport default {\n components: { GiftUpsell },\n methods: {\n handleAddToCart(upsellLineItem = null) {\n // ...\n }\n }\n}\n```\n\nGiftUpsell.vue\n\n```\n\n Add to cart with upsell\n\nexport default {\n methods: {\n createUpsellLineItem() {\n // whatever\n return some object;\n },\n\n upsellAddToCart() {\n const lineItem = createUpsellLineItem();\n this.$emit('upsell-add-to-cart', lineItem);\n }\n }\n}\n```\n\nThe problem now is: When I use the new upsell add-to-cart button, it works fine. The `lineItem` parameter is passed as the *only* parameter to `handleAddToCart` and the logic works.\n\nWhen I, however, click on the old, \"normal\" add-to-cart button, the `handleAddToCart` method gets the `$event` as first parameter - which is not present when `handleAddToCart` is called via the `upsell-add-to-cart` event.\n\nThis is confusing. Why is the $event parameter present when I don't need it, and only the event parameters present (but not event object) when I need the parameters? Is there a way to get rid of this inconsistency?\n\n========================================\n\nCode:\n```html\n<template>\n <btn @click.native=\"handleAddToCart\">Add to Cart</btn>\n <gift-upsell @upsellAddToCart=\"handleAddToCart\" />\n</template>\n\n<script>\nimport GiftUpsell from '~/components/GiftUpsell'\n\nexport default {\n components: { GiftUpsell },\n methods: {\n handleAddToCart(upsellLineItem = null) {\n // ...\n }\n }\n}\n```\n\n```html\n<template>\n <btn @click.native=\"upsellAddToCart\">Add to cart with upsell</btn>\n</template>\n\n<script>\nexport default {\n methods: {\n createUpsellLineItem() {\n // whatever\n return some object;\n },\n\n upsellAddToCart() {\n const lineItem = createUpsellLineItem();\n this.$emit('upsell-add-to-cart', lineItem);\n }\n }\n}\n```\n\n```text\nlineItem\n```\n\n```text\nhandleAddToCart\n```\n\n```text\nhandleAddToCart\n```\n\n```text\n$event\n```\n\n```text\nhandleAddToCart\n```\n\n```text\nupsell-add-to-cart\n```\n\n```html\n<btn @click.native=\"handleAddToCart\">Add to Cart</btn>\n<gift-upsell @upsellAddToCart=\"handleAddToCart\" />\n```\n\n```html\n<btn @click.native=\"handleAddToCart($event)\">Add to Cart</btn>\n<gift-upsell @upsellAddToCart=\"handleAddToCart($event)\" />\n```\n\n```html\n<btn @click.native=\"handleAddToCart()\">Add to Cart</btn>\n<gift-upsell @upsellAddToCart=\"handleAddToCart\" />\n```\n\n```html\n<btn @click.native=\"handleAddToCart()\">Add to Cart</btn>\n<gift-upsell @upsellAddToCart=\"handleAddToCart($event)\" />\n```\n\n```text\nv-on\n```\n\n```text\n@click\n```\n\n```text\nlineItem\n```\n\n```text\nhandleAddToCart\n```\n\n```text\n<btn @click>\n```\n\n```text\nclick\n```\n\n```text\nMouseEvent\n```\n\n```text\nhandleAddToCart\n```\n\n```text\n<btn>\n```\n\n```text\nhandleAddToCart\n```\n\n```text\nv-on\n```\n\n========================================\n\nComments:\n- Thanks. I thought that the parameter I passed in $emit would/should be something different than (additional to) the $event object passed to a handler, and wondered why the $event was missing in the first place when passing this parameter..\n- Indeed, @trollkotze, one might think it works similar to the filters and `value` parameter. Related: v2.vuejs.org/v2/guide/filters.html\n- \"The v-on directive automatically passes the event data to the specified method when only a method name is given\" - The documentation says otherwise, see comment ``// `event` is the native DOM event`. Could be that I read something wrong, but I think your answer and the documentation contradict, and I think you are right.\n- @MarkusWeninger Hmm. I don't understand. How does \"`event` is the native DOM event\" contradict my answer?","metadata":{"transformedAt":"2026-08-18T18:33:07.861Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":195,"estimatedTokens":1082}}364{"id":"stack-63382121","source":"stackoverflow","questionId":63382121,"title":"css changed after nuxt generate","tags":["vue.js","vuetify.js","nuxt.js"],"text":"Title: css changed after nuxt generate\nTags: vue.js, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt with Vuetify.\nI created a class and assigned it some padding.\n\nThe class is defined in a unscoped `` in `layouts/default.vue`.\n\nwhen I'm on development mode (`npm run dev`) everything looks great as I aimed for.\nthe class is on container element so the final html looks like\n\n``\n\nthe devtools look like that when I'm on dev mode:\n\nhttps://i.sstatic.net/aN9z1.png\n\nso `my-class` is applied. But once I build the project (`npm run generate`) `my-class` is overridden by the `container` class rules:\n\nhttps://i.sstatic.net/lH4kr.png\n\nI guess it is happening because of the order in which the classes combined into a single css but not sure it behaves differently for dev and built projects.\nHow can I fix it?\n\n========================================\n\nTop Answer:\nmanaged to fix this by disabling tree shaking for vuetify. Change the following in nuxt.config.js:\n\n```\nbuildModules: [\n [\"@nuxtjs/vuetify\", { treeShake: false }],\n ],\n```\n\n========================================\n\nCode:\n```text\n<style>\n```\n\n```text\nlayouts/default.vue\n```\n\n```text\nnpm run dev\n```\n\n```text\n<div class=\"container container--fluid my-class\">\n```\n\n```text\nmy-class\n```\n\n```text\nnpm run generate\n```\n\n```text\nmy-class\n```\n\n```text\ncontainer\n```\n\n```text\nimport Vue from \"vue\"\nimport Vuetify from \"vuetify\"\nversion \"^2.1.1\" ,\nVue.use(Vuetify)\n\nexport default (ctx) => {\n const vuetify = new Vuetify({\n theme: {\n dark: false, // From 2.0 You have to select the theme dark or light here\n },\n })\n\n ctx.app.vuetify = vuetify\n ctx.$vuetify = vuetify.framework\n}\n```\n\n```text\n@nuxt/vuetify\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ncss\n```\n\n```text\nnpm install @mdi/font -D\n```\n\n```js\nbuildModules: [\n [\"@nuxtjs/vuetify\", { treeShake: false }],\n ],\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.861Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":111,"estimatedTokens":465}}365{"id":"stack-57489947","source":"stackoverflow","questionId":57489947,"title":"How to make routes case sensitive in Nuxt","tags":["javascript","vue.js","vue-router","nuxt.js"],"text":"Title: How to make routes case sensitive in Nuxt\nTags: javascript, vue.js, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI use nuxt.js + vue.js. I need to create case sensitivity of routers. I found the following property: caseSensitive. I’m trying to put it into nuxt.config but it doesn’t work, the transition is possible by links in upper case. If I directly change the file ~project/.nuxt/router.js, everything works correctly. Help me to figure it out.\n\n```\nrouter: {\n extendRoutes (routes) {\n for (let key in routes) {\n routes[key]['caseSensitive'] = true\n }\n }\n```\n\n========================================\n\nCode:\n```text\nrouter: {\n extendRoutes (routes) {\n for (let key in routes) {\n routes[key]['caseSensitive'] = true\n }\n }\n```\n\n```text\n// nuxt.config.js\nrouter: {\n extendRoutes(routes) {\n for (const key in routes) {\n routes[key].caseSensitive = true\n }\n }\n}\n```\n\n```text\nrouter.extendRoutes\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ncaseSensitive\n```\n\n========================================\n\nComments:\n- Just a note: your documentation link goes to the French docs.","metadata":{"transformedAt":"2026-08-18T18:33:07.861Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":55,"estimatedTokens":281}}366{"id":"stack-69323946","source":"stackoverflow","questionId":69323946,"title":"Electron-Prisma Error: can not find module '.prisma/client'","tags":["javascript","node.js","electron","nuxt.js","prisma"],"text":"Title: Electron-Prisma Error: can not find module '.prisma/client'\nTags: javascript, node.js, electron, nuxt.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm building a Nuxt-electron-prisma app and I kinda stuck here. when I use prisma normally as guided every thing is fine on dev but on build i get this error :\n\n```\nA javascript error occurred in the main process\nUncaught exception:\nError: can not find module : '.prisma/client'\n```\n\nI tried changing prisma provider output to `../resources/prisma/client`\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../resources/prisma/client\"\n}\n```\n\nand in main.js of electron\n\n```\nconst { PrismaClient } = require('../resources/prisma/client');\nconst prisma = new PrismaClient()\n```\n\nbut I get error `Cannot find module '_http_common' at webpackMissingModules` in both dev and build ! which by others opinion is caused when using prisma on client-side but I only use it on `background.js` (`main.js` of the my boilerplate)\n\nI'm using Nuxtron boilerplate for Nuxt-electron which is using yml file for electron-builder config file and in it I also added prisma to files property:\n\n```\nappId: com.example.app\nproductName: nuxt-electron-prisma\ncopyright: Copyright © 2021\nnsis: \n oneClick: false\n perMachine: true\n allowToChangeInstallationDirectory: true\n\ndirectories:\n output: dist\n buildResources: resources\nfiles:\n - \"resources/prisma/database.db\"\n - \"node_modules/.prisma/**\"\n - \"node_modules/@prisma/client/**\"\n - from: .\n filter:\n - package.json\n - app\npublish: null\n```\n\nand still get errors\n\nin my `win-unpacked/resources` I have this only: `win-unpacked\\resources\\app.asar.unpacked\\node_modules\\@prisma\\engines`\n\nhttps://i.sstatic.net/wMyij.png\n\nand of course my package.json\n\n```\n{\n \"private\": true,\n \"name\": \"nuxt-electron-prisma\",\n \"productName\": \"nuxt-electron-prisma\",\n \"description\": \"\",\n \"version\": \"1.0.0\",\n \"author\": \"\",\n \"main\": \"app/background.js\",\n \"scripts\": {\n \"dev\": \"nuxtron\",\n \"build\": \"nuxtron build\"\n },\n \"dependencies\": {\n \"electron-serve\": \"^1.0.0\",\n \"electron-store\": \"^6.0.1\",\n \"@prisma/client\": \"^3.0.2\"\n },\n \"devDependencies\": {\n \"@mdi/font\": \"^6.1.95\",\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/device\": \"^2.1.0\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"@nuxtjs/vuetify\": \"1.12.1\",\n \"core-js\": \"^3.15.1\",\n \"electron\": \"^10.1.5\",\n \"electron-builder\": \"^22.9.1\",\n \"glob\": \"^7.1.7\",\n \"noty\": \"^3.2.0-beta\",\n \"nuxt\": \"^2.15.7\",\n \"nuxtron\": \"^0.3.1\",\n \"sass\": \"1.32.13\",\n \"swiper\": \"^5.4.5\",\n \"prisma\": \"^3.0.2\",\n \"vue-awesome-swiper\": \"^4.1.1\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nOk, I finally solved it!!\nfirst of all no need to change client generator output direction!\n\n```\n//schema.prisma\ndatasource db {\n provider = \"sqlite\"\n url = \"file:../resources/database.db\"\n}\ngenerator client {\n provider = \"prisma-client-js\"\n // output = \"../resources/prisma/client\" !! no need for this!\n}\n```\n\nthen in electron-builder config add `./prisma` , `@prisma` and database\n\n```\n// my config file was a .yml\nextraResources:\n - \"resources/database.db\"\n - \"node_modules/.prisma/**/*\"\n - \"node_modules/@prisma/client/**/*\"\n\n// or in js\nextraResources:[\n \"resources/database.db\"\n \"node_modules/.prisma/**/*\"\n \"node_modules/@prisma/client/**/*\"\n]\n```\n\nthis solved `Error: cannot find module : '.prisma/client'\n\nbut this alone won't read DB in built exe file!\n\nso in main.js where importing `@prisma/client` should change DB reading directory:\n\n```\nimport { join } from 'path';\nconst isProd = process.env.NODE_ENV === 'production';\n\nimport { PrismaClient } from '@prisma/client';\nconst prisma = new PrismaClient({\n datasources: {\n db: {\n url: `file:${isProd ? join(process.resourcesPath, 'resources/database.db') : join(__dirname, '../resources/database.db')}`,\n },\n },\n})\n```\n\nwith these configs I could fetch data from my sqlite DB\n\n========================================\n\nCode:\n```text\nA javascript error occurred in the main process\nUncaught exception:\nError: can not find module : '.prisma/client'\n```\n\n```js\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../resources/prisma/client\"\n}\n```\n\n```js\nconst { PrismaClient } = require('../resources/prisma/client');\nconst prisma = new PrismaClient()\n```\n\n```yaml\nappId: com.example.app\nproductName: nuxt-electron-prisma\ncopyright: Copyright © 2021\nnsis: \n oneClick: false\n perMachine: true\n allowToChangeInstallationDirectory: true\n\ndirectories:\n output: dist\n buildResources: resources\nfiles:\n - \"resources/prisma/database.db\"\n - \"node_modules/.prisma/**\"\n - \"node_modules/@prisma/client/**\"\n - from: .\n filter:\n - package.json\n - app\npublish: null\n```\n\n```json\n{\n \"private\": true,\n \"name\": \"nuxt-electron-prisma\",\n \"productName\": \"nuxt-electron-prisma\",\n \"description\": \"\",\n \"version\": \"1.0.0\",\n \"author\": \"\",\n \"main\": \"app/background.js\",\n \"scripts\": {\n \"dev\": \"nuxtron\",\n \"build\": \"nuxtron build\"\n },\n \"dependencies\": {\n \"electron-serve\": \"^1.0.0\",\n \"electron-store\": \"^6.0.1\",\n \"@prisma/client\": \"^3.0.2\"\n },\n \"devDependencies\": {\n \"@mdi/font\": \"^6.1.95\",\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/device\": \"^2.1.0\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"@nuxtjs/vuetify\": \"1.12.1\",\n \"core-js\": \"^3.15.1\",\n \"electron\": \"^10.1.5\",\n \"electron-builder\": \"^22.9.1\",\n \"glob\": \"^7.1.7\",\n \"noty\": \"^3.2.0-beta\",\n \"nuxt\": \"^2.15.7\",\n \"nuxtron\": \"^0.3.1\",\n \"sass\": \"1.32.13\",\n \"swiper\": \"^5.4.5\",\n \"prisma\": \"^3.0.2\",\n \"vue-awesome-swiper\": \"^4.1.1\"\n }\n}\n```\n\n```text\n../resources/prisma/client\n```\n\n```text\nCannot find module '_http_common' at webpackMissingModules\n```\n\n```text\nbackground.js\n```\n\n```text\nmain.js\n```\n\n```text\nwin-unpacked/resources\n```\n\n```text\nwin-unpacked\\resources\\app.asar.unpacked\\node_modules\\@prisma\\engines\n```\n\n```json\n{\n \"build\": {\n \"extraResources\": [\n {\n \"from\": \"node_modules/.prisma/client/\",\n \"to\": \"app/node_modules/.prisma/client/\"\n }\n ],\n }\n}\n```\n\n```json\n{\n \"build\": {\n \"files\": [\n {\n \"from\": \"node_modules/.prisma/client/\",\n \"to\": \"node_modules/.prisma/client/\"\n }\n ],\n }\n}\n```\n\n```text\n@prisma\n```\n\n```text\nresources/app/node_modules\n```\n\n```text\nresources/node_modules\n```\n\n```text\nresources/app/node_modules\n```\n\n```text\n@prisma\n```\n\n```text\nfiles\n```\n\n```text\n//schema.prisma\ndatasource db {\n provider = \"sqlite\"\n url = \"file:../resources/database.db\"\n}\ngenerator client {\n provider = \"prisma-client-js\"\n // output = \"../resources/prisma/client\" !! no need for this!\n}\n```\n\n```js\n// my config file was a .yml\nextraResources:\n - \"resources/database.db\"\n - \"node_modules/.prisma/**/*\"\n - \"node_modules/@prisma/client/**/*\"\n\n// or in js\nextraResources:[\n \"resources/database.db\"\n \"node_modules/.prisma/**/*\"\n \"node_modules/@prisma/client/**/*\"\n]\n```\n\n```js\nimport { join } from 'path';\nconst isProd = process.env.NODE_ENV === 'production';\n\nimport { PrismaClient } from '@prisma/client';\nconst prisma = new PrismaClient({\n datasources: {\n db: {\n url: `file:${isProd ? join(process.resourcesPath, 'resources/database.db') : join(__dirname, '../resources/database.db')}`,\n },\n },\n})\n```\n\n```text\n./prisma\n```\n\n```text\n@prisma\n```\n\n```text\n@prisma/client\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.861Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":369,"estimatedTokens":1809}}367{"id":"stack-70833580","source":"stackoverflow","questionId":70833580,"title":"Scrolling a page in vue-router only after loading the components","tags":["vue.js","nuxt.js","vue-router"],"text":"Title: Scrolling a page in vue-router only after loading the components\nTags: vue.js, nuxt.js, vue-router\nSource: Stack Overflow\n\nQuestion:\nAccording vue-router documentation (https://router.vuejs.org/guide/advanced/scroll-behavior.html#async-scrolling) you can do \"async scrolling\". I have a single page app where the height of the page varies page by page. When navigating back, I would like to scroll the page to the same position where the user clicked the link.\n\nNow, immediately when navigating back the component for the page has not been loaded fully and the overall height of the page is not long enough. The scroll to `savedPosition` will only go to the bottom of the page before the component loads.\n\nI can do this in nuxt.config.js\n\n```\nrouter: {\n scrollBehavior (to, from, savedPosition) {\n if (savedPosition)\n {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve(savedPosition)\n }, 300)\n })\n }\n```\n\nThat will wait 300ms, around the time the page height is resolved, and only then scroll down. But this is not optimal. What if the loading of the component takes longer?\n\nHow would you implement vue-router scrolling only after the component on the page has loaded?\n\nCan I listen to events in the page in the vue-router `scrollBehavior`? Could I somehow wait for the Vue lifecycle hooks to trigger the scroll? Can I get a trigger about the page height changing?\n\n========================================\n\nTop Answer:\nApp.vue\n\n```\nwatch: {\n $route () {\n setTimeout(() => {\n window.scrollTo(0, 0)\n }, 0)\n }\n}\n```\n\n========================================\n\nCode:\n```text\nrouter: {\n scrollBehavior (to, from, savedPosition) {\n if (savedPosition)\n {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve(savedPosition)\n }, 300)\n })\n }\n```\n\n```text\nsavedPosition\n```\n\n```text\nscrollBehavior\n```\n\n```text\n// create an Observer instance to listen to height changes on an object\nconst resizeObserver = new ResizeObserver(entries => {\n // Check if the height is enough to scroll to that point\n if(entries[0].target.clientHeight >= savedPosition.top + screen.height) {\n // Then resolve to trigger the scroll and disconnect the observer\n resolve(savedPosition);\n resizeObserver.disconnect();\n }\n});\n// start observing a DOM node\nresizeObserver.observe(document.body);\n```\n\n```text\nscrollBehavior(to, from, savedPosition) {\n return new Promise((resolve, reject) => {\n if(savedPosition) {\n // create an Observer instance\n const resizeObserver = new ResizeObserver(entries => {\n if(entries[0].target.clientHeight >= savedPosition.top + screen.height) {\n resolve(savedPosition);\n resizeObserver.disconnect();\n }\n });\n \n // start observing a DOM node\n resizeObserver.observe(document.body);\n } else {\n resolve({ top: 0 });\n }\n });\n}\n```\n\n```text\nwatch: {\n $route () {\n setTimeout(() => {\n window.scrollTo(0, 0)\n }, 0)\n }\n}\n```\n\n========================================\n\nComments:\n- Hi, thanks for the suggestion and welcome to SO. Are you sure you are answering the question? There is, for example, no savedPosition in your answer and that is neede to scroll to the previous position.","metadata":{"transformedAt":"2026-08-18T18:33:07.861Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":118,"estimatedTokens":851}}368{"id":"stack-58319334","source":"stackoverflow","questionId":58319334,"title":"Nuxt environment variables exposed in client when uploaded to Zeit/Now","tags":["environment-variables","nuxt.js","dotenv","vercel"],"text":"Title: Nuxt environment variables exposed in client when uploaded to Zeit/Now\nTags: environment-variables, nuxt.js, dotenv, vercel\nSource: Stack Overflow\n\nQuestion:\nI am deploying a Nuxt App with Zeit/Now. In the development phase I was using a `.env` file to store the secrets to my Contentful CMS, exposing the secrets to `process.env` with the nuxt-dotenv package. To do that, at the top of the nuxt.config I was calling `require('dotenv').config()`.\n\nI then stored the secrets with Zeit/Now and created a now.json to set them up for build and runtime like so:\n\n```\n{\n \"env\": {\n \"DEMO_ID\": \"@demo_id\"\n },\n \"build\": {\n \"env\": {\n \"DEMO_ID\": \"@demo_id\"\n }\n }\n}\n```\n\nWith that setup, the build was only working for the index page and all of the Javascript did not function. Only when I added the env-property to the `nuxt.config.js`file, the app started working properly on the Zeit-server. \n\n```\nrequire('dotenv').config()\n\nexport default {\n...\nenv: {\n DEMO_ID: process.env.DEMO_ID\n },\n...\n modules: [\n '@nuxtjs/dotenv'\n ],\n...\n}\n```\n\nBUT: When I then checked the uploaded Javascript files, my secrets were exposed, which I obviously don't want. \n\nWhat am I doing wrong here? Thanks for your help.\n\n========================================\n\nTop Answer:\nWe had a similar problem in our project. Even, We created a nuxt project from scratch and checked to see if there was a situation we skipped. We noticed that, while nuxt building, it copies the .env variables into the utils.js in the nuxt folder. Through the document here, we changed the modules section in nuxt.config.js as follows,\n\n```\nmodules: ['@ nuxtjs / apollo', '@ nuxtjs / axios', ['@ nuxtjs / dotenv', { only: ['']}]],\n```\n\nThen we noticed that .env variables are not exposed.\n\nI hope it helped.\n\nOur nuxt version is \"nuxt\": \"^ 2.13.0\".\n\nAlso, some discussion over here.\n\n========================================\n\nCode:\n```text\n{\n \"env\": {\n \"DEMO_ID\": \"@demo_id\"\n },\n \"build\": {\n \"env\": {\n \"DEMO_ID\": \"@demo_id\"\n }\n }\n}\n```\n\n```text\nrequire('dotenv').config()\n\nexport default {\n...\nenv: {\n DEMO_ID: process.env.DEMO_ID\n },\n...\n modules: [\n '@nuxtjs/dotenv'\n ],\n...\n}\n```\n\n```text\n.env\n```\n\n```text\nprocess.env\n```\n\n```text\nrequire('dotenv').config()\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nenv\n```\n\n```text\nprocess.env.MY_ENV\n```\n\n```text\nserverMiddleware\n```\n\n```text\nmodules: ['@ nuxtjs / apollo', '@ nuxtjs / axios', ['@ nuxtjs / dotenv', { only: ['']}]],\n```\n\n========================================\n\nComments:\n- Same problem happens to us. One of the our app secrets was exposed. Did you solve the problem?","metadata":{"transformedAt":"2026-08-18T18:33:07.861Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":129,"estimatedTokens":657}}369{"id":"stack-68400108","source":"stackoverflow","questionId":68400108,"title":"Flickering content when trying to show non-authenticated and authenticated content on the same page","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: Flickering content when trying to show non-authenticated and authenticated content on the same page\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\n(Nuxt project)\nI am stuck finding a solution related to show non-authenticated and authenticated content on the same page.\n\nI have two possible solutions in my mind but they have some caveats.\n\nThe first one, decides on the `mounted` method if the user can see the authenticated content but I couldn't solve the flickering content issue, this is the demo for that approach:\nhttps://60f08a8293123d00e57c14e8--happy-minsky-1268c6.netlify.app/\nClick the login button and reload the page, you will see the flickering content\n\nMy second approach, it is using the `null` to avoid both, the non-authenticated and authenticated content until the app reaches the `mounted` method, the problem with this solution is it is not search engine friendly because there is no static content generation, please compare this two links:\n\n**Generated from this solution:** https://gist.github.com/ltroya-as/fbbdce2b3dc30063e9c4ec7e93e3aba1#file-index-generated-file-html-L522\n\n**Expected:** https://gist.github.com/ltroya-as/d37e3d0a89efebbfd66c2daf7700f50d#file-expected-generated-file-html-L523\n\nIs there a way to make the second solution more search engine friendly? I am worried that the second solution affects search engine results.\n\nRepository with instructions:\nhttps://github.com/ltroya-as/nuxt-rehydratation-example\n\n--- Update\n\nMy project is configured in full static mode\n\n========================================\n\nTop Answer:\nYou should use beforeEach (navigation guards) - this one should do the trick. You can use it to check if the user is logged in or not there, https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards\n\nsomething like this:\n\n```\nconst router = new VueRouter({\n routes: [\n {\n path: '/foo',\n component: Foo,\n beforeEnter: (to, from, next) => {\n // ...\n }\n }\n ]\n})\n```\n\nI think that this answer it will help you Pass data with beforeEnter to route components\n\n========================================\n\nCode:\n```text\nmounted\n```\n\n```text\nnull\n```\n\n```text\nmounted\n```\n\n```text\nnull\n```\n\n```text\nconst router = new VueRouter({\n routes: [\n {\n path: '/foo',\n component: Foo,\n beforeEnter: (to, from, next) => {\n // ...\n }\n }\n ]\n})\n```\n\n========================================\n\nComments:\n- What are you trying to SEO here? `No authenticated content`? If you want a smoother effect, maybe try to look for a transition or any other CSS solution: vuejs.org/v2/guide/… Even tho, you can totally define what should be sent ahead of time and generate it on the server (`target: server`) directly. Because rehydration will by default cause a \"flicker\" indeed.\n- Can you please answer to my previous comment please?\n- The equivalent of that on nuxt is middleware, isn't it?\n- I tried to use middleware but it doesn't work. You can see the last commit here github.com/ltroya-as/nuxt-rehydratation-example/tree/…\n- A middleware and router guard is not exactly the thing @LTroya.\n- In nuxt context, what will be the equivalent for that? @kissu\n- For `beforeEnter`? There is not equivalent needed since you can use it as a component guard: router.vuejs.org/guide/advanced/… Middleware is specific to Nuxt, and works well too @LTroya\n- Can you create an example using Nuxt? You can use my example as a base, please @kissu\n- @LTroya I'm still not sure what you're expecting since you did not answered my comments under your question.\n- I am not sure how to use `beforeEnter` on Nuxt since all the routes are dynamically generated @kissu\n- Not sure if OP is still answering, hence we cannot help him without further details. :(\n- A real case scenario in the company is that they have `Megafactories` page, on that page they show `Megafactories` related information such as what they are, importance, how the company is related to this, and so on (marketing things)\n- Looking more in-depth about the problem and possible solutions, I found this article developers.google.com/search/blog/2015/10/…. What do you guys think about it?\n- @LTroya Read this. Google isn't the only search engine. Plus indexing of JS heavy page (which Vue SPA is) means Google needs much more computation resources to do that. I remember video from some conference where the lector explained that this can cause long periods of time your site is not indexed or only partially indexed....\n- Also this is very good resource on SEO of JS heavy sites...\n- Thanks for all the articles! The company only cares for chrome at the moment and we use nuxt to increase the performance of the app. I think we are good for the moment, I will look for more info and ways to improve that.","metadata":{"transformedAt":"2026-08-18T18:33:07.861Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":104,"estimatedTokens":1200}}370{"id":"stack-56658173","source":"stackoverflow","questionId":56658173,"title":"how to break loop in webpack hook","tags":["javascript","node.js","vue.js","webpack","nuxt.js"],"text":"Title: how to break loop in webpack hook\nTags: javascript, node.js, vue.js, webpack, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm working with a project nuxt.js, I need to run a shell script on every changed file, that is, every webpack build.\n\nso I'm using the Webpack Hooks\n\nI created my Webpack Plugin\n\n`/plugins/NamedExports.js`\n\n```\nconst pluginName = 'NamedExports'\nconst { exec } = require('child_process')\n\nclass NamedExports {\n apply(compiler) {\n compiler.hooks.beforeCompile.tap(pluginName, (params, callback) => {\n exec('sh plugins/shell.sh', (err, stdout, stderr) => {\n console.log(stdout)\n console.log(stderr)\n })\n })\n }\n}\n\nexport default NamedExports\n```\n\n`plugins/shell.js`\n\n```\nparameters=$(ls components)\nfor item in ${parameters[*]}\ndo\n ls components/$item/ | grep -v index.js | sed 's#^\\([^.]*\\).*$#export { default as \\1 } from \"./&\"#' > components/$item/index.js\ndone\n\necho \"worked\"\n```\n\nthis script is to make named exports within each folder in the component directory, example\n\n`components/atoms/ButtonStyled.vue`\n`components/atoms/BoxStyled.vue`\n\nthen it is generated `components/atoms/index.js`\n\n```\nexport { default as ButtonStyled } from \"./ButtonStyled.vue\"\nexport { default as BoxStyled } from \"./BoxStyled.vue\"\n```\n\nI registered my Plugin in `nuxt.config.nuxt` or `webpack.config.js`\n\n```\nimport NamedExports from './plugins/NamedExports.js'\n\nexport default {\n // ... other config here ...\n build: {\n plugins: [\n // ... other plugins here ...\n new NamedExports()\n ],\n }\n}\n```\n\nbut when I run my app and change any file, the server says that a change has been made to `components/atoms/index.js` and then a new build is done, so it gets infinite build.\n\nCan someone help me break this loop?\n\nfor when to change a file, simply generate new index.js and not generate infinite builds\n\nthanks in advance\n\n========================================\n\nTop Answer:\nThe problem is obviously new files retriggering a build. Conceptually, there are a few ways of going about this.\n\n1) if the files are updated, don't output new files. You need to compare timestamps for this. It's probably going to be messy.\n\n2) write a loader. Match `components/**/index.js`, output the correct javascript for it. Ensure **stateless**. I.e. Don't output another file, just a string. \n\nThen put dummy files in each directory with a comment that it's auto-generated by a webpack plugin. \n\nEven better if your dummy file tells webpack how to generate it. \n\nhttps://webpack.js.org/contribute/writing-a-loader/\n\n========================================\n\nCode:\n```text\nconst pluginName = 'NamedExports'\nconst { exec } = require('child_process')\n\nclass NamedExports {\n apply(compiler) {\n compiler.hooks.beforeCompile.tap(pluginName, (params, callback) => {\n exec('sh plugins/shell.sh', (err, stdout, stderr) => {\n console.log(stdout)\n console.log(stderr)\n })\n })\n }\n}\n\nexport default NamedExports\n```\n\n```text\nparameters=$(ls components)\nfor item in ${parameters[*]}\ndo\n ls components/$item/ | grep -v index.js | sed 's#^\\([^.]*\\).*$#export { default as \\1 } from \"./&\"#' > components/$item/index.js\ndone\n\necho \"worked\"\n```\n\n```text\nexport { default as ButtonStyled } from \"./ButtonStyled.vue\"\nexport { default as BoxStyled } from \"./BoxStyled.vue\"\n```\n\n```text\nimport NamedExports from './plugins/NamedExports.js'\n\nexport default {\n // ... other config here ...\n build: {\n plugins: [\n // ... other plugins here ...\n new NamedExports()\n ],\n }\n}\n```\n\n```text\n/plugins/NamedExports.js\n```\n\n```text\nplugins/shell.js\n```\n\n```text\ncomponents/atoms/ButtonStyled.vue\n```\n\n```text\ncomponents/atoms/BoxStyled.vue\n```\n\n```text\ncomponents/atoms/index.js\n```\n\n```text\nnuxt.config.nuxt\n```\n\n```text\nwebpack.config.js\n```\n\n```text\ncomponents/atoms/index.js\n```\n\n```text\ncomponents/**/index.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.861Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":179,"estimatedTokens":958}}371{"id":"stack-45494579","source":"stackoverflow","questionId":45494579,"title":"Plugin only server side","tags":["nuxt.js"],"text":"Title: Plugin only server side\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a plugin that I don't want the client to see. Unfortunately it is allways built both for the server and the client. How can this be prevented? \n\n```\n\n \n Test\n \n\n import getAll from '~/plugins/api'\n export default {\n asyncData (context, callback) {\n getAll(function(data){\n callback(null,data);\n })\n }\n }\n\n```\n\nThis is my .vue file. The fetch of the data is working but i can also See the code from the client side which i don't want.\n\n========================================\n\nTop Answer:\nAdding a `.server` suffix to the file should work for nuxt3, for example if your file is `myPlugin.ts` rename it to `myPlugin.server.ts` - this will only be called on the server.\n\n========================================\n\nCode:\n```text\n<template>\n <div>\n Test\n </div>\n</template>\n\n<script>\n import getAll from '~/plugins/api'\n export default {\n asyncData (context, callback) {\n getAll(function(data){\n callback(null,data);\n })\n }\n }\n</script>\n```\n\n```text\n<script>\nimport getAll from '~/plugins/api'\nexport default {\n asyncData (context, callback) {\n if (context.isServer) {\n getAll(function(data){\n callback(null,data);\n })\n }\n }\n}\n</script>\n```\n\n```text\n// nuxt.config.js:\n\nexport default {\n plugins: [\n { src: '~/plugins/both-sides.js' },\n { src: '~/plugins/client-only.js', mode: 'client' },\n { src: '~/plugins/server-only.js', mode: 'server' }\n ]\n}\n```\n\n```text\ncontext.isServer\n```\n\n```text\n.server\n```\n\n```text\nmyPlugin.ts\n```\n\n```text\nmyPlugin.server.ts\n```\n\n========================================\n\nComments:\n- Unfortunately, with this option the plugin is still passed to the client side\n- @Lanayx Do you know a solution which is not passing the code to the client side?\n- @PhilippS. Looks like `mode: 'server'` is the right solution as of today (nuxtjs.org/guide/plugins#client-side-only)\n- @Lanayx Thank you! I have a middleware which should be only available on server side. Any idea how to accomplish this?","metadata":{"transformedAt":"2026-08-18T18:33:07.862Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":103,"estimatedTokens":535}}372{"id":"stack-51815236","source":"stackoverflow","questionId":51815236,"title":"How to generate 100% Static website with Nuxt.js without API request?","tags":["vue.js","nuxt.js"],"text":"Title: How to generate 100% Static website with Nuxt.js without API request?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am testing around with Nuxt.js to generate a static website. \n\nIs it possible to generate a 100% static site when using an API to fetch data, so that one can get rid of the API and requests?\n\nBased on my tests so far that all the files are generated properly and being hosted on the Github Pages and can be reached, except:\n\n- When hitting the pages directly via URL bar, no error (expected behavior)\n\n- When navigating to the pages via routes, the pages **is still sending the request to API** (does not exist outside local machine), even though the data has already been fetched and the `.html` file is generated with the data already during the generate process.\n\nUsing asyncData to get the data for the components from the API.\n\n========================================\n\nTop Answer:\nThere is a trick to make your routes accessible via directly entering the url into the address bar if you are hosting your site in github pages. You just need to configure your webpack to generate multiple `index` files with the same `entry` point that will be stored in each `directory` based on your `routes`.\n\nThis is easily achieved if you are using `vue-cli` to generate your project.\n\nFor example, I have these routes:\n\nhttps://i.sstatic.net/xC4yF.png,\n\nI just need to create a `vue.config.js` in the root of my project.\n\nhttps://i.sstatic.net/kHsMf.png\n\nand inside the `vue.config.js` file, I just need to register several more `pages` based on what's on my `router`.\nEach `entry` point should be your `main.js` file, and the template should be your `index.html`.\n\nThe filename should be `/index.html`\n\nIf you entered sub-directory into the `filename`, Vue will automatically create those directories if they don't exist during compilation. So if the filename you entered is `photography/index.html`, Vue will automatically create a `photography` directory inside the `dist` directory.\n\nhttps://i.sstatic.net/LDx07.png\n\nAnd if you check your `dist` directory, you will see the directories with an `index.html` inside.\n\nhttps://i.sstatic.net/p2XUA.png\n\nSo when you enter your route into the address bar, it will actually access one of these directories and display the `index.html`.\n\nThis is what I actually did to my homepage which I hosted in my github account.\n\n**Here's my github page:** https://wisdomsky.github.io/\n\nI have two pages the `about` and `photography` and if you will enter https://wisdomsky.github.io/photography into the address bar, it will render my photography page instead of receiving the Github 404 page.\n\n========================================\n\nCode:\n```text\n.html\n```\n\n```js\nasync fetch({ store }) {\n if (_.isEmpty(store.getters['tags/getTags'])) {\n await store.dispatch('tags/fetchTags');\n }\n},\n```\n\n```text\n.html\n```\n\n```text\nfetchTags\n```\n\n```text\ntags\n```\n\n```text\nnuxt generate\n```\n\n```text\nindex\n```\n\n```text\nentry\n```\n\n```text\ndirectory\n```\n\n```text\nroutes\n```\n\n```text\nvue-cli\n```\n\n```text\nvue.config.js\n```\n\n```text\nvue.config.js\n```\n\n```text\npages\n```\n\n```text\nrouter\n```\n\n```text\nentry\n```\n\n```text\nmain.js\n```\n\n```text\nindex.html\n```\n\n```text\n<your-route>/index.html\n```\n\n```text\nfilename\n```\n\n```text\nphotography/index.html\n```\n\n```text\nphotography\n```\n\n```text\ndist\n```\n\n```text\ndist\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\nabout\n```\n\n```text\nphotography\n```\n\n========================================\n\nComments:\n- There was a discussion 100%static site possible?#1949 which comes down to: make requests during static generation (nuxt.config.js ... {generate:), save them to a json file, and then import that file either to vuex state or directly into components. I wonder if there is a ready solution for that, so that we don't have to write our own bicycles and miss edge cases, for Angular there is `TransferHttpCacheModule`...\n- before encountered that thread, that's exactly what I did, populate the vuex with the data during the generation process. Thank you for sharing this :)\n- Thank you for the detailed answer, your answer is addressing point 1, which is working as expected :). If you inspect your photography page, you will still see that it is making a request api to unsplash (which might be the behavior you want), but for me the .html file with the data already generated so there is no point in trying to fetch that data from api again.\n- In Nuxt.JS you can determine if your page is served from `client` or from `server`. you can use that to wrap your API calls in a condition so that they won't be called again if your page is served via client. See nuxtjs.org/examples\n- @Julian Paolo Dayag, well, if requests won't be made on a client, then you will end up with empty content on routing, since it won't be requested. You either have to route between simple `.html` files without SPA routing, or cache requests at `nuxt generate` to a file, so that the client can't read data from that ready file and still have SPA routing.\n- my solution was to use vuex and populate the store manager during the generation process\n- Could you at least some example code in the solution ? It's not very clear, do you save a state to a file and then read it, or it is magically works between route changes ?\n- have added the sample code on how I have done it. State will be populated and saved into the .js file (let's call it nuxtjs magic). Then since a generated static website is still a Vue app everything works as expected","metadata":{"transformedAt":"2026-08-18T18:33:07.862Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":183,"estimatedTokens":1382}}373{"id":"stack-71594569","source":"stackoverflow","questionId":71594569,"title":"NuxtJS: QuillJS document is not defined","tags":["vue.js","nuxt.js","quill","vue-quill-editor"],"text":"Title: NuxtJS: QuillJS document is not defined\nTags: vue.js, nuxt.js, quill, vue-quill-editor\nSource: Stack Overflow\n\nQuestion:\nI have a Vue SPA that I'm trying to migrate to Nuxt, and this is my first attempt. I've copied across my components, and have been adding back dependencies to my package.json, however after getting to vue-quill-editor, I've started getting the document is not defined.\n\nError page frames:\n\n```\nReferenceError\ndocument is not defined\n\nnode_modules/quill/dist/quill.js:7661:12\nnode_modules/quill/dist/quill.js:36:30\n__webpack_require__\nnode_modules/quill/dist/quill.js:1030:1\nnode_modules/quill/dist/quill.js:36:30\n__webpack_require__\nnode_modules/quill/dist/quill.js:5655:14\nnode_modules/quill/dist/quill.js:36:30\n__webpack_require__\nnode_modules/quill/dist/quill.js:10045:13\nnode_modules/quill/dist/quill.js:36:30\n__webpack_require__\n```\n\nI've tried wrapping the 2 components that use the quill editor in\n\n```\n\n```\n\ntags, but that hasn't changed anything at all. Here is one of the components:\n\n```\n\n \n \n \n \n Notes\n \n \n \n \n \n \n \n\n```\n\n```\nimport { quillEditor } from \"vue-quill-editor\";\n```\n\nI've looked at a number of SO threads but none have worked. If any more info is needed just say :)\n\nI appreciate any help\n\n========================================\n\nTop Answer:\nin nuxt 3 you have to install plugin globally.\nExample:in directory plugins create js/ts file:\n\n\r\n\r\n\n```\nimport { defineNuxtPlugin } from '#app';\nimport { QuillEditor } from '@vueup/vue-quill';\nimport '@vueup/vue-quill/dist/vue-quill.snow.css';\n\nexport default defineNuxtPlugin((nuxtapp) => {\n nuxtapp.vueApp.component('QuillEditor', QuillEditor)\n})\n```\n\n\r\n\r\n\r\n\nthen declare it in nuxt.config.ts\n\n\r\n\r\n\n```\nplugins: ['~/plugins/quill.ts']\n```\n\n========================================\n\nCode:\n```text\nReferenceError\ndocument is not defined\n\nnode_modules/quill/dist/quill.js:7661:12\nnode_modules/quill/dist/quill.js:36:30\n__webpack_require__\nnode_modules/quill/dist/quill.js:1030:1\nnode_modules/quill/dist/quill.js:36:30\n__webpack_require__\nnode_modules/quill/dist/quill.js:5655:14\nnode_modules/quill/dist/quill.js:36:30\n__webpack_require__\nnode_modules/quill/dist/quill.js:10045:13\nnode_modules/quill/dist/quill.js:36:30\n__webpack_require__\n```\n\n```html\n<client-only>\n```\n\n```html\n<template>\n <client-only>\n <div>\n <b-card no-body class=\"mt-4\">\n <b-card-header>\n Notes\n </b-card-header>\n <b-card-body>\n <quill-editor v-model=\"contents\" :content=\"contents\"></quill-editor>\n </b-card-body>\n </b-card>\n </div>\n </client-only>\n</template>\n\n<script>\n```\n\n```js\nimport { quillEditor } from \"vue-quill-editor\";\n```\n\n```text\n<template>\n <ClientOnly fallback-tag=\"div\" fallback=\"Loading editor...\">\n <QuillEditor theme=\"snow\" />\n </ClientOnly>\n </template>\n\n<script setup lang=\"ts\">\nimport { QuillEditor } from '@vueup/vue-quill'\nimport '@vueup/vue-quill/dist/vue-quill.snow.css'\n</script>\n```\n\n```js\nimport { defineNuxtPlugin } from '#app';\nimport { QuillEditor } from '@vueup/vue-quill';\nimport '@vueup/vue-quill/dist/vue-quill.snow.css';\n\nexport default defineNuxtPlugin((nuxtapp) => {\n nuxtapp.vueApp.component('QuillEditor', QuillEditor)\n})\n```\n\n```js\nplugins: ['~/plugins/quill.ts']\n```\n\n```text\nimport { defineNuxtPlugin } from '#app';\nimport { QuillEditor } from '@vueup/vue-quill';\nimport '@vueup/vue-quill/dist/vue-quill.snow.css';\n\nexport default defineNuxtPlugin((nuxtapp) => {\n nuxtapp.vueApp.component('QuillEditor', QuillEditor)\n})\n```\n\n```text\n/plugins/quillEditor.client.ts\n```\n\n```text\nclient\n```\n\n========================================\n\nComments:\n- Does this answer your question? How to fix navigator / window / document is undefined in Nuxt\n- I've had a look at that one too, sadly not helpful :(\n- I'm 90% positive that this will solve your issue. Check the last part. Do you have a minimal reproducible example?\n- Apologies for the late response, I did manage to get it fixed just 20 mins ago. I had to import globally and set client only, as importing into the component is going to SSR\n- You will impact your whole website if you import it globally. Did you tried my 3rd solution yet? I mean, you do you if you want to have a package loaded on every page even if you never use it (it will delay the whole initial loading even more).\n- My apologies I didn't see the bottom part first time around. I've got stuff rendering now, just need to get certain plugins such as sidebar menu and perfect scrollbar actually working now. Thank you\n- You don't **HAVE** to install it globally no.\n- also not necessary to register a plugin in nuxt 3, its auto imported\n- My team have implemented Quill in Nuxt 3. I'll take a look and let you know if we did anything differently, but using ClientOnly is typically the only way to render things like this; all very dom dependent","metadata":{"transformedAt":"2026-08-18T18:33:07.862Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":197,"estimatedTokens":1221}}374{"id":"stack-62223392","source":"stackoverflow","questionId":62223392,"title":"Nuxt.js with Typeform causes me to force reload page","tags":["javascript","vue.js","nuxt.js","typeform"],"text":"Title: Nuxt.js with Typeform causes me to force reload page\nTags: javascript, vue.js, nuxt.js, typeform\nSource: Stack Overflow\n\nQuestion:\nI am making my own personal webdesign website but I can't wrap my head around this problem. \n\nHow it happens:\nWhen I **navigate** from any page to my contact-page (where the Typeform is), the Typeform is simply not showing. When I **reload** the contact-page itself, it works as it is expected. \n\nI am loading the Typeform script this way:\n*contact.vue*\n\n```\nhead () {\n return {\n script: [\n { src: 'https://embed.typeform.com/embed.js' }\n ]\n }\n }\n```\n\nand I am embedding it in the template this way:\n\n```\n\n \n```\n\nI am following all the steps they provided, but it doesn't seem to work...\nI am also getting the following errors in my console but I don't think they are relevant because the form works when I reload the contact-page:\n\n```\n[Report Only] Refused to frame 'https://aaron479753.typeform.com/' because an ancestor violates the following Content Security Policy directive: \"frame-ancestors https:\".\n\nGET https://cdn.segment.com/analytics.js/v1/9at6spGDYXelHDdz4r0cP73b3wV1f0ri/analytics.min.js net::ERR_BLOCKED_BY_CLIENT\n```\n\nnote: I am developing on localhost so that's why HTTPS is not enabled.\n\nThanks in advance!\nAaron\n\nEdit:\nthe form when I reload the page\n\nthe form when I go to (for example) /home and then back to /contanct\n\n========================================\n\nCode:\n```text\nhead () {\n return {\n script: [\n { src: 'https://embed.typeform.com/embed.js' }\n ]\n }\n }\n```\n\n```text\n<div class=\"typeform-widget\" data-url=\"https://url-to-my-form\" \n data-transparency=\"50\" data-hide-headers=true data-hide-footer=true\n style=\"width: 100%; height: 500px;\"></div>\n <div style=\"font-size: 12px;color: #999;opacity: 0.5; padding-top: 5px;\"></div>\n```\n\n```text\n[Report Only] Refused to frame 'https://aaron479753.typeform.com/' because an ancestor violates the following Content Security Policy directive: \"frame-ancestors https:\".\n\n\nGET https://cdn.segment.com/analytics.js/v1/9at6spGDYXelHDdz4r0cP73b3wV1f0ri/analytics.min.js net::ERR_BLOCKED_BY_CLIENT\n```\n\n========================================\n\nComments:\n- I also still have this issue. would love to resolve this console error for my site soheco.org","metadata":{"transformedAt":"2026-08-18T18:33:07.862Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":80,"estimatedTokens":591}}375{"id":"stack-72146078","source":"stackoverflow","questionId":72146078,"title":"Using Firebase Functions with Nuxt 3","tags":["firebase","google-cloud-functions","nuxt.js"],"text":"Title: Using Firebase Functions with Nuxt 3\nTags: firebase, google-cloud-functions, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nEnvironment\n\n- Operating System: macOS 10.15.7\n\n- Node Version:v16.14.2\n\n- Nuxt Version: 3.0.0-rc.2\n\n- Firebase: 9.7.0\n\n- firebase-admin: 10.2.0\n\n- firebase-functions: 3.21.0\n\n- firebase-functions-test: 0.3.3\n\nIn firebase.json the following config is set:\n\n```\n{\n\"functions\": { \"source\": \".output/server\" }\n}\n```\n\nI have a file under the \"server\" directory containing the following function:\n\n```\nimport * as functions from \"firebase-functions\";\n\nexport const helloWorld = functions.https.onRequest((request, response) => {\n functions.logger.info(\"Hello logs!\", {structuredData: true});\n response.send(\"Hello from Firebase!\");\n});\n```\n\nWhen I run:\n\n```\nNITRO_PRESET=firebase npm run build\nfirebase emulators:start --only functions\n```\n\nthen go to my firebase emulator log, it does not show the new `helloWorld()` function being initialized. Also, when going to \"http://localhost:5001/$PROJECTNAME/us-central1/helloWorld\", it returns \"Function us-central1-helloWorld does not exist, valid functions are: us-central1-server\" which suggests that my function has not been initialized.\n\nIs there any way I can write firebase cloud functions in my Nuxt 3 app from files in my server directory?\n\nI saw a similar discussion here that said it was possible to change the nuxt.config.ts `functions` object between deploying functions,storage,firestore and deploying server and hosting. I am trying to write firebase functions solely in the \"server\" directory without creating a \"functions\" directory and the root of my project. Is this possible?\n\nI have also opened a discussion on GitHub here\n\n========================================\n\nCode:\n```text\n{\n\"functions\": { \"source\": \".output/server\" }\n}\n```\n\n```text\nimport * as functions from \"firebase-functions\";\n\nexport const helloWorld = functions.https.onRequest((request, response) => {\n functions.logger.info(\"Hello logs!\", {structuredData: true});\n response.send(\"Hello from Firebase!\");\n});\n```\n\n```text\nNITRO_PRESET=firebase npm run build\nfirebase emulators:start --only functions\n```\n\n```text\nhelloWorld()\n```\n\n```text\nfunctions\n```\n\n```text\nimport { initializeApp } from \"firebase/app\";\n import { getFirestore } from \"firebase/firestore\";\n import { getFunctions } from \"firebase/functions\";\n \n const firebaseConfig = {\n apiKey: \"...\",\n // ....\n };\n \n const firebaseApp = initializeApp(firebaseConfig);\n const db = getFirestore(firebaseApp);\n const functions = getFunctions(firebaseApp);\n \n export { db, functions };\n```\n\n```text\n<script> \n import { functions } from '../firebaseConfig';\n import { httpsCallable } from 'firebase/functions';\n \n // ...\n methods: {\n async callFunction() {\n const addMessage = httpsCallable(functions, 'addMessage');\n const result = await addMessage({ text: messageText })\n const data = result.data;\n //...\n });\n \n }\n \n </script>\n```\n\n```text\n{\n \"firestore\": {\n \"rules\": \"firestore.rules\",\n \"indexes\": \"firestore.indexes.json\"\n },\n \"functions\": {\n \"predeploy\": [\n \"npm --prefix \\\"$RESOURCE_DIR\\\" run lint\"\n ],\n \"source\": \".output/server\" \n },\n \"hosting\": {\n \"site\": \"<your_project_id>\",\n \"public\": \".output/public\",\n \"cleanUrls\": true,\n \"rewrites\": [{ \"source\": \"**\", \"function\": \"server\" }],\n \"ignore\": [\n \"firebase.json\",\n \"**/.*\",\n \"**/node_modules/**\"\n ]\n }\n}\n```\n\n```text\nfirebase.json\n```\n\n========================================\n\nComments:\n- He wants to use nuxt3 as external server. He wants to use libraries like firebase-functions SDK and firebase-admin SDK. Those libraries work in node environment.\n- Yes, all that is correct, and the answer talks about it too. Can you please elaborate? My answer is explaining how to deploy Cloud Functions using Nuxt 3 as front end and I was also able to apply the app through Nitro server\n- There's nothing to elaborate. Example you wrote works only as open API for everyone if we speak about video. He wants to be able to authenticate users and do things in database. He needs to use firebase-functions and firebase-admin SDK.\n- Yes, and that is possible. He just needs to my answer.\n- Ok so show us how he can authenticate external HTTPs calls.\n- I don't think this is the main question of the user, but if you have something else to add you can post it as a comment or an answer.","metadata":{"transformedAt":"2026-08-18T18:33:07.862Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":161,"estimatedTokens":1115}}376{"id":"stack-73207167","source":"stackoverflow","questionId":73207167,"title":"nuxt: not found inside docker image","tags":["node.js","docker","nuxt.js"],"text":"Title: nuxt: not found inside docker image\nTags: node.js, docker, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am building a docker environment for a nuxt 3 app. This is my `package.json` file:\n\n```\n{\n \"private\": true,\n \"scripts\": {\n \"start\": \"nuxt start\",\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\",\n \"prepare\": \"husky install\",\n \"prepare:hook\": \"husky add .husky/commit-msg \\\"npx --no -- commitlint --edit $1\"\n },\n \"dependencies\": {\n \"nuxt\": \"3.0.0-rc.6\"\n },\n \"devDependencies\": {\n \"@commitlint/cli\": \"^17.0.3\",\n \"@commitlint/config-conventional\": \"^17.0.3\",\n \"@commitlint/types\": \"^17.0.0\",\n \"@formkit/nuxt\": \"1.0.0-beta.9\",\n \"@formkit/themes\": \"1.0.0-beta.9\",\n \"@formkit/vue\": \"1.0.0-beta.9\",\n \"@nuxt/kit\": \"npm:@nuxt/kit-edge@latest\",\n \"@pinia/nuxt\": \"^0.3.0\",\n \"@swisscom/sdx\": \"file:./sdx\",\n \"@typescript-eslint/eslint-plugin\": \"^5.30.5\",\n \"@typescript-eslint/parser\": \"^5.30.5\",\n \"eslint\": \"^8.19.0\",\n \"eslint-plugin-nuxt\": \"^3.2.0\",\n \"eslint-plugin-prettier\": \"^4.2.1\",\n \"eslint-plugin-vue\": \"^9.2.0\",\n \"husky\": \"^8.0.1\",\n \"luxon\": \"^3.0.1\",\n \"pinia\": \"^2.0.16\",\n \"prettier\": \"2.7.1\",\n \"sass\": \"^1.53.0\",\n \"typescript\": \"^4.7.4\",\n \"vue\": \"^3.2.37\"\n }\n}\n```\n\nThis is my `docker-compose.yml` file:\n\n```\nservices:\n app:\n build:\n context: .\n dockerfile: Dockerfile\n args:\n - NPM_TOKEN=${NPM_TOKEN}\n - NPM_MAIL=${NPM_MAIL}\n restart: always\n ports:\n - '3000:3000'\n env_file:\n - .env\n depends_on:\n - db\n db:\n image: mongo\n restart: always\n ports:\n - 27017:27017\n volumes:\n - smap_db:/usr/db/smap\n environment:\n MONGO_INITDB_ROOT_USERNAME: ${DB_USER}\n MONGO_INITDB_ROOT_PASSWORD: ${DB_PASSWORD}\nvolumes:\n smap_db:\n external: true\n```\n\nAnd this is my `Dockerfile` for the nuxt 3 app:\n\n```\n# Dockerfile\nFROM node:18.6.0-bullseye\n\nARG NPM_TOKEN\nARG NPM_MAIL\n\n# Set working directory\nWORKDIR /usr/bin/smap\n\n# Install dependencies\nCOPY .npmrc package.json sdx ./\nRUN npm install\nRUN rm -f .npmrc\n\n# Copy the app\nCOPY . .\nRUN npm run build\n\nEXPOSE 3000\n\nENV NUXT_HOST=0.0.0.0\n\nCMD [ \"npm\", \"start\" ]\n```\n\nThis is my `.dockerignore` file:\n\n```\n# Dependencies\nnode_modules\n\n# Editor\n.vscode\n\n# Build outputs\n.nuxt\n.output\ndist\n\n# Commitlint\n.husky\ncommitlint.config.ts\n\n# Other\nREADME.md\n```\n\nWhen I run `docker compose up` I get the following error from building the docker file:\n\n```\n=> ERROR [7/7] RUN npm run build 0.8s\n------\n > [7/7] RUN npm run build:\n#0 0.796\n#0 0.796 > build\n#0 0.796 > nuxt build\n#0 0.796\n#0 0.803 /tmp/build6594337338.sh: 2: nuxt: not found\n------\nfailed to solve: executor failed running [/bin/sh -c npm run build]: exit code: 127\n```\n\nHere is what I have tried so far to solve this:\n\n- Deleted all containers, volumes etc. associated with my app and then rebuild everything\n\n- Reset docker to factory settings\n\n- Deactivated the buildkit feature\n\n- Commented everything out in the `.dockerignore`\nTried the following image versions from node:\n\n- `node:18.6.0-bullseye`\n\n- `node:18.6.0`\n\n- `node:18.6.0-alpine`\n\n- `node:18`\n\nAll of this didn't help and I always got the same error.\n\nWhy is the `nuxt` command not found inside the docker container? Am I doing something wrong? Does anyone know how I can fix this?\n\n### Update\n\nI set the `NPM_CONFIG_LOGLEVEL` to `info`. The error is still the same but with some additional information:\n\n```\n=> ERROR [8/8] RUN npm run build 1.7s\n------\n > [8/8] RUN npm run build:\n#0 1.641 npm info using npm@8.15.0\n#0 1.642 npm info using node@v18.7.0\n#0 1.642 npm timing npm:load:whichnode Completed in 0ms\n#0 1.643 npm timing config:load:defaults Completed in 2ms\n#0 1.643 npm timing config:load:file:/usr/local/lib/node_modules/npm/npmrc Completed in 5ms\n#0 1.643 npm timing config:load:builtin Completed in 6ms\n#0 1.643 npm timing config:load:cli Completed in 1ms\n#0 1.644 npm timing config:load:env Completed in 1ms\n#0 1.644 npm timing config:load:file:/usr/bin/smap/.npmrc Completed in 2ms\n#0 1.644 npm timing config:load:project Completed in 5ms\n#0 1.644 npm timing config:load:file:/root/.npmrc Completed in 0ms\n#0 1.644 npm timing config:load:user Completed in 1ms\n#0 1.645 npm timing config:load:file:/usr/local/etc/npmrc Completed in 6ms\n#0 1.645 npm timing config:load:global Completed in 6ms\n#0 1.645 npm timing config:load:validate Completed in 2ms\n#0 1.645 npm timing config:load:credentials Completed in 1ms\n#0 1.645 npm timing config:load:setEnvs Completed in 1ms\n#0 1.645 npm timing config:load Completed in 28ms\n#0 1.645 npm timing npm:load:configload Completed in 28ms\n#0 1.645 npm timing npm:load:mkdirpcache Completed in 1ms\n#0 1.645 npm timing npm:load:mkdirplogs Completed in 1ms\n#0 1.645 npm timing npm:load:setTitle Completed in 1ms\n#0 1.646 npm timing config:load:flatten Completed in 2ms\n#0 1.646 npm timing npm:load:display Completed in 9ms\n#0 1.653 npm timing npm:load:logFile Completed in 7ms\n#0 1.653 npm timing npm:load:timers Completed in 0ms\n#0 1.654 npm timing npm:load:configScope Completed in 0ms\n#0 1.656 npm timing npm:load Completed in 50ms\n#0 1.667\n#0 1.667 > build\n#0 1.667 > nuxt build\n#0 1.667\n#0 1.675 /tmp/build-27aedcc8.sh: 1: nuxt: not found\n#0 1.677 npm timing command:run Completed in 15ms\n#0 1.678 npm timing npm Completed in 74ms\n------\nfailed to solve: executor failed running [/bin/sh -c npm run build]: exit code: 127\n```\n\n========================================\n\nTop Answer:\nI had the same error because my Docker was setup incorrectly, resulting in an empty `node_modules` folder inside the container.\n\nSpecifically, my `docker-compose.yml` had a typical volume mapping as so:\n\n```\nfrontend:\n volumes:\n - ./frontend:/app\n```\n\nIf you have not ran `yarn` or `npm install` locally, this will cause your local directory to overwrite the container's directory, replacing its `node_modules` with an empty folder, and therefore not finding `nuxt` as a command.\n\nFix this by using a named volume instead:\n\n```\nfrontend:\n volumes:\n - ./frontend:/app\n - node_modules:/app/node_modules\n```\n\nYou retain the volume mapping so you get things like hot-reloading, but it will effectively \"exclude\" `node_modules` from being mapped. It also names the volume so it's identifiable in your Docker volumes list.\n\nCredits:\n\n- @David Maze for pointing out the root issue and providing a solution.\n\n- @Nate T for the idea to use named volumes.\n\n========================================\n\nCode:\n```json\n{\n \"private\": true,\n \"scripts\": {\n \"start\": \"nuxt start\",\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\",\n \"prepare\": \"husky install\",\n \"prepare:hook\": \"husky add .husky/commit-msg \\\"npx --no -- commitlint --edit $1\"\n },\n \"dependencies\": {\n \"nuxt\": \"3.0.0-rc.6\"\n },\n \"devDependencies\": {\n \"@commitlint/cli\": \"^17.0.3\",\n \"@commitlint/config-conventional\": \"^17.0.3\",\n \"@commitlint/types\": \"^17.0.0\",\n \"@formkit/nuxt\": \"1.0.0-beta.9\",\n \"@formkit/themes\": \"1.0.0-beta.9\",\n \"@formkit/vue\": \"1.0.0-beta.9\",\n \"@nuxt/kit\": \"npm:@nuxt/kit-edge@latest\",\n \"@pinia/nuxt\": \"^0.3.0\",\n \"@swisscom/sdx\": \"file:./sdx\",\n \"@typescript-eslint/eslint-plugin\": \"^5.30.5\",\n \"@typescript-eslint/parser\": \"^5.30.5\",\n \"eslint\": \"^8.19.0\",\n \"eslint-plugin-nuxt\": \"^3.2.0\",\n \"eslint-plugin-prettier\": \"^4.2.1\",\n \"eslint-plugin-vue\": \"^9.2.0\",\n \"husky\": \"^8.0.1\",\n \"luxon\": \"^3.0.1\",\n \"pinia\": \"^2.0.16\",\n \"prettier\": \"2.7.1\",\n \"sass\": \"^1.53.0\",\n \"typescript\": \"^4.7.4\",\n \"vue\": \"^3.2.37\"\n }\n}\n```\n\n```yaml\nservices:\n app:\n build:\n context: .\n dockerfile: Dockerfile\n args:\n - NPM_TOKEN=${NPM_TOKEN}\n - NPM_MAIL=${NPM_MAIL}\n restart: always\n ports:\n - '3000:3000'\n env_file:\n - .env\n depends_on:\n - db\n db:\n image: mongo\n restart: always\n ports:\n - 27017:27017\n volumes:\n - smap_db:/usr/db/smap\n environment:\n MONGO_INITDB_ROOT_USERNAME: ${DB_USER}\n MONGO_INITDB_ROOT_PASSWORD: ${DB_PASSWORD}\nvolumes:\n smap_db:\n external: true\n```\n\n```text\n# Dockerfile\nFROM node:18.6.0-bullseye\n\nARG NPM_TOKEN\nARG NPM_MAIL\n\n# Set working directory\nWORKDIR /usr/bin/smap\n\n# Install dependencies\nCOPY .npmrc package.json sdx ./\nRUN npm install\nRUN rm -f .npmrc\n\n# Copy the app\nCOPY . .\nRUN npm run build\n\nEXPOSE 3000\n\nENV NUXT_HOST=0.0.0.0\n\nCMD [ \"npm\", \"start\" ]\n```\n\n```text\n# Dependencies\nnode_modules\n\n# Editor\n.vscode\n\n# Build outputs\n.nuxt\n.output\ndist\n\n# Commitlint\n.husky\ncommitlint.config.ts\n\n# Other\nREADME.md\n```\n\n```text\n=> ERROR [7/7] RUN npm run build 0.8s\n------\n > [7/7] RUN npm run build:\n#0 0.796\n#0 0.796 > build\n#0 0.796 > nuxt build\n#0 0.796\n#0 0.803 /tmp/build6594337338.sh: 2: nuxt: not found\n------\nfailed to solve: executor failed running [/bin/sh -c npm run build]: exit code: 127\n```\n\n```text\n=> ERROR [8/8] RUN npm run build 1.7s\n------\n > [8/8] RUN npm run build:\n#0 1.641 npm info using npm@8.15.0\n#0 1.642 npm info using node@v18.7.0\n#0 1.642 npm timing npm:load:whichnode Completed in 0ms\n#0 1.643 npm timing config:load:defaults Completed in 2ms\n#0 1.643 npm timing config:load:file:/usr/local/lib/node_modules/npm/npmrc Completed in 5ms\n#0 1.643 npm timing config:load:builtin Completed in 6ms\n#0 1.643 npm timing config:load:cli Completed in 1ms\n#0 1.644 npm timing config:load:env Completed in 1ms\n#0 1.644 npm timing config:load:file:/usr/bin/smap/.npmrc Completed in 2ms\n#0 1.644 npm timing config:load:project Completed in 5ms\n#0 1.644 npm timing config:load:file:/root/.npmrc Completed in 0ms\n#0 1.644 npm timing config:load:user Completed in 1ms\n#0 1.645 npm timing config:load:file:/usr/local/etc/npmrc Completed in 6ms\n#0 1.645 npm timing config:load:global Completed in 6ms\n#0 1.645 npm timing config:load:validate Completed in 2ms\n#0 1.645 npm timing config:load:credentials Completed in 1ms\n#0 1.645 npm timing config:load:setEnvs Completed in 1ms\n#0 1.645 npm timing config:load Completed in 28ms\n#0 1.645 npm timing npm:load:configload Completed in 28ms\n#0 1.645 npm timing npm:load:mkdirpcache Completed in 1ms\n#0 1.645 npm timing npm:load:mkdirplogs Completed in 1ms\n#0 1.645 npm timing npm:load:setTitle Completed in 1ms\n#0 1.646 npm timing config:load:flatten Completed in 2ms\n#0 1.646 npm timing npm:load:display Completed in 9ms\n#0 1.653 npm timing npm:load:logFile Completed in 7ms\n#0 1.653 npm timing npm:load:timers Completed in 0ms\n#0 1.654 npm timing npm:load:configScope Completed in 0ms\n#0 1.656 npm timing npm:load Completed in 50ms\n#0 1.667\n#0 1.667 > build\n#0 1.667 > nuxt build\n#0 1.667\n#0 1.675 /tmp/build-27aedcc8.sh: 1: nuxt: not found\n#0 1.677 npm timing command:run Completed in 15ms\n#0 1.678 npm timing npm Completed in 74ms\n------\nfailed to solve: executor failed running [/bin/sh -c npm run build]: exit code: 127\n```\n\n```text\npackage.json\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\nDockerfile\n```\n\n```text\n.dockerignore\n```\n\n```text\ndocker compose up\n```\n\n```text\n.dockerignore\n```\n\n```text\nnode:18.6.0-bullseye\n```\n\n```text\nnode:18.6.0\n```\n\n```text\nnode:18.6.0-alpine\n```\n\n```text\nnode:18\n```\n\n```text\nnuxt\n```\n\n```text\nNPM_CONFIG_LOGLEVEL\n```\n\n```text\ninfo\n```\n\n```text\nCOPY .npmrc package.json sdx ./\n```\n\n```text\npackage.json\n```\n\n```text\npackage.json\n```\n\n```text\nsdx\n```\n\n```text\nCOPY\n```\n\n```text\nCOPY\n```\n\n```text\nsdx\n```\n\n```text\nCOPY ./sdx ./sdx\n```\n\n```text\nfrontend:\n volumes:\n - ./frontend:/app\n```\n\n```text\nfrontend:\n volumes:\n - ./frontend:/app\n - node_modules:/app/node_modules\n```\n\n```text\nnode_modules\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\nyarn\n```\n\n```text\nnpm install\n```\n\n```text\nnode_modules\n```\n\n```text\nnuxt\n```\n\n```text\nnode_modules\n```\n\n```text\nRUN npm install --production=false\n```\n\n```text\n--production=false\n```\n\n========================================\n\nComments:\n- Tried with Node16? It's probably not related to your issue but who knows? Also, did you checked some questions there on that same topic? Sorry, I don't have a lot of experience with Docker.\n- I just tried it with node 16 and got the same error :( I am reasearching this problem now for about three days and haven't found an answer. I will open an issue on the nodejs/docker-node github if I don't get an answer here.\n- You can try few more things here and see if it does help. First remove copying the `.npmrc` before installing the node modules in the container. And second, add a `RUN ls node_modules/` and see if nuxt is indeed installed after the `npm install`.\n- I tried to reproduce your problem using nuxt 3 quickstart and the same dockerfile/docker-compose, however it ran successfully in Docker. Please can you try the same activity, if it fails then it could be a problem with your local setup, if it works then it's more likely a problem with your app.\n- @MelkisH. Thanks, that helped a lot. I could solve the problem with your input. I'll ad an answer\n- But does the hot reload still function?\n- In order for hmr to work you need to expose the hmr port\n- You sure about this one? What does it do exactly, mind sharing some official source?","metadata":{"transformedAt":"2026-08-18T18:33:07.862Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":571,"estimatedTokens":3312}}377{"id":"stack-65809613","source":"stackoverflow","questionId":65809613,"title":"How to import boostrap v5 (js + css) into nuxt.js v2.14 with vue v3 project?","tags":["vue.js","nuxt.js","vuejs3","bootstrap-5"],"text":"Title: How to import boostrap v5 (js + css) into nuxt.js v2.14 with vue v3 project?\nTags: vue.js, nuxt.js, vuejs3, bootstrap-5\nSource: Stack Overflow\n\nQuestion:\nAs of today, *bootstrap-vue* does not support ***vue v3*** and ***bootstrap v5***.\n\nI would like to just **import** bootstrap files into ***nuxt v2.14*** project. Could anyone give me a specific example how to accomplish this?\n\nSince I just started vue/nuxt a week ago I would appreciate help at this point.\n\nP.S. Emphasis on CSS **and** JS.\n\n========================================\n\nTop Answer:\nAs I installed bootstrap 5 with npm, I didn't want to do it the same way as the accepted answer so maybe this will be helpfull for someone esle:\n\n-About css:\nI am used to work with scss so I installed sass loader:\n\n```\nnpm install --save-dev sass sass-loader@10 fibers\n```\n\nNext in the assets folder I created a scss folder with a main.scss file inside. In this file you can import bootstrap css (like that you can even override bootstrap variables, don't forget to import them if you want to do that):\n\n```\n@import \"~bootstrap\";\n```\n\nThen in the nuxt.config.js I added this:\n\n```\ncss: [\n '~/assets/scss/main.scss'\n],\n```\n\n-The js part was the most tricky but finally it works perfectly:\n\nIn the plugins folder, just create a file named bootstrap.js\nJust add an import inside:\n\n```\nimport bootstrap from 'bootstrap'\n```\n\nThen in your nuxt.config.js:\n\n```\nplugins: [\n {src: '~/plugins/bootstrap.js', mode: 'client'}\n],\n```\n\nDont't forget the mode:'client', if not you will get 'document is not defined' error because of server side renderning.\n\nEnjoy :)\n\nEdit: the nuxt js version when I write this: 2.15.3 with bootstrap 5 as well :)\n\n========================================\n\nCode:\n```text\nexport default {\n ...\n css: ['~/assets/bootstrap/bootstrap.min.css'],\n script: [\n {\n src: \"~/assets/bootstrap/bootstrap.bundle.min.js\",\n type: \"text/javascript\"\n }\n ]\n ...\n}\n```\n\n```text\nbootstrap\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnpm install --save-dev sass sass-loader@10 fibers\n```\n\n```text\n@import \"~bootstrap\";\n```\n\n```text\ncss: [\n '~/assets/scss/main.scss'\n],\n```\n\n```text\nimport bootstrap from 'bootstrap'\n```\n\n```text\nplugins: [\n {src: '~/plugins/bootstrap.js', mode: 'client'}\n],\n```\n\n========================================\n\nComments:\n- thx for your contribution. I will give this a try. Btw, why dont' people just use the CDN? Performance wise there's not much of a difference anymore between CDN/local, imho. Just makes it much easier.\n- the import in main.scss does not work for me. i use `@import \"node_modules/bootstrap/scss/bootstrap\"` instead;\n- Using Nuxt 3. In main.scss I had to **@import \"bootstrap/scss/bootstrap.scss\";** instead.\n- The import in bootstrap.js does not work for me in Nuxt 3. I have to use `import 'bootstrap/js/index.esm'; export default defineNuxtPlugin(() => { })`","metadata":{"transformedAt":"2026-08-18T18:33:07.862Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":118,"estimatedTokens":733}}378{"id":"stack-69224413","source":"stackoverflow","questionId":69224413,"title":"Where to put custom Vue mixins and helper functions in a Nuxt project?","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: Where to put custom Vue mixins and helper functions in a Nuxt project?\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a Nuxt project and I need to make custom functions and Vue mixins to reuse in Vue components and pages.\n\nIn which folder should I put the files containing these? Should I create a 'lib' folder at the top level of the Nuxt project and put the files in there?\n\nExtra details if that can help:\n\n- These functions will be imported only when needed (not global)\n\n- These functions will be tested\n\nNuxt Directory Structure Documentation\n\n========================================\n\nTop Answer:\nyou can put the mixins file into 2 folders.\n\n- you can create global-mixin.js into the plugins folder and after that set this file into `plugins: []` part in nuxt.config. link\n\n- you can create a mixins folder and create mixin.js into that. link\n\nBut the nuxt.js's documents suggested that the first solution was correct\n\n========================================\n\nCode:\n```text\nimport someMixin from '@/mixins/someMixin'\n...\nexport default {\n mixins: [someMixin],\n ...\n}\n```\n\n```text\nmixins\n```\n\n```text\nmodels\n```\n\n```text\nservices\n```\n\n```text\nutils\n```\n\n```text\nmixins\n```\n\n```text\nplugins: []\n```\n\n```js\nimport Vue from \"vue\"\n\nif (!Vue.__my_mixin__) {\n Vue.__my_mixin__ = true\n Vue.mixin({ \n methods: {\n sayIt(name) {\n console.log(`Hello dear ${name}`)\n }\n }\n })\n}\n```\n\n```js\nplugins: [\n { src: '~/plugins/my-mixin-plugin.js' },\n],\n```\n\n```html\n<template>\n <span>{{ sayIt('Batman') }}</span>\n</template>\n```\n\n```js\nthis.sayIt('Batman')\n```\n\n```text\ncommon\n```\n\n```text\nmyMixinFolder\n```\n\n```text\nmyMixinFolder\n```\n\n```text\nmy-mixin-plugin.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nscript\n```\n\n========================================\n\nComments:\n- Nuxt do not have any specific folder aimed for mixins, you can any convention that you'd like here.","metadata":{"transformedAt":"2026-08-18T18:33:07.862Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":123,"estimatedTokens":480}}379{"id":"stack-60648515","source":"stackoverflow","questionId":60648515,"title":"How to implement Facebook Messenger customer chat SDK in Nuxt, Vue?","tags":["vue.js","nuxt.js","facebook-messenger","facebook-chatbot","facebook-customer-chat"],"text":"Title: How to implement Facebook Messenger customer chat SDK in Nuxt, Vue?\nTags: vue.js, nuxt.js, facebook-messenger, facebook-chatbot, facebook-customer-chat\nSource: Stack Overflow\n\nQuestion:\ni was doing this implementation with **Facebook Messenger customer chat SDK** into my Nuxt app.\n\n**Solution 1 (worked 0%):**\n\nI tried the https://www.npmjs.com/package/vue-fb-customer-chat package, and it didn't work, the package's site itself is down -.-! i import it and use it as a plugins and so on, i did **as exactly as instructed**, i even tried to use `` and `` as extra too, but nothing seem to work!\n\n**Solution 2 (worked 50%):**\n\nMoreover, i tried to use it as a static file by creating a static file called `fb-sdk.js` and successfully deploy it:\n\n```\nwindow.fbAsyncInit = function() {\n FB.init({\n xfbml: true,\n version: \"v6.0\"\n })\n}\n;(function(d, s, id) {\n var js,\n fjs = d.getElementsByTagName(s)[0]\n if (d.getElementById(id)) return\n js = d.createElement(s)\n js.id = id\n js.src = \"https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js\"\n fjs.parentNode.insertBefore(js, fjs)\n})(document, \"script\", \"facebook-jssdk\")\n```\n\nbut i got this error when begin to chat using it:\n\n```\nErrorUtils caught an error:\n\na.substr is not a function. [Caught in: React reported an error]\n\nSubsequent errors won't be logged; see https://fburl.com/debugjs.\n```\n\nThe chat box came up and disappear, then it was no longer clickable @@\n\nSo please help me adding **Facebook Messenger customer chat SDK** into **NuxtJS**, is there a package? a step-by-step tutorial?\n\n========================================\n\nTop Answer:\nFWIW, here’s how I implemented it in Nuxt without installing a 3rd party package, and it’s working.\n\nYour `default.vue` layout:\n\n```\n...\n\n...\n```\n\nYour `nuxt.config.js` (which is the script Facebook asks you to insert so copy it from your own instructions):\n\n```\n...\n\nscript: [\n {\n type: 'text/javascript',\n hid: 'fb-customer-chat',\n body: true,\n innerHTML: `\n var chatbox = document.getElementById('fb-customer-chat');\n chatbox.setAttribute(\"page_id\", YOUR_PAGE_ID);\n chatbox.setAttribute(\"attribution\", \"biz_inbox\");\n\n window.fbAsyncInit = function() {\n FB.init({\n xfbml : true,\n version : 'v11.0'\n });\n };\n\n (function(d, s, id) {\n var js, fjs = d.getElementsByTagName(s)[0];\n if (d.getElementById(id)) return;\n js = d.createElement(s); js.id = id;\n js.src = 'https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js';\n fjs.parentNode.insertBefore(js, fjs);\n }(document, 'script', 'facebook-jssdk'));`\n },\n],\n__dangerouslyDisableSanitizersByTagID: { 'fb-customer-chat': ['innerHTML'] },\n\n...\n```\n\nThe `__dangerouslyDisableSanitizersByTagID` setting ensures that the code inside `innerHTML` with the hid `fb-customer-chat` won’t be sanitized.\n\n========================================\n\nCode:\n```text\nwindow.fbAsyncInit = function() {\n FB.init({\n xfbml: true,\n version: \"v6.0\"\n })\n}\n;(function(d, s, id) {\n var js,\n fjs = d.getElementsByTagName(s)[0]\n if (d.getElementById(id)) return\n js = d.createElement(s)\n js.id = id\n js.src = \"https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js\"\n fjs.parentNode.insertBefore(js, fjs)\n})(document, \"script\", \"facebook-jssdk\")\n```\n\n```text\nErrorUtils caught an error:\n\na.substr is not a function. [Caught in: React reported an error]\n\nSubsequent errors won't be logged; see https://fburl.com/debugjs.\n```\n\n```text\n<VueFbCustomerChat />\n```\n\n```text\n<vue-fb-customer-chat />\n```\n\n```text\nfb-sdk.js\n```\n\n```text\n...\n\n<div id=\"fb-root\"></div>\n<div id=\"fb-customer-chat\" class=\"fb-customerchat\"></div>\n\n...\n```\n\n```text\n...\n\nscript: [\n {\n type: 'text/javascript',\n hid: 'fb-customer-chat',\n body: true,\n innerHTML: `\n var chatbox = document.getElementById('fb-customer-chat');\n chatbox.setAttribute(\"page_id\", YOUR_PAGE_ID);\n chatbox.setAttribute(\"attribution\", \"biz_inbox\");\n\n window.fbAsyncInit = function() {\n FB.init({\n xfbml : true,\n version : 'v11.0'\n });\n };\n\n (function(d, s, id) {\n var js, fjs = d.getElementsByTagName(s)[0];\n if (d.getElementById(id)) return;\n js = d.createElement(s); js.id = id;\n js.src = 'https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js';\n fjs.parentNode.insertBefore(js, fjs);\n }(document, 'script', 'facebook-jssdk'));`\n },\n],\n__dangerouslyDisableSanitizersByTagID: { 'fb-customer-chat': ['innerHTML'] },\n\n...\n```\n\n```text\ndefault.vue\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n__dangerouslyDisableSanitizersByTagID\n```\n\n```text\ninnerHTML\n```\n\n```text\nfb-customer-chat\n```\n\n========================================\n\nComments:\n- I am facing the same error. Interestingly, it works fine on some of my colleagues' machines(not all). For one of the colleague, it worked with Incognito mode.\n- I can'tseem to get it to work after following the doc. After adding a .js file in the plugin folder and include the plugin in the nuxt config file. Do I have to do anything else?\n- I have the same issue, I have implemented it on a real url that is https and I still get nothing.\n- @JamieBonnett, are you using Nuxt or Vue?\n- @StivenRamírezArango Nuxt","metadata":{"transformedAt":"2026-08-18T18:33:07.863Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":210,"estimatedTokens":1300}}380{"id":"stack-52369628","source":"stackoverflow","questionId":52369628,"title":"Nuxt transition not working on diffents layouts","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Nuxt transition not working on diffents layouts\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt for my new website, and I create a CSS transition with page-enter-active class, but it's only working on the pages based on the default layout.\n\nA simple demo of the problem : https://test-transition-layout.netlify.com/\n\nWhen browsing from or to the home page (based on a different layout), there's no transition. But if you navigate from team page to about, you can see it.\n\nThe code of the demo : https://github.com/KevinFuret/test-template-transition\n\nThanks a lot for your help\n\n========================================\n\nCode:\n```text\n.page-enter-active,\n.page-leave-active,\n.layout-enter-active, \n.layout-leave-active {\n transition: opacity .5s\n}\n\n.page-enter,\n.page-leave-active,\n.layout-enter, \n.layout-leave-active {\n opacity: 0\n}\n```\n\n```text\nassets/main.css\n```\n\n========================================\n\nComments:\n- Thanks a lot for the help !","metadata":{"transformedAt":"2026-08-18T18:33:07.863Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":42,"estimatedTokens":249}}381{"id":"stack-55890252","source":"stackoverflow","questionId":55890252,"title":"How to access Nuxt context variable from Vuex action","tags":["vue.js","vuex","nuxt.js"],"text":"Title: How to access Nuxt context variable from Vuex action\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to access context variable to use the `isMobile` flag to select a different endpoint depending on the result. I could pass it on the `dispatch` from the component, but I know there should be one way to do it.\n\n```\nexport const actions = {\n...\n signUpGoogle({ commit }) {\n fireauth.useDeviceLanguage()\n\n if (context.isMobile) {\n fireauth.signInWithPopup(GoogleProvider).then ...\n\n } else {\n fireauth.signInWithRedirect(GoogleProvider)\n }\n\n}\n```\n\nI saw here that it can be obtained on server init, but I really don't want to rely on this as caching will mess things up\n\nhttps://nuxtjs.org/guide/vuex-store/#the-nuxtserverinit-action\n\nThanks for the help\n\n========================================\n\nTop Answer:\nYou can do one thing in nuxtServerInit, set this variable in state using the context, and then use state.isMobile to do this type of API Calls. Hopefully, that should solve this.\nIf it's not very clear, I can edit to give some code examples\n\n========================================\n\nCode:\n```js\nexport const actions = {\n...\n signUpGoogle({ commit }) {\n fireauth.useDeviceLanguage()\n\n if (context.isMobile) {\n fireauth.signInWithPopup(GoogleProvider).then ...\n\n } else {\n fireauth.signInWithRedirect(GoogleProvider)\n }\n\n}\n```\n\n```text\nisMobile\n```\n\n```text\ndispatch\n```\n\n```text\nthis.app.$config.isMobile\n```\n\n```text\npublicRuntimeConfig\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- not quite understand what u mean. But nuxtServerInit executes on first request each time and there no caching","metadata":{"transformedAt":"2026-08-18T18:33:07.863Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":78,"estimatedTokens":424}}382{"id":"stack-67751476","source":"stackoverflow","questionId":67751476,"title":"How to fix navigator / window / document is undefined in Nuxt","tags":["javascript","vue.js","nuxt.js"],"text":"Title: How to fix navigator / window / document is undefined in Nuxt\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI was trying to determined UserAgent and Retina info inside Nuxt application. But the application is throwing an error and showing navigatior / window is undefined. How can i get these info inside nuxt application?\n\n```\nconst userAgent = navigator.userAgent.toLowerCase()\nconst isAndroid = userAgent.includes('android')\n```\n\n```\nisRetina() {\n let mediaQuery\n if (typeof window !== 'undefined' && window !== null) {\n mediaQuery =\n '(-webkit-min-device-pixel-ratio: 1.25), (min--moz-device-pixel-ratio: 1.25), (-o-min-device-pixel-ratio: 5/4), (min-resolution: 1.25dppx)'\n if (window.devicePixelRatio > 1.25) {\n return true\n }\n if (window.matchMedia && window.matchMedia(mediaQuery).matches) {\n return true\n }\n }\n return false\n}\n```\n\n========================================\n\nCode:\n```js\nconst userAgent = navigator.userAgent.toLowerCase()\nconst isAndroid = userAgent.includes('android')\n```\n\n```js\nisRetina() {\n let mediaQuery\n if (typeof window !== 'undefined' && window !== null) {\n mediaQuery =\n '(-webkit-min-device-pixel-ratio: 1.25), (min--moz-device-pixel-ratio: 1.25), (-o-min-device-pixel-ratio: 5/4), (min-resolution: 1.25dppx)'\n if (window.devicePixelRatio > 1.25) {\n return true\n }\n if (window.matchMedia && window.matchMedia(mediaQuery).matches) {\n return true\n }\n }\n return false\n}\n```\n\n```html\n<script>\nimport { jsPlumb } from 'jsplumb' // client-side library only, no SSR support\n\nexport default {\n mounted() {\n if (process.client) {\n // your JS code here like >> jsPlumb.ready(function () {})\n }\n },\n}\n</script>\n```\n\n```html\n<template>\n <div>\n <p>this will be rendered on both: server + client</p>\n \n <client-only>\n <p>this one will only be rendered on client</p>\n </client-only>\n <div>\n</template>\n```\n\n```js\nexport default {\n components: {\n [process.client && 'VueEditor']: () => import('vue2-editor'),\n }\n}\n```\n\n```text\nnavigator is undefined\n```\n\n```text\nwindow is undefined\n```\n\n```text\ndocument is not defined\n```\n\n```text\nmounted\n```\n\n```text\nprocess.client\n```\n\n```text\nmounted\n```\n\n```text\n<client-only>\n```\n\n```text\nclient-only\n```\n\n```text\nvue-editor\n```\n\n========================================\n\nComments:\n- Hi for some reason even after following the steps you have mentioned it does not seem to work and I am getting `document is not defined` error. I have posted my question here can you please help me out with this? stackoverflow.com/q/69814456/7584240\n- Is it possible to assign then a name to the component with this syntax? (I'm trying to use this trick with `VueTouch`, but I have to name it `v-touch` to make it work)\n- @Joe82 `[process.client && 'VTouch'] ...` should do the trick yeah.\n- With `[process.client && 'VTouch']` I get `Failed to mount component: template or render function not defined.`, and with `[process.client && 'VueTouch']` I get `Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the \"name\" option.`\n- @Joe82 it looks like vue-touch is not compatible/maintained anymore: github.com/vuejs/vue-touch Are you talking about another package? Feel free to open a new question and mention this answer. I'll help you more in-depth. :)","metadata":{"transformedAt":"2026-08-18T18:33:07.863Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":132,"estimatedTokens":840}}383{"id":"stack-48607646","source":"stackoverflow","questionId":48607646,"title":"vuefity translate v-text-field label","tags":["vue.js","vuejs2","nuxt.js","vuetify.js"],"text":"Title: vuefity translate v-text-field label\nTags: vue.js, vuejs2, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nI need to translate the label (and placeholder) of vuetify text-field (`v-text-field`). The code looks like this\n\n```\n(...)\n\n \n(...)\n\n import VuetifyGoogleAutocomplete from 'vuetify-google-autocomplete'\n export default {\n data () {\n return {\n registerAddressLabel () {\n return this.$t('common.addressLabel')\n },\n registerAddress: '',\n registerEmail: '',\n registerPassword: '',\n registerName: ''\n }\n },\n methods: {\n getAddressData (addressData, placeholderResultData) {\n\n }\n },\n components: {\n VuetifyGoogleAutocomplete\n }\n }\n\n```\n\nin the first case (also tried with autocomplete) the label is exactly (`$t('common.nameLabel')` as a string). so it seems it doesn't handle as a function.\nIs it possible to translate all labels this way?\n\n========================================\n\nTop Answer:\nYou can also do it without the word v-bind, just with the colon:\n\n```\n\n```\n\n========================================\n\nCode:\n```text\n<template>(...)\n<v-text-field\n label=\"$t('common.nameLabel')\"\n v-model=\"registerName\"\n required\n ></v-text-field>\n<vuetify-google-autocomplete\n ref=\"registerAddress\"\n id=\"map\"\n dark\n label=\"registerAddressLabel\"\n google-api-key=\"Xyz\"\n v-on:placechanged=\"getAddressData\"\n >\n </vuetify-google-autocomplete>\n(...)</template>\n<script>\n import VuetifyGoogleAutocomplete from 'vuetify-google-autocomplete'\n export default {\n data () {\n return {\n registerAddressLabel () {\n return this.$t('common.addressLabel')\n },\n registerAddress: '',\n registerEmail: '',\n registerPassword: '',\n registerName: ''\n }\n },\n methods: {\n getAddressData (addressData, placeholderResultData) {\n\n }\n },\n components: {\n VuetifyGoogleAutocomplete\n }\n }\n</script>\n```\n\n```text\nv-text-field\n```\n\n```text\n$t('common.nameLabel')\n```\n\n```text\n<v-text-field\n v-bind:label=\"$t('common.nameLabel')\"\n v-model=\"registerName\"\n required></v-text-field>\n```\n\n```text\nv-bind\n```\n\n```text\n<v-text-field\n :label=\"$t('common.nameLabel')\"\n v-model=\"registerName\"\n required>\n</v-text-field>\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.863Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":122,"estimatedTokens":554}}384{"id":"stack-67604476","source":"stackoverflow","questionId":67604476,"title":"How to add Quasar to an existing Nuxt app?","tags":["javascript","vue.js","nuxt.js","quasar-framework"],"text":"Title: How to add Quasar to an existing Nuxt app?\nTags: javascript, vue.js, nuxt.js, quasar-framework\nSource: Stack Overflow\n\nQuestion:\nI want to install Quasar to my existing Nuxt project. I've been reading through the quasar docs and the only thing they mentioned in the installation page is their own CLI which has no option for Nuxt. I also came across the nuxt-quasar module but it not maintained anymore. Has anyone have any experience with this?\n\n========================================\n\nTop Answer:\nIf it's Vue compatible then it's Nuxt compatible. Period. No idea what the accepted answer is talking about it being cumbersome, it's the same process as you do for any other framework, basically identical to what you do with e.g. Vuetify. Non-standard for Quasar, sure, but it's Vue compatible, there's nothing particularly cumbersome or difficult about it.\n\nHere's how you do it in Nuxt 3. Slightly different for Nuxt 2 where you import Vue in order to `.use` something, I made it for Nuxt 3 to be more future proof.\n\nFrom https://quasar.dev/start/umd. Just do the same things they do there, but in a Nuxt manner. First they get styles and fonts in the head. Then they get the scripts. Then they register Quasar in Vue. Lets do that now!\n\n```\n// plugins/quasar.js\nimport 'quasar/dist/quasar.prod.css'\nimport Quasar from 'quasar/dist/quasar.umd.prod';\n\nexport default defineNuxtPlugin((nuxtApp) => {\n nuxtApp.vueApp.use(Quasar, {\n config: {\n // options\n }\n })\n})\n```\n\n```\n// nuxt.config.js\n{\n plugins: [\n '~/plugins/quasar.js'\n ]\n}\n```\n\nDone! Now we can use it like this:\n\n```\n\n \n \n\n### Hello World!\n\n \n\n```\n\n========================================\n\nCode:\n```js\n// plugins/quasar.js\nimport 'quasar/dist/quasar.prod.css'\nimport Quasar from 'quasar/dist/quasar.umd.prod';\n\nexport default defineNuxtPlugin((nuxtApp) => {\n nuxtApp.vueApp.use(Quasar, {\n config: {\n // options\n }\n })\n})\n```\n\n```js\n// nuxt.config.js\n{\n plugins: [\n '~/plugins/quasar.js'\n ]\n}\n```\n\n```html\n<q-page-container>\n <q-page>\n <h1>Hello World!</h1>\n </q-page>\n</q-page-container>\n```\n\n```text\n.use\n```\n\n========================================\n\nComments:\n- Yes, I'm still figuring things out but you led me to the right path\n- Down voted. I have a project in production for years now running nuxt2 and vuetify but don’t like discouraging people not to use other ui framework.\n- @bob Vue2 will be EOL by the end of the year, so I recommend that you actually update towards Nuxt3. Otherwise, I never told something negative about using Nuxt + Vuetify (quite the opposite tbh). Meanwhile, I totally do not recommend Nuxt + Quasar for the sole purpose of being able to use Vuetify indeed. So I'm not sure where am I discouraging people to use a UI framework here.\n- Actually, after reading the issue here -> github.com/quasarframework/quasar/issues/11165 @kissu is correct! Quasar does it's own thing when it comes to SSR so its components will not work with Nuxt!\n- Cumbersome in the way that it's not really meant for such purpose. You can of course include a Remix app inside of a Nuxt one too for sure. Having 2 meta frameworks working at the same time is probably not the best approach, this is all I meant. Especially since it's an UMD build and not an ESM one. Also, context is important: I wrote my answer 13 months ago, things have maybe moved from that time. Still, I would not import the whole style + JS in that manner anyway, even if it's doable.\n- Also, `nuxtApp.vueApp.use` is a Nuxt3 only thing. Here, OP asked the question with a regular `nuxt.js` tag (especially regarding the time). So, your answer is not accurate for his use case.\n- The `nuxt.js` tag is for Nuxt, it's not version specific. The OP asked for how to do it in Nuxt never specifying which verison. It's 100% accurate for the question asked. If he wants it for Nuxt 2 I also gave instructions regarding which changes would have to be made, which is literally the same instructions for any regular plugin in Nuxt, which I guarantee he's familiar with how to do, adding an example for Nuxt 3 is more relevant today, regardless of whether your answer was from 13 months ago or not.\n- As with everything, you don't specify a major version initially. Hence we don't have a Nuxt v2 tag here (not really useful IMO). Also, given the context, Nuxt3 was not RC-released yet at that date hence why I answered with a Nuxt2 target in mind. I do agree on it being future-proof for sure! Meanwhile, I'm not sure about the assumption that anybody knows how to write that in a v2 syntax, an edit with the proper code would be highly welcome. I already did that to some of my answers (provide answes for both versions). Finally, even if your solution works I would still not recommend it (perf).\n- I think the OP wanted to use Quasar for components and not the CLI and framework itself and so this answer addresses that.\n- @TwoFingerRightClick no point into using quasar, material UI (through Vuetify for example) is enough for just components.\n- @kissu you can't seriously be suggesting that he swaps Quasar with Vuetify because of that line of reasoning... He needs a UI framework, both frameworks do the job he wants them to do, in nearly an identical manner, if he wants to use Quasar why shouldn't he? Because there's another framework that can also do it? That's not how any of this works and you know it\n- @SimonHyll apparently it's not clear enough so I will explain it in an even simpler manner with a representative example of both Quasar and Nuxt. Nuxt is a meta-framework, being able to offer you Bacon burgers, chicken burgers, and fries, like Mcdonald's. Quasar is a meta-framework too, so like BurgerKing, perfect for Bacon burgers, wraps, and chicken burgers. Now, if you are at McD and you want a chicken burger, what do you do? Do you order it there (at McDo/Nuxt)? Or do you **BUILD** a BurgerK/Quasar building **INSIDE** of McDo/Nuxt? Both can deliver materials UI components.\n- @SimonHyll it's like saying: \"Oh, I'm using Nuxt as of right now but I need **axios** for my HTTP calls. I need to Install NextJS (React's most popular meta-framework) for that purpose\". No. You install axios and wire it to Nuxt, no need to bring something totally unrelated, overkill, and slow down your web app. There are tools for specific use cases, using 10% of them to fill a gap is not a proper way of thinking. Install just what you need. Need a UI framework? Install the UI framework and not a huge monster with 50 features, 1 feature of those 50 being a UI framework. Seems reasonable to me\n- @kissu The problem with that example is that when you install something like Quasar, React, NextJS or whatever meta-framework you want, that doesn't mean you actually in the end use everything those frameworks offer. You can use just a subset of what they offer. By doing so it's easier later if you decide to use more things to extend your current toolbox with a framework you've already set up. If I like the burgers at Burger King but prefer the drinks at McD, I can install both and get just the parts I want. There's nothing overkill here because I'm not buying everything they offer from both.\n- @SimonHyll this is a quite naive way of thinking because this is not how it is, unfortunately. You cannot code-split everything, especially the configuration files etc, it's not meant for such a purpose. Try it yourself and check the final bundle size, you'll be fixed quickly. Still, having both frameworks used is redundant and useless from a cognitive load aspect + performance + configuration complexity. Also, those considerations should not be: \"Eh, whatever will happen in the long run\" kind of thinking but well-thought from the beginning. As for the example, it's actually not like you can\n- @SimonHyll only take the drinks from McD because their building will take 200 square meters in your current BurgerK building. That one is not optional. Also, why even bother paying the BurgerK tax, while you have a Lawson next door to buy your drink (`npm` is not a huge hard thing that you need to reach for, `npm i vuetify` is quite fast to type overall). So yeah, it is overkill because it's kinda asking your kid to get some parts from McD and BurgerK and can lead to confusion. While, bringing your own drink and ordering a burger is far simpler than a mental load, again.\n- @SimonHyll even doing a major migration is usually a pain and can be quite complex if your app is somewhat complex. I've been there, and it's quite hardcore even for somebody who daily used Nuxt. Mixing both? That would be quite a pain that you inflict on yourself and on which one you will spend countless hours trying to have both working down the road with dependencies, conflicts, and opinionated ways of thinking from 2 developer groups. JS world is rough and it's not all pink, plugging various pieces together without **heavy** maintenance down the road. Don't make it complex from the start.\n- Haven't read this wall of text, but fortunately there is a great plugin here that integrates Quasar with Nuxt: github.com/Maiquu/nuxt-quasar\n- @JasonLandbridge this wall is quite unrelated to your answer tho. And everybody sees it but thanks for your input anyway.\n- @JasonLandbridge just ignore him, I've tried talking sense with him, he learned programming sometime during early 2000 and is convinced that's how things still work\n- @SimonHyll not sure if you or Jason didn't read the thread here. Quite a troll sir. Whatever. I guess you drink sparkling water btw (if we're on the page of making some random assumptions out of the blue).\n- @SimonHyll yeah fully agree, I've seen him ranting on way too many questions always spouting the same nonsense. It's like he HAS to say something even though it has nothing to do with answering the question. I opted to ignore him too and hopefully help others find a way to solve their Nuxt-quasar related questions.\n- @JasonLandbridge got an example of such questions sir? I'm eager to see what I can improve here tbh. Usually, my feedback is not totally unrelated AFAIK. There are also (unfortunately) some rules on Stackoverflow that you have to comply with.\n- Link-only answers are not viable, unfortunately. Please try to add more information (like a few steps on how to set it up) at least.","metadata":{"transformedAt":"2026-08-18T18:33:07.863Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":117,"estimatedTokens":2579}}385{"id":"stack-53081769","source":"stackoverflow","questionId":53081769,"title":"SyntaxError: Unexpected token export when using lodash with Nuxt","tags":["vue.js","nuxt.js"],"text":"Title: SyntaxError: Unexpected token export when using lodash with Nuxt\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHere is my repo with live demo https://github.com/alechance/nuxt-lodash. I'm using Nuxt with Vuetify + lodash-es, when running `npm run dev` and reload my page I got a `SyntaxError: Unexpected token export` with `export default isArray;`\n\n========================================\n\nCode:\n```text\nnpm run dev\n```\n\n```text\nSyntaxError: Unexpected token export\n```\n\n```text\nexport default isArray;\n```\n\n```text\nbuild: {\n transpile: [\n 'lodash-es'\n ],\n // Other build options\n}\n```\n\n```text\nlodash-es\n```\n\n```text\nbabel\n```\n\n```text\nbuild\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- Thank you, it's working. However I wanted to test Vuetify `a la carte` with `babel-plugin-transform-imports` and I still got this error. I just updated the repo in github github.com/alechance/nuxt-lodash, I don't understand the problem...\n- `babel-plugin-transform-imports` overwrites `transpile` configuration. If you want to have tree-shaking, you can use latest version of nuxt with official vuetify recommendation for a la carte. Or use vuetify-loader that will bundle and split component's automatically. Or even use babel-plugin-lodash, as another option.\n- OK good, I tried something else here github.com/alechance/nuxt-vuetify-lodash, lodash and vuetify seem to be working, however it looks like my app is loading every vuetify components. Then I tried to overwrite vuetify styles with my own CSS, vuetify always comes after my styles. Any idea why? Thank you!\n- Glad it works. This is out of scope of current question, but from personal experience, fully featured UI libraries usually do not expect their styles being overwritten. Total cost of such overwrite, eventually, is higher than recreating necessary component's on your own. This is personal experience, not a trend.\n- Yes I understand, I just want to change a few CSS properties and do not want to write `!important` in my styles. It looks like my CSS is rendered in my `` before the ones from vueitfy. Do you know how I can change the order in my `` so that my styles come after vuetify CSS? I know it's out of scope from my initial question...","metadata":{"transformedAt":"2026-08-18T18:33:07.863Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":55,"estimatedTokens":568}}386{"id":"stack-50663868","source":"stackoverflow","questionId":50663868,"title":"Nuxtjs async await in a page doesnt work on page refresh","tags":["javascript","vuejs2","nuxt.js"],"text":"Title: Nuxtjs async await in a page doesnt work on page refresh\nTags: javascript, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nAm trying to fetch data in the fetch method of my page using vuex and nuxt js but whenever a person refreshes the page it fails but works when i navigate through nuxt navigation\n\nSo in my page i have\n\n```\nfetch ({ store, params }) {\n store.dispatch('getJobspecialisims')\n },\n\n //IVE ALSO TRIED ASYNC\n async asyncData (context) {\n await context.store.dispatch('getJobspecialisims');\n },\n```\n\nSO in my vuex action i have\n\n```\nasync getJobspecialisims({commit}){\n await axios.get(process.env.baseUrl+'/job-specialisims').then((res)=>{\n commit(types.SET_JOB_SPECIALISIMS, res.data.data)\n },(err)=>{\n console.log(\"an error occured \", err);\n });\n },\n```\n\nNow on my component where am fetching the records\n\n```\n\n \n \n \n```\n\nThe http request is nver sent when a person refreshes the browser\n\nWhere am i going wrong?\nI would prefer the async await method. I uderstand that it returns a promise but i have no idea on how to know when the promise has resolved. Thepage should always await untill the data has been completely ffetched hence ive called the fetch or asyncdata method in my page\n\nWhat else do i need to add or amend?\n\n========================================\n\nCode:\n```text\nfetch ({ store, params }) {\n store.dispatch('getJobspecialisims')\n },\n\n //IVE ALSO TRIED ASYNC\n async asyncData (context) {\n await context.store.dispatch('getJobspecialisims');\n },\n```\n\n```text\nasync getJobspecialisims({commit}){\n await axios.get(process.env.baseUrl+'/job-specialisims').then((res)=>{\n commit(types.SET_JOB_SPECIALISIMS, res.data.data)\n },(err)=>{\n console.log(\"an error occured \", err);\n });\n },\n```\n\n```text\n<div>\n <li v-for=\"(specialisim) in $store.getters.jobspecialisims\">\n <!-DO STUFF HERE-> \n </li>\n```\n\n```text\nfetch ({ store, params }) {\n // store.dispatch('getJobspecialisims')\n return store.dispatch('getJobspecialisims')\n},\n```\n\n```text\nasync getJobspecialisims({ commit }) {\n const res = await axios.get(YOUR_URL);\n if (!res.error) {\n commit(\"getJobspecialisims\", res.data.data);\n } else {\n console.log(res.error);\n }\n}\n```\n\n========================================\n\nComments:\n- `The http request is nver sent when a person refreshes the browser` is nuxt.js or the browser caching? Did you use the dev tools in the browser (network tab) and see if you have cached results in there? I'm not sure how to check cache settings in nuxt.js but you could start with the browser.\n- there are no cached results ive checked","metadata":{"transformedAt":"2026-08-18T18:33:07.863Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":102,"estimatedTokens":657}}387{"id":"stack-67644948","source":"stackoverflow","questionId":67644948,"title":"How do I access localStorage or mock localStorage for Jest + vue-test-utils tests?","tags":["javascript","jestjs","nuxt.js","vue-test-utils"],"text":"Title: How do I access localStorage or mock localStorage for Jest + vue-test-utils tests?\nTags: javascript, jestjs, nuxt.js, vue-test-utils\nSource: Stack Overflow\n\nQuestion:\nI am trying to test an axios request, and I need to use an auth token in order to access the endpoint, however my test fails because I am getting \"Bearer null\" and inputting this into my headers.Authorization. Here is my actual code below\n\nFile I'm testing:\n\n```\nthis.$axios.get(url, { headers: { Authorization: `Bearer ${localStorage.getItem(\"access-token\")}` } })\n .then((response) => {\n this.loading = true; \n // Get latest barcode created and default it to our \"from\" input\n this.barcodeFrom = response.data.data[response.data.data.length - 1]['i_end_uid'] + 1;\n this.barcodeTo = this.barcodeFrom + 1;\n this.barcodeRanges = response.data.data;\n\n // Here we add to the data array to make printed barcodes more obvious for the user\n this.barcodeRanges.map(item => item['range'] = `${item['i_start_uid']} - ${item['i_end_uid']}`);\n\n // Make newest barcodes appear at the top\n this.barcodeRanges.sort((a, b) => new Date(b['created_at']) - new Date(a['created_at']));\n })\n .catch((error) => {\n console.log('Barcode retrieval error:', error);\n this.barcodeFrom === 0 ? null : this.snackbarError = true;\n })\n .finally(() => {\n // Edge case when there's no barcode records\n this.barcodeFrom === 0 ? this.barcodeTo = 1 : null;\n this.loading = false\n });\n console.log('bcr', this.barcodeRanges);\n```\n\nTest file:\n\n```\nimport Vuetify from \"vuetify\";\nimport Vuex from \"vuex\";\nimport { createLocalVue, shallowMount } from \"@vue/test-utils\";\nimport VueMobileDetection from \"vue-mobile-detection\";\nimport axios from 'axios';\n\nimport index from \"@/pages/barcode_logs/index\";\n\ndescribe('/pages/barcode_logs/index.vue', () => {\n // Initialize our 3rd party stuff\n const localVue = createLocalVue();\n localVue.use(Vuetify);\n localVue.use(Vuex);\n localVue.use(axios);\n localVue.use(VueMobileDetection);\n\n // Initialize store\n let store;\n\n // Create store\n store = new Vuex.Store({\n modules: {\n core: {\n state: {\n labgroup:{\n current: {\n id: 1\n }\n }\n }\n }\n }\n });\n\n // Set-up wrapper options\n const wrapperOptions = {\n localVue,\n store,\n mocks: {\n $axios: {\n get: jest.fn(() => Promise.resolve({ data: {} }))\n }\n }\n };\n\n // Prep spies for our component methods we want to validate\n const spycreateBarcodes = jest.spyOn(index.methods, 'createBarcodes');\n const createdHook = jest.spyOn(index, 'created');\n // Mount the component we're testing\n const wrapper = shallowMount(index, wrapperOptions);\n\n test('if barcode logs were retrieved', () => {\n expect(createdHook).toHaveBeenCalled();\n expect(wrapper.vm.barcodeRanges).toHaveLength(11);\n });\n\n});\n```\n\nHow do I mock or get the actual auth token in to work in my test?\n\n========================================\n\nTop Answer:\n```\nconst setItem = jest.spyOn(Storage.prototype, 'setItem')\nconst getItem = jest.spyOn(Storage.prototype, 'getItem')\n\nexpect(setItem).toHaveBeenCalled()\nexpect(getItem).toHaveBeenCalled()\n```\n\n========================================\n\nCode:\n```text\nthis.$axios.get(url, { headers: { Authorization: `Bearer ${localStorage.getItem(\"access-token\")}` } })\n .then((response) => {\n this.loading = true; \n // Get latest barcode created and default it to our \"from\" input\n this.barcodeFrom = response.data.data[response.data.data.length - 1]['i_end_uid'] + 1;\n this.barcodeTo = this.barcodeFrom + 1;\n this.barcodeRanges = response.data.data;\n\n // Here we add to the data array to make printed barcodes more obvious for the user\n this.barcodeRanges.map(item => item['range'] = `${item['i_start_uid']} - ${item['i_end_uid']}`);\n\n // Make newest barcodes appear at the top\n this.barcodeRanges.sort((a, b) => new Date(b['created_at']) - new Date(a['created_at']));\n })\n .catch((error) => {\n console.log('Barcode retrieval error:', error);\n this.barcodeFrom === 0 ? null : this.snackbarError = true;\n })\n .finally(() => {\n // Edge case when there's no barcode records\n this.barcodeFrom === 0 ? this.barcodeTo = 1 : null;\n this.loading = false\n });\n console.log('bcr', this.barcodeRanges);\n```\n\n```text\nimport Vuetify from \"vuetify\";\nimport Vuex from \"vuex\";\nimport { createLocalVue, shallowMount } from \"@vue/test-utils\";\nimport VueMobileDetection from \"vue-mobile-detection\";\nimport axios from 'axios';\n\nimport index from \"@/pages/barcode_logs/index\";\n\ndescribe('/pages/barcode_logs/index.vue', () => {\n // Initialize our 3rd party stuff\n const localVue = createLocalVue();\n localVue.use(Vuetify);\n localVue.use(Vuex);\n localVue.use(axios);\n localVue.use(VueMobileDetection);\n\n // Initialize store\n let store;\n\n // Create store\n store = new Vuex.Store({\n modules: {\n core: {\n state: {\n labgroup:{\n current: {\n id: 1\n }\n }\n }\n }\n }\n });\n\n // Set-up wrapper options\n const wrapperOptions = {\n localVue,\n store,\n mocks: {\n $axios: {\n get: jest.fn(() => Promise.resolve({ data: {} }))\n }\n }\n };\n\n // Prep spies for our component methods we want to validate\n const spycreateBarcodes = jest.spyOn(index.methods, 'createBarcodes');\n const createdHook = jest.spyOn(index, 'created');\n // Mount the component we're testing\n const wrapper = shallowMount(index, wrapperOptions);\n\n test('if barcode logs were retrieved', () => {\n expect(createdHook).toHaveBeenCalled();\n expect(wrapper.vm.barcodeRanges).toHaveLength(11);\n });\n\n});\n```\n\n```text\nglobal.localStorage = {\n state: {\n 'access-token': 'superHashedString'\n },\n setItem (key, item) {\n this.state[key] = item\n },\n getItem (key) { \n return this.state[key]\n }\n}\n```\n\n```text\njest.spyOn(global.localStorage, 'setItem')\njest.spyOn(global.localStorage, 'getItem')\n```\n\n```text\nmocks: {\n $axios: {\n get: jest.fn(() => Promise.resolve({ data: {} }))\n }\n}\n```\n\n```text\nlocalVue.use(axios)\n```\n\n```text\nlocalStorage\n```\n\n```text\nlocalStorage\n```\n\n```text\nlocalVue.use(axios)\n```\n\n```text\n$axios\n```\n\n```text\nconst setItem = jest.spyOn(Storage.prototype, 'setItem')\nconst getItem = jest.spyOn(Storage.prototype, 'getItem')\n\nexpect(setItem).toHaveBeenCalled()\nexpect(getItem).toHaveBeenCalled()\n```\n\n========================================\n\nComments:\n- I had to manually localStorage.setItem('access-token') = 'mytoken' before mounting my component, but your answer lead in me in that direction so thank you. I have another question though, when I set up the $axios mock with \"get: jest.fn(() => Promise.resolve({ data: {} }))\", it always just returns that empty object \"{}\", do I have to hard-code my expected response for every test I mock a GET????\n- Glad my code helped! About axios data: if you are planning to use fetched (in mock) data in further tests then $axios.get should return some data.","metadata":{"transformedAt":"2026-08-18T18:33:07.863Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":261,"estimatedTokens":1824}}388{"id":"stack-60983551","source":"stackoverflow","questionId":60983551,"title":"How to remove Google font Roboto from head in Nuxt/Vuetify?","tags":["fonts","vuetify.js","nuxt.js"],"text":"Title: How to remove Google font Roboto from head in Nuxt/Vuetify?\nTags: fonts, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nBy default Vuetify includes Google font \"Roboto\" in the head of the static generated page from Nuxt. How I can remove this font from the head? Is there an option for this? I would like to save this unnecessary request...\n\n========================================\n\nCode:\n```js\nbuildModules: [\n '@nuxtjs/vuetify'\n],\n```\n\n```js\nvuetify: {\n customVariables: ['~/assets/variables.scss'], // vuetify var styles.\n optionsPath: './vuetify.options.js', // vuetify option like theme.\n defaultAssets: false,\n treeShake: true\n }\n```\n\n========================================\n\nComments:\n- Great! \"defaultAssets: false\" done the thing - thanks for the tip!\n- When I do this, it removes the mdi icons. How can I add them back in?\n- @connorcode , you need to define it as an object: defaultAssets: { font: false, icons: true, }, or add mdi-icons manually vuetify docs explain this well.\n- This removes the menu and expand icons (nav) but maintains the social media icons, very strange\n- @connorcode are you using version v2.0.0-beta.2 of vuetify module? cuz its not stable yet , you must use v1.11 .","metadata":{"transformedAt":"2026-08-18T18:33:07.863Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":33,"estimatedTokens":313}}389{"id":"stack-67354796","source":"stackoverflow","questionId":67354796,"title":"Error: getaddrinfo ENOTFOUND '0' when trying to start nuxt dev server","tags":["vue.js","dns","nuxt.js"],"text":"Title: Error: getaddrinfo ENOTFOUND '0' when trying to start nuxt dev server\nTags: vue.js, dns, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI wanted to start a nuxt dev server with this script in my `package.json` (my goal is to access the page from my mobile phone to test it):\n\n```\n\"dev:host\": \"nuxt --hostname '0' --port 8000\"\n```\n\nI basically copied the line from the nuxt docs (https://nuxtjs.org/docs/2.x/features/configuration#edit-host-and-port), but I get this error when executing the script:\n\n```\nFATAL getaddrinfo ENOTFOUND '0'\n at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:64:26)\n```\n\nThat's weird, because when I edit `nuxt.config.js` and add a server object with the same properties, it works (at least at my pc, i still can't access the page with my phone although its in the same network, but I guess that's a different problem). Has anyone stumbled across this dns.js error as well?\n\n========================================\n\nTop Answer:\nNot sure of the issue here since it's working totally fine on my side.\n\nMaybe try with `0.0.0.0`.\n\nAlso, what is your OS? It's maybe your `@nuxt/cli` version?\n\nHere is my test repo: https://github.com/kissu/so-nuxt-vimeo\n\nMaybe host one on github and it to me, that way I may try and see if it's fine on my side or not (will help debugging if it's Nuxt or system related).\n\nhttps://i.sstatic.net/mqD5T.png\n\n========================================\n\nCode:\n```json\n\"dev:host\": \"nuxt --hostname '0' --port 8000\"\n```\n\n```text\nFATAL getaddrinfo ENOTFOUND '0'\n at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:64:26)\n```\n\n```text\npackage.json\n```\n\n```text\nnuxt.config.js\n```\n\n```json\n\"dev:host\": \"nuxt --hostname 0.0.0.0 --port 80\"\n```\n\n```text\n0.0.0.0\n```\n\n```text\n@nuxt/cli\n```\n\n========================================\n\nComments:\n- @kissu Hey, thank you for your answer. Unfortunately I get the same error with your nuxt app. My version is 2.15.4, too. So I guess the error is system related.\n- a repo for me to test it locally!","metadata":{"transformedAt":"2026-08-18T18:33:07.863Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":72,"estimatedTokens":500}}390{"id":"stack-69114800","source":"stackoverflow","questionId":69114800,"title":"Nuxt3: how to use tailwindcss","tags":["nuxt.js","tailwind-css","unocss"],"text":"Title: Nuxt3: how to use tailwindcss\nTags: nuxt.js, tailwind-css, unocss\nSource: Stack Overflow\n\nQuestion:\nVery first try on Nuxt3 via Nuxt3 Starter\n\nI wonder how can I use tailwindcss in Nuxt3 Starter manually.\n\n(Not via @nuxtjs/tailwindcss , because it's for Nuxt2, and not work with Nuxt3.)\n\nI created a blank Nuxt3 project by\n\n```\nnpx degit \"nuxt/starter#v3\" my-nuxt3-project\n```\n\nthen, I installed the tailwindcss manually\n\n```\nnpm install -D tailwindcss@latest postcss@latest autoprefixer@latest\n```\n\n**nuxt.config.ts**\n\n```\nexport default {\n css: [\n '~/assets/tailwind.css',\n ]\n}\n```\n\n**assets/tailwind.css**\n\n```\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\nbut I can only get the raw code but not the compiled css:\n\nHow can I use tailwindcss in Nuxt3?\n\nAny help is greatly appreciated!\n\nonline mini demo\n\nupdate:\n\n@nuxtjs/tailwindcss is already supported in Nuxt3\n\nbasic example\n\n========================================\n\nTop Answer:\nI made a fully configured nuxt 3 \"starter-kit\", supporting TypeScript and several considered as useful libraries, fully configured and ready to use in real world projects: TypeScript, Tailwind CSS, Sass, Storybook, Vitest & Pinia. I just pushed it yesterday - should be ready to use...\n\nMaybe it will help someone: https://github.com/lazercaveman/nuxt3-starter :)\n\n========================================\n\nCode:\n```bash\nnpx degit \"nuxt/starter#v3\" my-nuxt3-project\n```\n\n```text\nnpm install -D tailwindcss@latest postcss@latest autoprefixer@latest\n```\n\n```text\nexport default {\n css: [\n '~/assets/tailwind.css',\n ]\n}\n```\n\n```css\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\nbuild: {\n postcss: {\n postcssOptions: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n },\n },\n}\n```\n\n```text\ncss: [\"~/assets/css/tailwind.css\"]\n```\n\n```text\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\ncontent: [\n \"./components/**/*.{vue,js}\",\n \"./layouts/**/*.vue\",\n \"./pages/**/*.vue\",\n \"./plugins/**/*.{js,ts}\",\n \"./nuxt.config.{js,ts}\",\n ],\n```\n\n```text\nnpm install -D tailwindcss@latest postcss@latest autoprefixer@latest\n```\n\n```text\nnpx tailwindcss init\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ntailwind.css\n```\n\n```text\ntailwind.config.js\n```\n\n```sh\nyarn run tailwindcss init\n```\n\n```text\ntailwindcss.config.js\n```\n\n```text\ncss: ['~/assets/styles/tailwind.css'],\nbuild: {\n postcss: {\n postcssOptions: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {}\n }\n }\n }\n},\n```\n\n```text\n@import 'tailwindcss/base';\n@import 'tailwindcss/components';\n@import 'tailwindcss/utilities';\n```\n\n```text\nyarn add postcss && tailwindcss\n```\n\n```text\nyarn dev\n```\n\n```text\nyarn add --dev @nuxtjs/tailwindcss\n\n// OR\n\nnpm install --save-dev @nuxtjs/tailwindcss\n```\n\n```js\nexport default defineNuxtConfig({\n modules: ['@nuxtjs/tailwindcss']\n})\n```\n\n```text\ncontent\n```\n\n```text\ntailwind.config.js\n```\n\n```text\ncomponents\n```\n\n```text\npages\n```\n\n```text\nlayouts\n```\n\n========================================\n\nComments:\n- There is probably some configuration to do with postcss too? tailwindcss.com/docs/…\n- @kissu Thanks a lot! I use the default `postcss.config.js`, but I just found it has never been ran.\n- check the official docs of tailwind css tailwindcss.com/docs/guides/nuxtjs\n- Thanks a lot for you answer! This question is asked a month ago when nuxt3 is in private beta, nuxt3 is support tailwindcss now.\n- This should not be accepted answer as it's outdated, Nuxt3 supports TailwindCSS just fine.\n- Actually, technically Tailwind CSS isn't supported in Nuxt 3 - https://modules.nuxtjs.org/?version=3.x, however, WindiCSS is.\n- @23johanningmeierjl, how is it not supported? I'm using it in my Nuxt3 project just fine without any issues whatsoever. You simply do not need a module for Tailwind. It simply needs to be configured in nuxt.config.js in build params.\n- @SamAxe, I answered this months ago when Tailwind 3 was not out yet. The docs were old, and when following the docs on the basis for the installation with Nuxt, it yielded errors. This is because the Nuxt Tailwind module was and still is incompatible with Nuxt 3. You can review the old docs here. I found WindiCSS as the best alternative then, and was my best answer at the time. Also, the alternative method is less-than-preferable because it doesn't work when running 'npm run dev', it only works when building.\n- @23jjl the above answer update is still not accurate, running `nuxi dev` supports hot refresh without a problem and will recompile tailwind on the fly\n- @SamAxe, I tried it yesterday. Tailwind worked when I deployed it, however, not when I ran `nuxi dev`. None of the styling showed up whatsoever. This is because in the `nuxt.config.ts` file, Post CSS is set to run when it “builds”, not when you run it using the 'dev' command. I will say it would work great with CodeSandbox, because it \"builds\" it when it generates the app automatically. As a VS Code (or sometime Gitpod) user, it won't work at all because it doesn't compile Tailwind when running `nuxi dev`. Unless I'm missing something, I'm fairly sure I'm still accurate.\n- @SamAxe, you missed something in your answer. You need to add \"./app.vue/\" under the \"content\" declaration in `tailwind.config.js` as well as a few other things if you want your app to be styled. Wasn't aware of that. I did not add this, when I tried it.\n- @SamAxe, I think I have clarified. I feel that the video gives a better example of how to do it. (Personally, I'm a bit of a visual learner). I also kept the idea of Windi CSS (I have to recommend it) and UnoCSS. The benchmarks I included are also useful. I hope this is better.\n- @23jjl good catch regards the config.js, amended my answer, thanks for pointing that out\n- Not like Tailwind3 is a big deal anyway. You can always ask to support some features ok the Windi project.\n- Especially with this: twitter.com/windi_css/status/…\n- @AndrewP. Interesting, 3-rc3 was not available at the time I wrote this answer, I assume something may have changed the way postcss is configured during build. In theory, above set up relies on Nuxt itself very little so still should work, but I might be wrong.\n- It seems Nuxt v3 rc 13 has changed the nuxtx.config file structure slightly and it's now. postcss -> plugins -> tailwindcss, ... without being wrapped in \"build\" and without \"postcssOptions\"\n- That is not valid anymore since Nuxt 3 stable doesn't support the nuxt 2 syntax anymore - but tailwind did update their. documentation, on how to setup tailwind with nuxt 3: tailwindcss.com/docs/guides/nuxtjs#3\n- how can we modify this config though? tailwind config changes not being respected by nuxt\n- tailwindcss.nuxtjs.org/tailwind/…","metadata":{"transformedAt":"2026-08-18T18:33:07.864Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":241,"estimatedTokens":1745}}391{"id":"stack-63585172","source":"stackoverflow","questionId":63585172,"title":"How to update $auth.user properties in Nuxt.js?","tags":["vue.js","vuex","nuxt.js"],"text":"Title: How to update $auth.user properties in Nuxt.js?\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhen I want to update `$auth.user.balance`:\n\n```\nmethods:{\n test(){\n this.$auth.user.balance = 10;\n }\n}\n```\n\nBut it returns error:\n\n```\nError: [vuex] do not mutate vuex store state outside mutation handlers.\n```\n\nHow can I update these vuex properties in Nuxtjs?\n\n========================================\n\nTop Answer:\nWhen you're using Vuex you should only mutate your state throught your mutations, in your Vuex you should create a mutation like this :\n\n```\nsetBalance(state, payload) {\n auth.user.balance = payload;\n },\n```\n\nand in your component you need to map your new mutation in your `methods`,\n\n```\n...mapMutations('auth', ['setBalance']),\n```\n\ndon't forget to import the mapMutations from vuex\n\n```\nimport { mapMutations } from 'vuex';\n```\n\nand in your component when you want to set a new value to balance you call\n\n```\ntest(){\n let newValue = 10;\n this.setBalance(newValue);\n }\n```\n\nYou can learn more about mutations in Vuex store here in Vuex documentation\n\n========================================\n\nCode:\n```text\nmethods:{\n test(){\n this.$auth.user.balance = 10;\n }\n}\n```\n\n```text\nError: [vuex] do not mutate vuex store state outside mutation handlers.\n```\n\n```text\n$auth.user.balance\n```\n\n```js\nconst userToUpdate = {...this.$auth.user}\nuserToUpdate.balance = 10;\nthis.$auth.setUser(userToUpdate)\n```\n\n```text\n$auth.setUser()\n```\n\n```text\n$auth.setUser()\n```\n\n```text\nsetUser\n```\n\n```text\nsetBalance(state, payload) {\n auth.user.balance = payload;\n },\n```\n\n```text\n...mapMutations('auth', ['setBalance']),\n```\n\n```text\nimport { mapMutations } from 'vuex';\n```\n\n```text\ntest(){\n let newValue = 10;\n this.setBalance(newValue);\n }\n```\n\n```text\nmethods\n```\n\n========================================\n\nComments:\n- In my case, when using this.$auth.user in a computed variable it was not updating the DOM, i've needed to use this.$auth.user directly.","metadata":{"transformedAt":"2026-08-18T18:33:07.864Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":123,"estimatedTokens":503}}392{"id":"stack-57573255","source":"stackoverflow","questionId":57573255,"title":"How to create dynamic nested routes in nuxt.js","tags":["vue.js","nuxt.js"],"text":"Title: How to create dynamic nested routes in nuxt.js\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHow do I use routing and folder structure to pass multiple optional parameters in the URL?\nWhat folder structure should I create to handle such cases where the route is something like\n\n```\nuser/:id/:product\nuser/:id/product/:id\n```\n\n========================================\n\nCode:\n```text\nuser/:id/:product\nuser/:id/product/:id\n```\n\n```text\n// For user/:id/:product\nuser/_id/_product \npages/\n--| user/\n-----| _id/\n--------| index.vue\n--------| _product\n-----------| index.vue\n\n\n// For user/:id/product/:id\npages/\n--| user/\n-----| _id/\n--------| index.vue\n--------| product\n-----------| _id.vue\n```\n\n========================================\n\nComments:\n- I am still learning this, but where is the parent file for the nested children files? Per the Nuxt documentation, there needs to be a .vue file with the same name as the directory holding the children files, e.g. user/_id.vue and user/_id/product.vue","metadata":{"transformedAt":"2026-08-18T18:33:07.864Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":45,"estimatedTokens":254}}393{"id":"stack-75698069","source":"stackoverflow","questionId":75698069,"title":"Disable eslint error with Vuejs and v-html","tags":["vue.js","nuxt.js","eslint"],"text":"Title: Disable eslint error with Vuejs and v-html\nTags: vue.js, nuxt.js, eslint\nSource: Stack Overflow\n\nQuestion:\nI use Nuxt 2 with Vue 2 and vuetify.\n\nMy vscode was updated and I am getting an eslint error with v-html.\n\nThe code is:\n\n```\n\n \n```\n\nand the error is:\n\n```\n[vue/no-v-text-v-html-on-component]\n\nUsing v-html on component may break component's content.\n```\n\nBefore this problem, I used\n`` on top of my code and I had no problem\n\nbut now this is not enough.\n\nI have tried\n\n```\n\n```\n\nbut no look\n\n========================================\n\nTop Answer:\n`` in the line before the component worked for me:\n\n```\n\n \n \n\n```\n\n========================================\n\nCode:\n```text\n<v-list-item-title\n v-html=\"`${parent.genFilteredText(item.nome)}`\"\n >\n </v-list-item-title>\n```\n\n```text\n[vue/no-v-text-v-html-on-component]\n\nUsing v-html on component may break component's content.\n```\n\n```text\n<!--eslint-disable vue/no-v-text-v-html-on-component-->\n```\n\n```text\n<!--eslint-disable vue/no-v-html-->\n```\n\n```text\n<v-list-item-title v-html=\"`${parent.genFilteredText(item.nome)}`>\n\n </v-list-item-title>\n```\n\n```text\n<v-list-item-title>\n <span v-html=\"`${parent.genFilteredText(item.nome)}`\"></span>\n</v-list-item-title>\n\n// OR\n<v-list-item-title>\n <div v-html=\"`${parent.genFilteredText(item.nome)}`\"></div>\n</v-list-item-title>\n\n// OR\n<v-list-item-title>\n <p v-html=\"`${parent.genFilteredText(item.nome)}`\"></p>\n</v-list-item-title>\n```\n\n```html\n<template>\n <!-- eslint-disable-next-line vue/no-v-text-v-html-on-component -->\n <Foo vhtml=\"myHtml\" />\n</template>\n\n<!-- Rest of your Vue SFC -->\n```\n\n```text\n<!-- eslint-disable-next-line vue/no-v-text-v-html-on-component -->\n```\n\n```text\n<!-- eslint-disable-next-line vue/no-v-html -->\n```\n\n========================================\n\nComments:\n- did you relint the file after adding the disable comment? you might also try disabling the rule app-wide in your eslint config. Within `\"rules\": {}` add `\"vue/no-v-text-v-html-on-component\": 0`","metadata":{"transformedAt":"2026-08-18T18:33:07.864Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":116,"estimatedTokens":503}}394{"id":"stack-55199158","source":"stackoverflow","questionId":55199158,"title":"Passing props from layout to component","tags":["vue.js","nuxt.js"],"text":"Title: Passing props from layout to component\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSo I'm fairly new to vue and my googlefu may not be good enough, but what I am trying to do is pass props from layout => global component. Is this something that's possible? I'm currently playing around and have a default layout defined as such\n\nlayouts/default.vue\n\n```\n\n \n \n \n \n\nimport SiteNav from \"../components/SiteNav\"\n\nexport default {\n test: \"corgi\",\n components: {\n SiteNav\n }\n}\n\n```\n\ncomponents/SiteNav.vue\n\n```\n\n \n Click to Sign In\n Click to Second Page\n \n\nexport default {\n props: {\n test: {\n type: String,\n required: false,\n default: \"\"\n }\n },\n created() {\n this.$parent.$emit(\"update:layout\", this.test)\n },\n render() {\n return this.$slots.default[0]\n }\n}\n\n```\n\nI've been able to create multiple pages that all uses this global component but I haven't been able to successfully pass props from the layout to the global component. Is there a way?\n\n========================================\n\nTop Answer:\nSince `` is in default.vue, you could simply listen to the event like this:\n\n```\n\n```\n\nThen you define a `updateLayout` method and its first parameter will be whatever you've emitted from:\n\n```\nthis.$emit('update:layout', this.test);\n```\n\nNote that you must not emit on the $parent object (it makes it harder to track where events come from).\n\n========================================\n\nCode:\n```text\n<template>\n <div>\n <SiteNav/>\n <nuxt class=\"nuxt-container\"/>\n </div>\n</template>\n\n<script>\nimport SiteNav from \"../components/SiteNav\"\n\nexport default {\n test: \"corgi\",\n components: {\n SiteNav\n }\n}\n</script>\n```\n\n```text\n<template>\n <div>\n <nuxt-link to=\"/sign-in\">Click to Sign In</nuxt-link>\n <nuxt-link to=\"/second-page\">Click to Second Page</nuxt-link>\n </div>\n</template>\n<script>\nexport default {\n props: {\n test: {\n type: String,\n required: false,\n default: \"\"\n }\n },\n created() {\n this.$parent.$emit(\"update:layout\", this.test)\n },\n render() {\n return this.$slots.default[0]\n }\n}\n</script>\n```\n\n```text\n//Component.Vue\n\n<template>\n <div>All your lovely stuff</div>\n</template>\n\n<script>\nexport default {\n mounted() {\n this.$nuxt.$emit('test', 'blah');\n }\n}\n</script>\n```\n\n```text\n//default.vue\n\ncreated() {\n this.$nuxt.$on('test', data => {\n console.log(data+' emitted')\n })\n },\n```\n\n```text\nbeforeDestroy() {\n // $off method will turn off the event listner\n this.$nuxt.$off('test');\n },\n```\n\n```text\nmounted()\n```\n\n```text\ncreated()\n```\n\n```text\n<SiteNav @update:layout=\"updateLayout\" />\n```\n\n```text\nthis.$emit('update:layout', this.test);\n```\n\n```text\n<SiteNav/>\n```\n\n```text\nupdateLayout\n```\n\n========================================\n\nComments:\n- So to clarify, the updateLayout method should be located inside of the default.vue for setting the prop and this.$emit is put wherever the prop would be changed?\n- default.vue contains the `updateLayout` since that is where you use the directive `@update:layout=\"updateLayout\"`. When you use `$emit` you allow other components that use your component to listen to that event using the `@event` syntax\n- Right, so I tested that and the method created never seems to be called. \"Property or method \"updateLayout\" is not defined on the instance but referenced during render.\" I tried calling from a few different areas and the method inside of defaultVue never seems to get triggered.\n- you must define your methods in the `methods` key see v1.vuejs.org/guide/events.html\n- Okay, awesome. The component was able to successfully emit the event and the layout received it. Would you happen to know if a page that was using the layout would be able to pass a prop through? I tried using the same $emit statement in a page and passing in a variable from there but that didn't seem to work.\n- Im not sure what you mean there, going from a child to a parent is usually done using the `$emit`. From parent to child you just pass down properties using the `props` key (like ``)\n- Interesting! So the flow of what I want to do is: login-page.vue => sends a piece of information to the component to update. In this example, I see that I can indeed listen to the emitted event in my layout from both the component once it mounts and from login-page where I tested it out. As it is right now, I believe the component won't ever update. Is all I need to do is add the listener to the component and call it from the login-page?\n- Excellent. It's a pretty handy feature.\n- should `beforeDestroy` be in `default.vue` or `Component.Vue` ?\n- @abedelhak.ajbouni, you put beforeDestroy in default.vue. When you turn it on it creates a listener in default.vue, so you are turning it off in the same place you created it.","metadata":{"transformedAt":"2026-08-18T18:33:07.864Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":192,"estimatedTokens":1191}}395{"id":"stack-63172001","source":"stackoverflow","questionId":63172001,"title":"Where do I add this websocket code in the new nuxt.js setup since it does not have server?","tags":["vue.js","websocket","nuxt.js","ws"],"text":"Title: Where do I add this websocket code in the new nuxt.js setup since it does not have server?\nTags: vue.js, websocket, nuxt.js, ws\nSource: Stack Overflow\n\nQuestion:\n- I am using the new version of Nuxt which does not come with a server folder\n\n- In the old version, you had a server folder and an index.js which contained the app\n\n- I want to add the websocket WS library with the new version of NuxtJS\n\nThe library requires an instance of server which you create by calling http.createServer(app) meaning an instance of the running express app. You would use this server instance now to listen to 3000 in the index.js file. Also create a sessionHandler which you obtain by calling session({}) with the express-session library\n\n```\nconst WebSocket = require('ws')\n function websocket({ server, sessionHandler, logger }) {\n // https://github.com/websockets/ws/blob/master/examples/express-session-parse/index.js, if you pass a server instance here 'upgrade' handler will crash\n const wss = new WebSocket.Server({ noServer: true })\n function noop() {}\n function heartbeat() {\n this.isAlive = true\n }\n wss.on('connection', (ws, request, client) => {\n ws.isAlive = true\n ws.on('pong', heartbeat)\n ws.on('message', (msg) => {\n logger.info(`Received message ${msg} from user ${client}`)\n ws.send(true)\n })\n })\n server.on('upgrade', (request, socket, head) => {\n sessionHandler(request, {}, () => {\n logger.info(`${JSON.stringify(request.session)} WEBSOCKET SESSION PARSED`)\n wss.handleUpgrade(request, socket, head, (ws) => {\n wss.emit('connection', ws, request)\n })\n })\n })\n // TODO use a setTimeout here instead of a setInterval\n setInterval(function ping() {\n // wss.clients => Set\n wss.clients.forEach(function each(ws) {\n if (ws.isAlive === false) return ws.terminate()\n ws.isAlive = false\n ws.ping(noop)\n })\n }, 30000)\n return wss\n }\n module.exports = websocket\n```\n\n- Does anyone know how I can make this work on the new Nuxt setup without the server folder\n\n========================================\n\nCode:\n```js\nconst WebSocket = require('ws')\n function websocket({ server, sessionHandler, logger }) {\n // https://github.com/websockets/ws/blob/master/examples/express-session-parse/index.js, if you pass a server instance here 'upgrade' handler will crash\n const wss = new WebSocket.Server({ noServer: true })\n function noop() {}\n function heartbeat() {\n this.isAlive = true\n }\n wss.on('connection', (ws, request, client) => {\n ws.isAlive = true\n ws.on('pong', heartbeat)\n ws.on('message', (msg) => {\n logger.info(`Received message ${msg} from user ${client}`)\n ws.send(true)\n })\n })\n server.on('upgrade', (request, socket, head) => {\n sessionHandler(request, {}, () => {\n logger.info(`${JSON.stringify(request.session)} WEBSOCKET SESSION PARSED`)\n wss.handleUpgrade(request, socket, head, (ws) => {\n wss.emit('connection', ws, request)\n })\n })\n })\n // TODO use a setTimeout here instead of a setInterval\n setInterval(function ping() {\n // wss.clients => Set\n wss.clients.forEach(function each(ws) {\n if (ws.isAlive === false) return ws.terminate()\n ws.isAlive = false\n ws.ping(noop)\n })\n }, 30000)\n return wss\n }\n module.exports = websocket\n```\n\n```js\nconst WebSocket = require('ws')\nconst wss = new WebSocket.Server({ noServer: true })\n\nwss.on('connection', ws => {\n ws.on('message', message => {\n console.log('received: %s', message);\n })\n ws.send('Hello')\n})\n\nexport default function () {\n this.nuxt.hook('listen', server => {\n server.on('upgrade', (request, socket, head) => {\n wss.handleUpgrade(request, socket, head, ws => {\n wss.emit('connection', ws);\n })\n })\n })\n}\n```\n\n```js\nexport default {\n modules: [\n '~/modules/ws'\n ]\n}\n```\n\n```js\nconst websocket = require('./websocket') // this is your file\n\nexport default function () {\n this.nuxt.hook('listen', server => {\n websocket({\n server,\n sessionHandler (request, _, cb) { // example\n cb()\n },\n logger: console // example\n })\n })\n}\n```\n\n```text\nmodules/ws.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nmodules/ws/index.js\n```\n\n```text\nmodules/ws/websocket.js\n```\n\n```text\nmodule.exports\n```\n\n```text\nws.send(true)\n```\n\n```text\nTypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received type boolean (true)\n```\n\n========================================\n\nComments:\n- @tony19 just tested it, while it is true that npx-create-app gives you the option to choose express server, i dont see any server folder inside\n- @tony19 imgur.com/a/h851j59 you can see here that despite doing everything as suggested by you, the server folder is not there\n- I thought I was using the latest version of `create-nuxt-app`, but I was actually using an older cached version that still had the server templates.\n- how would you import the existing function into this file and then export the server.on upgrade part\n- @PirateApp I'm not sure I understand you correctly, I update my answer.\n- ok lets say inside a REST api endpoint i want to send websocket data to all clients, wss.clients.forEach(function each(ws) {ws.send(JSON.stringify({action: 'news/UPDATE_NEWS_WS',data,}))}) how do I access this wss istance inside a controller?\n- @PirateApp I think the easiest way is export the `wss` and then import it in whatever file you use. Example. Or you may use addServerMiddleware (at module) to add custom middleware then pass `wss` via request object. I didn't test these but hope its works.\n- thank you very much @User 28 I was able to get everything working with sessions!\n- Firstly, top notch answer, thanks for this. And then, can this be modified to listen to normal http connections, and if so, how? Or will I have to use server middleware for that?\n- @SeriousLee I'm not sure that would be possible but you might try this `server.on('request', (req, res) => {...})` nodejs.org/dist/latest-v16.x/docs/api/…. However, I would use a serverMiddleware if possible.\n- @User28 thanks for getting back to me, you're right, it doesn't look like it can be extended to handling api requests. Could you perchance advise on how I might connect the two if I go the server middleware route? There's very little on google about any of this. Basically, I'm running a regular Express api server in my server middleware that has a single route on it. When the route gets hit, I want to notify one of the clients subscribed to the wss in the hook. But I can't seem to figure out how to get the hook or wss or any of it accessed in the middleware.\n- @User28 I made a separate post about it, if you'd care to take a look: stackoverflow.com/q/73657483/6048715\n- the hook listen does not work in production","metadata":{"transformedAt":"2026-08-18T18:33:07.864Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":186,"estimatedTokens":1735}}396{"id":"stack-74976115","source":"stackoverflow","questionId":74976115,"title":"Nested pages in Nuxt 3","tags":["javascript","nuxt.js","nuxt3.js"],"text":"Title: Nested pages in Nuxt 3\nTags: javascript, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI have structute like\n\n```\n/pages/\n section/\n index.vue\n out[id].vue\n```\n\nindex.vue has side menu with `id`s. How to render `out[id].vue` inside `index` ?\n\nLike Nuxt nested pages but in Nuxt3.\n\nCan I nest not child page?\n\n========================================\n\nTop Answer:\nIt is possible to display nested routes with ``.\n\nsource\n\nMore about ``: https://nuxt.com/docs/api/components/nuxt-page#nuxtpage\n\n========================================\n\nCode:\n```text\n/pages/\n section/\n index.vue\n out[id].vue\n```\n\n```text\nid\n```\n\n```text\nout[id].vue\n```\n\n```text\nindex\n```\n\n```text\n/pages/\n section.vue\n section/\n index.vue\n out[id].vue\n```\n\n```text\n<template>\n <div>\n <NuxtLayout>\n <NuxtLink to=\"section/\">index</NuxtLink>\n <NuxtLink to=\"section/out1\">out1</NuxtLink>\n <NuxtLink to=\"section/out2\">out2</NuxtLink>\n <NuxtPage />\n </NuxtLayout>\n </div>\n</template>\n```\n\n```text\n<script setup>\n definePageMeta({ layout: false })\n</script>\n```\n\n```text\nsection.vue\n```\n\n```text\n<NuxtPage>\n```\n\n```text\n<NuxtPage>\n```\n\n========================================\n\nComments:\n- Try creating a page `pages/section.vue` instead of `pages/section/index.vue`. And use `` inside it.\n- @Tristan it works. but not as i wanted..\n- It opens new route. I want not nested route. I want to embed page into parent.\n- It doesn't. Check out the linked documentation. It says: \"`NuxtPage` is required to display top-level or nested pages located in the `pages/` directory.\" You can also check out the examples in the documentation @eri.\n- Since I already have NuxtLayout in app.vue, wrapping the section.vue in NuxtLayout gives me a layout nested inside another layout, with everything being rendered twice. If I leave the NuxtLayout off, it breaks. If I remove the NuxtLayout from app.vue, it does not get applied to any normal (non-nested) pages. I have been trying for days but no combination I found works for all cases and I am beginning to suspect this feature is simply broken in Nuxt3... :(\n- I will provide complete example\n- \"... gives me a layout nested inside another layout...\" -- in `section.vue` you need to disable the parent layout with: `definePageMeta({ layout: false })`. Sidenote: The ability to multiply layouts offers some wild possibilities for something creative!\n- @Kalnode in my case i need to save parent layout (menu, navigation)","metadata":{"transformedAt":"2026-08-18T18:33:07.864Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":101,"estimatedTokens":635}}397{"id":"stack-53679843","source":"stackoverflow","questionId":53679843,"title":"How to secure API Key with Nuxt and verify","tags":["vue.js","vuejs2","middleware","nuxt.js","api-key"],"text":"Title: How to secure API Key with Nuxt and verify\nTags: vue.js, vuejs2, middleware, nuxt.js, api-key\nSource: Stack Overflow\n\nQuestion:\nI am using Nuxt (with SSR/ PWA/ Vuejs/ Node.js/ Vuex/ Firestore) and would like to have a general idea or have an example for the following:\n\n- How can I secure an API key. For example to call MailChimp API\n\n- I am not familiar with how a hacker would see this if a poor solution is implemented. How can I verify it is not accessible to them?\n\nI have found a number of \"solutions\" that recommend using environment Variables, but for every solution someone indicates it wont be secure. See:\n\nhttps://github.com/nuxt-community/dotenv-module/issues/7\n\nhttps://github.com/nuxt/nuxt.js/issues/2033 \n\nPerhaps server middleware is the answer? https://blog.lichter.io/posts/sending-emails-through-nuxtjs and https://www.youtube.com/watch?v=j-3RwvWZoaU (@11:30). I just need to add an email to a mail chimp account once entered, seems like a lot of overhead.\n\nAlso I see I store my Firestore api key as an environment variable already. Is this secure? When I open chrome dev tools-> sources-> page-> app.js i can see the api key right there (only tested in dev mode)!\n\n========================================\n\nTop Answer:\nHow can I secure an API key. For example to call MailChimp API\n\nThe cruel truth here is NO... In the client side you cannot secure any kind of secret, at least in a web app.\n\nJust for you to have an idea of the techniques that can be used to protect an API and how they can be bypassed you can read this series of articles. While it is in the context of an Api serving a mobile app, the majority of it also applies for an API serving a web app. You will learn how api-keys, ouath tokens, hmac and certificate pinning can be used and bypassed.\n\nAccess to third part services must be always done in the back-end, never on the client side. With this approach you only have one place to protected, that is under your control. \n\nFor example in your case of accessing the Mailchimp API... If your back-end is the one in charge of doing it in behalf of your web app, then you can put security measures in place to detect and mitigate the usage of Mailchimp by your web app, like a User Behaviour Analytics (UBA) solution, but leaving for the web app the access to the Mailchimp API means that you only know that someone is abusing it when Mailchimp alerts your or you see it in their dashboards. \n\n I am not familiar with how a hacker would see this if a poor solution is implemented. How can I verify it is not accessible to them?\n\nAs you may already know F12 to access the developers tools is one of the ways.\n\nAnother ways id to use the OWASP security tool Zed Attack Proxy (ZAP) , and using their words:\n\n The OWASP Zed Attack Proxy (ZAP) is one of the world’s most popular free security tools and is actively maintained by hundreds of international volunteers*. It can help you automatically find security vulnerabilities in your web applications while you are developing and testing your applications. Its also a great tool for experienced pentesters to use for manual security testing.\n\n========================================\n\nCode:\n```text\nprivateRuntimeConfig\n```\n\n========================================\n\nComments:\n- How does env module help exactly? I assume if I run env's on client I'm right back where I'm currently at. So are you implying its safe to execute standard middleware functions and pull env api_key when this module sets env's to server only?\n- @JavaBeast yes, although middleware will be also executed on client when route changes so you will need to handle this cases\n- Cool I’ll give it a shot tonight. What about #2? Is dev tools-> app.js the only verification I should do? Update answer and I’ll accept when I get it to work later. Thanks!\n- Ended up using server middleware to avoid CORS issues from mailchimp api from client I was experiencing. Used blog.lichter.io/posts/… as a handy example reference for Nuxt API endpoint\n- Can you explain further this case? For example, in order to use the Mailchimp Secret API in order to add subscribers what i need to do?\n- @StefanoFranceschetto i've edited my original post and linked an example function related to your case, let me know if this is helpful\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:07.864Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":59,"estimatedTokens":1132}}398{"id":"stack-64444811","source":"stackoverflow","questionId":64444811,"title":"Nuxtjs Auth module not working in the middleware","tags":["nuxt.js"],"text":"Title: Nuxtjs Auth module not working in the middleware\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHi I found an old question similar to mine with no answer on StackOverFlow : nuxtjs/auth axios not sending cookie\n\nAlso here on GitHub, without a valid solution: https://github.com/nuxt-community/auth-module/issues/478\n\nSo the problem is that if I call `$auth.loggedIn` in any page, it works like a charm but if I do it in my custom authentication middleware (or if I use the default `auth` middleware), it always return `false`.\n\n### my auth configuration in nuxt.config.js\n\n```\nauth: {\n strategies: {\n local: {\n endpoints: {\n login: {\n url: '/rest-auth/login/',\n method: 'post',\n propertyName: 'key',\n },\n logout: { url: '/rest-auth/logout/', method: 'post' },\n user: {\n url: '/rest-auth/user/',\n method: 'get',\n propertyName: false,\n },\n },\n tokenType: 'Token',\n tokenName: 'Authorization',\n },\n redirect: {\n login: '/user_dashboard',\n home: '/',\n },\n },\n },\n```\n\n### my custom auth middleware\n\n```\nexport default async function ({ $auth, redirect }) {\n const user = await $auth.loggedIn\n console.log(user) // As requested, this is my package.json:\n\n```\n{\n \"name\": \"\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint:js\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"lint:style\": \"stylelint **/*.{vue,css} --ignore-path .gitignore\",\n \"lint\": \"npm run lint:js && npm run lint:style\",\n \"test\": \"jest\"\n },\n \"lint-staged\": {\n \"*.{js,vue}\": \"eslint\",\n \"*.{css,vue}\": \"stylelint\"\n },\n \"husky\": {\n \"hooks\": {\n \"commit-msg\": \"commitlint -E HUSKY_GIT_PARAMS\",\n \"pre-commit\": \"lint-staged\"\n }\n },\n \"dependencies\": {\n \"@nuxt/content\": \"^1.9.0\",\n \"@nuxtjs/auth\": \"^4.9.1\",\n \"@nuxtjs/axios\": \"^5.12.2\",\n \"@nuxtjs/pwa\": \"^3.0.2\",\n \"cookie-universal-nuxt\": \"^2.1.4\",\n \"core-js\": \"^3.6.5\",\n \"nuxt\": \"^2.14.7\",\n \"nuxt-buefy\": \"^0.4.3\"\n },\n \"devDependencies\": {\n \"@commitlint/cli\": \"^11.0.0\",\n \"@commitlint/config-conventional\": \"^11.0.0\",\n \"@nuxtjs/eslint-config\": \"^3.1.0\",\n \"@nuxtjs/eslint-module\": \"^3.0.0\",\n \"@nuxtjs/style-resources\": \"^1.0.0\",\n \"@nuxtjs/stylelint-module\": \"^4.0.0\",\n \"@vue/test-utils\": \"^1.1.0\",\n \"babel-core\": \"7.0.0-bridge.0\",\n \"babel-eslint\": \"^10.1.0\",\n \"babel-jest\": \"^26.5.0\",\n \"eslint\": \"^7.10.0\",\n \"eslint-config-prettier\": \"^6.12.0\",\n \"eslint-plugin-nuxt\": \"^1.0.0\",\n \"eslint-plugin-prettier\": \"^3.1.4\",\n \"husky\": \"^4.3.0\",\n \"jest\": \"^26.5.0\",\n \"lint-staged\": \"^10.4.0\",\n \"node-sass\": \"^4.14.1\",\n \"prettier\": \"^2.1.2\",\n \"sass-loader\": \"^10.0.3\",\n \"stylelint\": \"^13.7.2\",\n \"stylelint-config-prettier\": \"^8.0.2\",\n \"stylelint-config-standard\": \"^20.0.0\",\n \"vue-jest\": \"^3.0.4\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nUnfortunately I wasn't able to make `nuxtjs/auth` work in the middleware but I was able to solve the issue by using `cookie-universal-nuxt` in combination with `nuxtjs/auth`:\n\nYou can leave your axios version as it is, no need to downgrade for this solution\n\n- `npm install --save cookie-universal-nuxt`\n\n- add `cookie-universal-nuxt` in your `nuxt.config.js` file:\n\n```\nmodules: [\n // other modules ...\n '@nuxtjs/auth',\n 'cookie-universal-nuxt',\n ],\n```\n\n- create a custom `auth` middleware. I called mine `auth-user` in the middleware folder:\n\n```\nexport default async function ({ app, redirect }) {\n // the following look directly for the cookie created by nuxtjs/auth\n // instead of using $auth.loggedIn\n const user = await app.$cookies.get('auth._token.local')\n if (user) {\n // let the user see the page\n } else {\n // redirect to homepage\n redirect('/')\n }\n}\n```\n\n- then declare your middleware in the root page of your application that you want to be accessible only by authenticated users:\n\n```\n\nexport default {\n middleware: ['auth-user'],\n}\n\n```\n\nIf this doesn't work, check the cookie name where your user credential are saved by opening the developer tools / inspector in the browser.\n\n========================================\n\nCode:\n```js\nauth: {\n strategies: {\n local: {\n endpoints: {\n login: {\n url: '/rest-auth/login/',\n method: 'post',\n propertyName: 'key',\n },\n logout: { url: '/rest-auth/logout/', method: 'post' },\n user: {\n url: '/rest-auth/user/',\n method: 'get',\n propertyName: false,\n },\n },\n tokenType: 'Token',\n tokenName: 'Authorization',\n },\n redirect: {\n login: '/user_dashboard',\n home: '/',\n },\n },\n },\n```\n\n```js\nexport default async function ({ $auth, redirect }) {\n const user = await $auth.loggedIn\n console.log(user) // <-- this always return false for some reason :(\n if (user) {\n // let the user see the page\n } else {\n // redirect to homepage\n redirect('/')\n }\n}\n```\n\n```json\n{\n \"name\": \"<MY_APP_NAME>\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint:js\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"lint:style\": \"stylelint **/*.{vue,css} --ignore-path .gitignore\",\n \"lint\": \"npm run lint:js && npm run lint:style\",\n \"test\": \"jest\"\n },\n \"lint-staged\": {\n \"*.{js,vue}\": \"eslint\",\n \"*.{css,vue}\": \"stylelint\"\n },\n \"husky\": {\n \"hooks\": {\n \"commit-msg\": \"commitlint -E HUSKY_GIT_PARAMS\",\n \"pre-commit\": \"lint-staged\"\n }\n },\n \"dependencies\": {\n \"@nuxt/content\": \"^1.9.0\",\n \"@nuxtjs/auth\": \"^4.9.1\",\n \"@nuxtjs/axios\": \"^5.12.2\",\n \"@nuxtjs/pwa\": \"^3.0.2\",\n \"cookie-universal-nuxt\": \"^2.1.4\",\n \"core-js\": \"^3.6.5\",\n \"nuxt\": \"^2.14.7\",\n \"nuxt-buefy\": \"^0.4.3\"\n },\n \"devDependencies\": {\n \"@commitlint/cli\": \"^11.0.0\",\n \"@commitlint/config-conventional\": \"^11.0.0\",\n \"@nuxtjs/eslint-config\": \"^3.1.0\",\n \"@nuxtjs/eslint-module\": \"^3.0.0\",\n \"@nuxtjs/style-resources\": \"^1.0.0\",\n \"@nuxtjs/stylelint-module\": \"^4.0.0\",\n \"@vue/test-utils\": \"^1.1.0\",\n \"babel-core\": \"7.0.0-bridge.0\",\n \"babel-eslint\": \"^10.1.0\",\n \"babel-jest\": \"^26.5.0\",\n \"eslint\": \"^7.10.0\",\n \"eslint-config-prettier\": \"^6.12.0\",\n \"eslint-plugin-nuxt\": \"^1.0.0\",\n \"eslint-plugin-prettier\": \"^3.1.4\",\n \"husky\": \"^4.3.0\",\n \"jest\": \"^26.5.0\",\n \"lint-staged\": \"^10.4.0\",\n \"node-sass\": \"^4.14.1\",\n \"prettier\": \"^2.1.2\",\n \"sass-loader\": \"^10.0.3\",\n \"stylelint\": \"^13.7.2\",\n \"stylelint-config-prettier\": \"^8.0.2\",\n \"stylelint-config-standard\": \"^20.0.0\",\n \"vue-jest\": \"^3.0.4\"\n }\n}\n```\n\n```text\n$auth.loggedIn\n```\n\n```text\nauth\n```\n\n```text\nfalse\n```\n\n```text\nimport { Context, Middleware } from '@nuxt/types';\nimport { parse as parseCookie } from 'cookie';\nimport jsonwebtoken from 'jsonwebtoken';\nimport { IJwtPayload } from '../../api/_types/types';\n\n/**\n * This middleware is needed when running with SSR\n * it checks if the token in cookie is set and injects it into the nuxtjs/auth module\n * otherwise it will redirect to login\n * @param context\n */\nconst debugAuthMiddleware: Middleware = async (context: Context) => {\n if (process.server && context.req.headers.cookie != null) {\n try {\n const cookies = parseCookie(context.req.headers.cookie);\n const token = cookies['auth._token.local'] || '';\n const tokenWithoutBearer = token.replace('Bearer ', '');\n // console.log('headers.cookie token', token);\n // console.log('debugAuthMiddleware $auth 1', context.$auth.$state);\n if (!token || token.includes('false')) {\n // sometimes it stores 'Bearer false' when it unsets\n return;\n }\n const jwt: IJwtPayload = (jsonwebtoken.decode(tokenWithoutBearer) as unknown) as IJwtPayload;\n // console.log('jwt payload', jwt);\n if (!jwt) {\n return;\n }\n // console.log('set token ✅', jwt);\n await context.$auth.setToken('locale', tokenWithoutBearer);\n await context.$auth.setUser(jwt);\n context.$auth.$state.loggedIn = true;\n } catch (e) {\n console.error('debugAuthMiddleware', e);\n }\n // console.log('debugAuthMiddleware $auth 2', context.$auth.$state);\n }\n};\n\nexport default debugAuthMiddleware;\n```\n\n```text\nrouter: {\n middleware: ['user-agent', 'auth-ssr', 'auth'],\n},\n```\n\n```text\nauth: {\n redirect: {\n logout: '/?signedOut=1',\n home: '/dashboard',\n },\n strategies: {\n local: {\n endpoints: {\n login: { url: '/api/v1/auth/login', method: 'post', propertyName: 'token' },\n logout: { url: '/api/v1/auth/logout', method: 'post' },\n user: { url: '/api/v1/user', method: 'get', propertyName: 'user' },\n },\n autoFetchUser: false, // do not fetch automatically! user object is coming from login api call\n rewriteRedirects: true, // If enabled, user will redirect back to the original guarded route instead of redirect.home.\n fullPathRedirect: true, // If true, use the full route path with query parameters for redirect\n },\n },\n },\n```\n\n```text\nnuxt.config.ts\n```\n\n```js\nmodules: [\n // other modules ...\n '@nuxtjs/auth',\n 'cookie-universal-nuxt',\n ],\n```\n\n```js\nexport default async function ({ app, redirect }) {\n // the following look directly for the cookie created by nuxtjs/auth\n // instead of using $auth.loggedIn\n const user = await app.$cookies.get('auth._token.local')\n if (user) {\n // let the user see the page\n } else {\n // redirect to homepage\n redirect('/')\n }\n}\n```\n\n```html\n<script>\nexport default {\n middleware: ['auth-user'],\n}\n</script>\n```\n\n```text\nnuxtjs/auth\n```\n\n```text\ncookie-universal-nuxt\n```\n\n```text\nnuxtjs/auth\n```\n\n```text\nnpm install --save cookie-universal-nuxt\n```\n\n```text\ncookie-universal-nuxt\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nauth\n```\n\n```text\nauth-user\n```\n\n```py\nfrom rest_framework.authtoken import views\npath('api/login/',views.obtain_auth_token)\n```\n\n```py\nfrom rest_framework.authentication import TokenAuthentication\nclass TokenAuthentication(TokenAuthentication):\n keyword = 'Bearer'\n```\n\n```py\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': [\n 'rest_framework.authentication.BasicAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n 'myapp.authtoken.TokenAuthentication'\n]\n```\n\n```json\nauth: {\n strategies: {\n local: {\n user: {\n property: 'username',\n },\n endpoints: {\n login: { url: 'api/login/', method: 'post' },\n logout: { url: 'rest-auth/logout/', method: 'post' },\n user: { url: 'rest-auth/user/', method: 'get' }\n },\n tokenRequired:true,\n tokenType:'Bearer',\n autoFetchUser: false\n }\n }\n }\n```\n\n```js\nauth: {\n strategies: {\n local: {\n user: {\n property: 'username',\n autoFetch: true\n },\n\n endpoints: {\n\n login: { url: '/rest-auth/login/', method: 'post' },\n logout: { url: '/rest-auth/logout/', method: 'post' },\n user: { url: '/rest-auth/user/', method: 'get' },\n },\n token: {\n property: 'key',\n type: 'Token',\n name: 'Authorization',\n },\n \n }\n }\n }```\n```\n\n```text\nurls.py\n```\n\n```text\nobtain_auth_token\n```\n\n```text\nTokenAuthentication\n```\n\n```text\nBearer\n```\n\n```text\nurls.py\n```\n\n```text\nauthtoken.py\n```\n\n```text\nSettings.py\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- Hi seems I’ve solved the case by downgrade the nuxt/axios module, can you your package.json? Maybe I can have a look on mine and compare it.\n- @nathan1658 sure, see edit on the question\n- @nathan1658 following your suggestion, I found this issue: github.com/nuxt-community/auth-module/issues/853 so I'm trying downgrading axios with: `npm install @nuxtjs/axios@5.12.1`. wish me luck.\n- still not working\n- Hi sorry for late reply, I have the same version with yours. Can you check the secure setting on the cookie i.e. set it to false when debugging on http?\n- This seems a lot of work but probably is a more proper way of solving the issue. good job!\n- Imo this should be implemented directly within nuxtjs/auth to male this work out of the box for SSR. Maybe I have time in the future to propose a PR. Or someone else sees this and implements it ;)\n- Sharing codes and examples would always be helpful.\n- This may be irrelevant in the context of nuxtjs. Your code is Django. I can't quite see the connection of your answer and the question asked","metadata":{"transformedAt":"2026-08-18T18:33:07.864Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":529,"estimatedTokens":3158}}399{"id":"stack-54380719","source":"stackoverflow","questionId":54380719,"title":"Set path to output folder in Nuxt","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Set path to output folder in Nuxt\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nhttps://i.sstatic.net/KM8Lf.png\n\nWorking in windows, I'm able to generate a static site from my nuxt project using\n\n```\n$ npx nuxt generate\n```\n\nI'm interested in setting the output folder for the generated static files. \n\nI'm reading through https://nuxtjs.org/api/configuration-generate which explains that I should be looking at the generate property. However, I don't understand how to modift or access the generate property. How cam I access the generate property?\n\nEDIT; I changed the nuxt.config.js build object to :\n\n```\nbuild: {\npublicPath: 'public/',\n\n/*\n** You can extend webpack config here\n*/\nextend(config, ctx) {\n\n}\n}\n }\n```\n\nThen ran \n\n```\n$ npx nuxt generate\n```\n\nNo public folder is generated\n\n========================================\n\nCode:\n```text\n$ npx nuxt generate\n```\n\n```text\nbuild: {\npublicPath: 'public/',\n\n\n/*\n** You can extend webpack config here\n*/\nextend(config, ctx) {\n\n}\n}\n }\n```\n\n```text\n$ npx nuxt generate\n```\n\n```text\nmodule.exports = {\n mode: 'spa',\n generate: {\n dir: 'my-dist'\n },\n...............\n.............\n}\n```\n\n```text\nbuild: {\n publicPath: 'public/',\n.........\n............\n}\n```\n\n========================================\n\nComments:\n- medium.com/@andrejsabrickis/…\n- kesinlikle doğru -> modules: [ module.exports = { mode: 'spa', generate: { dir: 'dist' } } ],","metadata":{"transformedAt":"2026-08-18T18:33:07.864Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":91,"estimatedTokens":359}}400{"id":"stack-65493627","source":"stackoverflow","questionId":65493627,"title":"Gtag in Nuxt.js","tags":["vue.js","nuxt.js","gtag.js"],"text":"Title: Gtag in Nuxt.js\nTags: vue.js, nuxt.js, gtag.js\nSource: Stack Overflow\n\nQuestion:\nI'm really facing trouble configuring gtag in my nuxt js app.\n\nI this guide:\n\nhttps://www.carlcassar.com/articles/add-google-analytics-to-a-nuxt-js-app/\n\nThis is my plugin :\n\n```\nimport Vue from 'vue';\n import VueGtag from 'vue-gtag';\n \n Vue.use(VueGtag, {\n config: { id: 'G-*********' },\n appName: 'app-name',\n });\n```\n\nAnd this is how i Load it in nuxt.confing.js\n\n```\nplugins: [\n \"@/plugins/aos.client\",\n \"@/plugins/progress-path\",\n \"@/plugins/vue-input-ui\",\n '@plugins/vue-js-modal.js',\n \"@/plugins/paypal\",\n \"@/plugins/autocomplete\",\n \"@/plugins/lazy-load\",\n {\n src: './plugins/gtag.js',\n mode: 'client'\n },\n ],\n```\n\nBut I'm really facing trouble not getting anything to analytics console.\n\nThis is the gtag from google\n\n```\n\n \n \n window.dataLayer = window.dataLayer || [];\n function gtag(){dataLayer.push(arguments);}\n gtag('js', new Date());\n \n gtag('config', 'G-*********');\n \n```\n\nWhere am I wrong?\n\nThanks everyone\n\n========================================\n\nCode:\n```js\nimport Vue from 'vue';\n import VueGtag from 'vue-gtag';\n \n Vue.use(VueGtag, {\n config: { id: 'G-*********' },\n appName: 'app-name',\n });\n```\n\n```js\nplugins: [\n \"@/plugins/aos.client\",\n \"@/plugins/progress-path\",\n \"@/plugins/vue-input-ui\",\n '@plugins/vue-js-modal.js',\n \"@/plugins/paypal\",\n \"@/plugins/autocomplete\",\n \"@/plugins/lazy-load\",\n {\n src: './plugins/gtag.js',\n mode: 'client'\n },\n ],\n```\n\n```html\n<!-- Global site tag (gtag.js) - Google Analytics -->\n <script async src=\"https://www.googletagmanager.com/gtag/js?id=G-*********\"></script>\n <script>\n window.dataLayer = window.dataLayer || [];\n function gtag(){dataLayer.push(arguments);}\n gtag('js', new Date());\n \n gtag('config', 'G-*********');\n </script>\n```\n\n```js\nimport Vue from 'vue';\nimport VueGtag from 'vue-gtag';\n\nexport default ({ app }) => {\n Vue.use(VueGtag, {\n config: { id: 'G-*********' },\n appName: 'app-name',\n }, app.router);\n}\n```\n\n```text\nVue.use\n```\n\n```text\nexport default\n```\n\n========================================\n\nComments:\n- Indeed, it works for me too, thank you so much! But, would anyone be so kind as to explains why wrapping the very code suggested by vue-gtag works? Is it something related to the way nuxt processes its plugins?\n- @MamorukunBE, good question. I wish I could answer, though now I will have to read up on this. My guess would be that the `app.router` needs to be passed as a plugin option.","metadata":{"transformedAt":"2026-08-18T18:33:07.864Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":127,"estimatedTokens":656}}401{"id":"stack-70716659","source":"stackoverflow","questionId":70716659,"title":"Nuxt \"npm run dev\" build loop after setting up Tailwind CSS v3","tags":["nuxt.js","tailwind-css","postcss"],"text":"Title: Nuxt \"npm run dev\" build loop after setting up Tailwind CSS v3\nTags: nuxt.js, tailwind-css, postcss\nSource: Stack Overflow\n\nQuestion:\nI followed these steps from the Tailwind docs to add Tailwind CSS v3 to my Nuxt.js v2.15.8 project. Now, when I save a file while having `npm run dev` running, I get stuck in a rebuilding loop. It keeps building successfully, but then claiming that some random number was just updated so it rebuilds. I have to use Control + C to get it to exit.\n\n```\n↻ Updated components/Comment.vue 21:08:59\n\n✔ Client\n Compiled successfully in 1.86s\n\n✔ Server\n Compiled successfully in 1.49s\n\n↻ Updated 1642194543006 \n\n✔ Client\n Compiled successfully in 1.14s\n\n✔ Server\n Compiled successfully in 1.62s \n\n↻ Updated 1642194545447\n\n✔ Client\n Compiled successfully in 1.13s\n\n✔ Server\n Compiled successfully in 947.08ms\n\n↻ Updated 1642194547991\n\n...\n```\n\nDoes anyone know what might be causing this? The only 2 things I added to \"nuxt.config.js\" are below, directly out of the Tailwind CSS documentation.\n\n```\n// nuxt.config.js\n\nbuildModules: [\n // ...\n '@nuxt/postcss8',\n],\n// ...\nbuild: {\n // ...\n postcss: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n },\n}\n```\n\n```\n// tailwind.config.js\n\nconst defaultTheme = require('tailwindcss/defaultTheme')\n\nmodule.exports = {\n content: [\n './components/**/*.{js,vue,ts}',\n './layouts/**/*.vue',\n './pages/**/*.vue',\n './plugins/**/*.{js,ts}',\n './nuxt.config.{js,ts}',\n ],\n theme: {\n screens: {\n xxs: '360px',\n xs: '480px',\n ...defaultTheme.screens,\n },\n extend: {\n colors: {\n 'blue-100': '#8ac7f9',\n 'blue-150': '#72bbf7',\n 'blue-200': '#5bb0f6',\n 'blue-300': '#43a5f5',\n 'blue-400': '#2c99f3',\n 'blue-500': '#148ef2',\n 'blue-600': '#1280da',\n 'blue-700': '#1072c2',\n 'blue-800': '#0e63a9',\n 'blue-900': '#0c5591',\n },\n },\n },\n plugins: [],\n}\n```\n\n========================================\n\nTop Answer:\nI've solve the problem with the following steps:\n\n- Remove nuxt/tailwind module\n\n- the instructions for Tailwind 3 setup with Nuxt in the official documentation\n\n- Check your buildModules in nuxt.config, **remove '@nuxtjs/eslint-module'** and add '@nuxt/postcss8'\n\n- yarn clean\n\n- yarn install\n\n========================================\n\nCode:\n```text\n↻ Updated components/Comment.vue 21:08:59\n\n✔ Client\n Compiled successfully in 1.86s\n\n✔ Server\n Compiled successfully in 1.49s\n\n↻ Updated 1642194543006 \n\n✔ Client\n Compiled successfully in 1.14s\n\n✔ Server\n Compiled successfully in 1.62s \n\n↻ Updated 1642194545447\n\n✔ Client\n Compiled successfully in 1.13s\n\n✔ Server\n Compiled successfully in 947.08ms\n\n↻ Updated 1642194547991\n\n...\n```\n\n```text\n// nuxt.config.js\n\nbuildModules: [\n // ...\n '@nuxt/postcss8',\n],\n// ...\nbuild: {\n // ...\n postcss: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n },\n}\n```\n\n```text\n// tailwind.config.js\n\nconst defaultTheme = require('tailwindcss/defaultTheme')\n\nmodule.exports = {\n content: [\n './components/**/*.{js,vue,ts}',\n './layouts/**/*.vue',\n './pages/**/*.vue',\n './plugins/**/*.{js,ts}',\n './nuxt.config.{js,ts}',\n ],\n theme: {\n screens: {\n xxs: '360px',\n xs: '480px',\n ...defaultTheme.screens,\n },\n extend: {\n colors: {\n 'blue-100': '#8ac7f9',\n 'blue-150': '#72bbf7',\n 'blue-200': '#5bb0f6',\n 'blue-300': '#43a5f5',\n 'blue-400': '#2c99f3',\n 'blue-500': '#148ef2',\n 'blue-600': '#1280da',\n 'blue-700': '#1072c2',\n 'blue-800': '#0e63a9',\n 'blue-900': '#0c5591',\n },\n },\n },\n plugins: [],\n}\n```\n\n```text\nnpm run dev\n```\n\n```text\nmodule.exports = {\n content: [\n './nuxt.config.{js,ts}',\n ]\n}\n```\n\n```text\nmodule.exports = {\n content: [\n './nuxt.config.js',\n './nuxt.config.ts'\n ]\n}\n```\n\n========================================\n\nComments:\n- What about tailwind config? Have you configured it?\n- @Danila Yes, it is configured. Added it to the bottom of the original question.\n- And you installed `postcss@latest` and `autoprefixer@latest`? **latest** might be the key, because Nuxt uses not latest versions by default. You can also try to move plugins or buildModules around, maybe it should be first or something\n- I tried playing around with removing everything, then just installing \"@nuxt/postcss8\" and I am still seeing the issue, so I don't think it is `@latest` related.\n- Same here, with almost identical configuration.\n- @Wonderman I didn't solve the issue, but but what I did find, is that Tailwind v3 is conflicting with the ESLint module in Nuxt. Are you using the ESLint module? If so, try disabling it and it should build correctly. For the time being, I am just using ESLint via VS Code. Don't need it as a built in build tool.\n- This works, but it would've been useful to explain and state what your findings were rather than just posting simple steps. It seems like there is a conflict between `@nuxtjs/tailwind` and `@nuxtjs/eslint-module`. As it was already stated in the comments, I don't think I need `@nuxtjs/eslint-module`, so I just removed it.\n- You just saved my life! I had first attempts to update whole project with multiple dependecies last month, but literally gave up, bc i was not able to find the source of this evil endless build loop. Today another attempt, and by accident found out it was a tailwind issue. Your answer is first result on my google search. much love!\n- for me is not working :(","metadata":{"transformedAt":"2026-08-18T18:33:07.865Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":234,"estimatedTokens":1385}}402{"id":"stack-46478486","source":"stackoverflow","questionId":46478486,"title":"NuxtJS + Vuex — datas in the store","tags":["javascript","vuejs2","vuex","nuxt.js"],"text":"Title: NuxtJS + Vuex — datas in the store\nTags: javascript, vuejs2, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nUsing NuxtJS (a VueJS framework), I’m trying to get a bunch of datas from a REST API in a layout template (which can’t use the classic fech() or asyncData() methods).\n\nSo I'm using vuex and the nuxtServerInit() action.\nThis way, I should be able to gather all the datas directly during the load of the app, regardless of the current page.\n\nBut I can’t get it to work.\n\nHere’s my map.js file for the store:\n\n\r\n\r\n\n```\nimport axios from 'axios'\r\n\r\nconst api = 'http://rest.api.localhost/spots'\r\n \r\nexport const state = () => ({\r\n\tmarkers: null\r\n})\r\n\r\nexport const mutations = {\r\n\tinit (state) {\r\n axios.get(api)\r\n .then((res) => {\r\n state.markers = res.data\r\n })\r\n\t}\r\n}\r\n\r\nexport const actions = {\r\n\tinit ({ commit }) {\r\n commit('init')\r\n\t}\r\n}\n```\n\n\r\n\r\n\r\n\nAnd the index.js (that can fire the nuxtServerInit()):\n\n\r\n\r\n\n```\nexport const state = () => {}\r\n\r\nexport const mutations = {}\r\n\r\nexport const actions = {\r\n\tnuxtServerInit ({ commit }) {\r\n // ??\r\n console.log('test')\r\n\t}\r\n}\n```\n\n\r\n\r\n\r\n\nBut I can’t get it to work. The doc says:\n\n If you are using the Modules mode of the Vuex store, only the primary module (in store/index.js) will receive this action. You'll need to chain your module actions from there.\n\nBut I don’t know how I shall do this. How do I call an action defined in another module/file?\n\nI tried to copy various example, but never got them to work ; this is the best I could come up with.\n\nWhat did I missed? If needed, here’s the repo and the store folder\n\nThanks!\n\n========================================\n\nCode:\n```js\nimport axios from 'axios'\n\nconst api = 'http://rest.api.localhost/spots'\n \nexport const state = () => ({\n\tmarkers: null\n})\n\nexport const mutations = {\n\tinit (state) {\n\t\taxios.get(api)\n\t\t\t.then((res) => {\n\t\t\t\tstate.markers = res.data\n\t\t\t})\n\t}\n}\n\nexport const actions = {\n\tinit ({ commit }) {\n\t\tcommit('init')\n\t}\n}\n```\n\n```js\nexport const state = () => {}\n\nexport const mutations = {}\n\nexport const actions = {\n\tnuxtServerInit ({ commit }) {\n\t\t// ??\n\t\tconsole.log('test')\n\t}\n}\n```\n\n```text\nimport Vue from 'vue'\nimport Vuex from 'vuex'\nimport auth from './modules/auth'\nimport auth from './modules/base'\n\nVue.use(Vuex)\n\nexport default () => {\n return new Vuex.Store({\n actions: {\n nuxtServerInit ({ commit }, { req }) {\n if (req.session.user && req.session.token) {\n commit('auth/SET_USER', req.session.user)\n commit('auth/SET_TOKEN', req.session.token)\n }\n }\n },\n modules: {\n auth,\n base\n }\n })\n}\n```\n\n```text\nconst state = () => ({\n user: null,\n token: null\n})\n\nconst getters = {\n getToken (state) {\n return state.token\n },\n getUser (state) {\n return state.user\n }\n}\n\nconst mutations = {\n SET_USER (state, user) {\n state.user = user\n },\n SET_TOKEN (state, token) {\n state.token = token\n }\n}\n\nconst actions = {\n async register ({ commit }, { name, slug, email, password }) {\n try {\n const { data } = await this.$axios.post('/users', { name, slug, email, password })\n commit('SET_USER', data)\n } catch (err) {\n commit('base/SET_ERROR', err.response.data.message, { root: true })\n throw err\n }\n },\n /* ... */\n}\n\nexport default {\n namespaced: true,\n state,\n getters,\n mutations,\n actions\n}\n```\n\n```text\nexport const state = () => ({})\n\nexport const actions = {\n async nuxtServerInit ({ commit }, { req }) {\n if (req.session.user && req.session.token) {\n commit('auth/SET_USER', req.session.user)\n commit('auth/SET_TOKEN', req.session.token)\n }\n }\n}\n```\n\n```text\nconst state = () => ({\n user: null,\n token: null\n})\n\nconst getters = {\n getUser (state) {\n return state.user\n },\n getToken (state) {\n return state.token\n }\n}\n\nconst mutations = {\n SET_USER (state, user) {\n state.user = user\n },\n SET_TOKEN (state, token) {\n state.token = token\n }\n}\n\nconst actions = {\n async register ({ commit }, { name, slug, email, password }) {\n try {\n const { data } = await this.$axios.post('/users', { name, slug, email, password })\n commit('SET_USER', data)\n } catch (err) {\n commit('base/SET_ERROR', err.response.data.message, { root: true })\n throw err\n }\n }\n}\n\nexport default {\n state,\n getters,\n mutations,\n actions\n}\n```\n\n```text\ncommit('base/SET_ERROR', err.response.data.message, { root: true })\n```\n\n```text\nnamespaced: true\n```\n\n========================================\n\nComments:\n- it is deprecated in nuxt 2, and will be removed in nuxt 3, what is the new way to implement this?","metadata":{"transformedAt":"2026-08-18T18:33:07.865Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":262,"estimatedTokens":1156}}403{"id":"stack-71919492","source":"stackoverflow","questionId":71919492,"title":"How to use dynamic images in Nuxt?","tags":["javascript","vue.js","nuxt.js"],"text":"Title: How to use dynamic images in Nuxt?\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to display images from an assets folder in a Nuxt but it won't work even if the `src` value in the HTML is correct.\n\nHere is an excerpt of the code.\n\n```\n\n \n \n \n\n```\n\nThe above path is correct as the component is inside a pages folder at the same root level as the assets folder.\n\nI have image filenames in an array like so:\n\n```\ndata() {\n return {\n images: ['image0.jpg', 'image1.jpg'],\n ...\n}\n```\n\nThere is an async function that is making an API call\nto fetch some items. When the API is finished a random image is added to each item.\n\n```\nasync getMovies() {\n const data = axios.get `api_call_here`)\n const result = await data\n result.data.results.forEach((item) => {\n let randomImg = \n this.images[Math.floor(Math.random() * \n this.images.length)]\n item.img = randomImg\n this.items.push(item)\n })\n},\n```\n\nI am sure the path to the images is correct and that they exist in the specified folder. I also know the path works because I can display any single image from the same assets folder inside another component at the same level.\n\nI think I have tried every combination for the interpolation inside the `src` attribute and nothing has worked.\n\nLastly, I can see the correct path in the elements themselves when I inspect them in the developer console. What is even more baffling is the images seem to be taking up the appropriate space on the page but they are empty (blank space).\n\nI have run out of ideas. If anyone can help me figure out what is going wrong I'd be very grateful.\n\n========================================\n\nTop Answer:\nin Nuxt v3, you can use it like so\n\n```\n\nimport img1 from `~/path/to/img1`\n\n \n\n```\n\n========================================\n\nCode:\n```html\n<div v-for=\"(item, index) in items\" :key=\"index\">\n <div class=\"item-img\">\n <img :src=\"`../assets/imgs/${item.img}`\"/>\n </div>\n</div>\n```\n\n```js\ndata() {\n return {\n images: ['image0.jpg', 'image1.jpg'],\n ...\n}\n```\n\n```js\nasync getMovies() {\n const data = axios.get `api_call_here`)\n const result = await data\n result.data.results.forEach((item) => {\n let randomImg = \n this.images[Math.floor(Math.random() * \n this.images.length)]\n item.img = randomImg\n this.items.push(item)\n })\n},\n```\n\n```text\nsrc\n```\n\n```text\nsrc\n```\n\n```html\n<img :src=\"require(`../assets/imgs/${item.img}`)\" />\n```\n\n```html\n<script setup>\nimport img1 from `~/path/to/img1`\n</script>\n\n<template>\n <img :src=\"img1\" />\n</template>\n```\n\n```text\nexport default defineNuxtPlugin(() => {\n return {\n provide: {\n slugify: (text: string) => { \n return `${\n text\n .toLocaleLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, '')\n .replace(/[\\s_-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n }`\n }\n }\n }\n})\n// \"Any String\" will be converted to \"any-string\"\n```\n\n```text\n<script setup lang=\"ts\">\nconst props = defineProps({\n imageSrc: {\n type: String,\n required: true,\n }\n})\n</script>\n\n<template>\n <div\n :class=\"`bg-[url('${props.imageSrc)}')]`\"\n >\n <div>\n</template>\n```\n\n```text\n<template>\n <div>\n <h1>My awesome image.png</h1>\n <ImageComponent\n class=\"w-16 h-16 bg-contain\"\n :image-src=\"`${$slugify('My awesome image.png')}`\"\n />\n </div>\n</template?\n```\n\n```text\nimport img1 from ~/path/to/img1\n```\n\n```text\n:src\n```\n\n```text\n$slugify\n```\n\n```text\npublic\n```\n\n```text\nimport img_1 from '~/assets/fences_1.png';\nimport img_2 from '~/assets/fences_1.png';\n```\n\n```text\n{\n name: \"name\",\n photo_url: img_1,\n link_url: \"/index\",\n },\n```\n\n```text\n:style=\"{ 'background-image': 'url(' + item.photo_url + ')' }\"\n```\n\n```text\nimg_1\n```\n\n```html\n<NuxtImg :src=\"'images/' + yourImage\" />\n```\n\n```text\n<NuxtImg>\n```\n\n```text\n<NuxtImg>\n```\n\n```text\npublic\n```\n\n```text\nimages\n```\n\n```text\n<img :src=\"`/_nuxt/assets/${image}`\"/>\n```\n\n```text\npublic/img/1.png\n```\n\n```text\n<img class=\"img-fluid\" src=\"@/assets/img/1.png\"/>\n```\n\n========================================\n\nComments:\n- have you defined `items` in *data* ?\n- @Saeed yes, `items` is defined on data also. I forgot to mention that the other values of each item in the `v-for` display perfectly fine, so there is no problem there. It is simply that the `img` element is not displaying the images despite the fact that the correct paths are in the HTML.\n- `taking up the appropriate space`, did you check width and height of images? any *overflow hidden* style or something like that?\n- @Saeed there is an overflow hidden on the div wrapping the img tag. The height and width on the img tag itself are 100%. I just tried pasting in a url using the dev console and it immediately showed on the page, so I think the CSS is fine.\n- Does this answer your question? Vue.js dynamic images not working\n- Yep, you're probably looking at the wrong place here. As @Kapcash proposed, a `require` should do the trick when it comes down to dynamic stuff. Here is the part in the documentation related to Nuxt images.\n- due to the nature of the beast, rather than needing to rebuild your app every time you add a new item, look into storing non-design related files and images on the server's filesystem or s3 etc\n- Please note that this solution does not work in Nuxt 3, it will only work in Nuxt 2\n- @Maurice rectification, this only works with Webpack, not with Vite. Nuxt3 can be used with Webpack5.\n- good callout. I guess by default, the Nuxt3 project generator configures new projects with Vite, which is why this option didn't work for me. Also worth noting is that there is an issue open on GH around better handling for this situation: github.com/nuxt/framework/issues/7121\n- I have tried this but not working on nuxt 3 version\n- @KishanBhensadadiya it was stated that it was only for Vue2/Nuxt2 indeed. Updated my answer with a solution for Vue3/Nuxt3.\n- This does not work in nuxt 3, can't find the require() modules. To with dynamic image in your template you need the static URL and nuxt 3 does not serve files in the assets/ directory at a static URL like /assets/my-file.png. If you need a static URL, use the public/ directory.\n- @OlaboyeDavidTobi please read the answer again, there is a `Vue3/Nuxt3` section.\n- Don't know about Vue3 but see nuxt.com/docs/getting-started/assets for Nuxt3\n- @OlaboyeDavidTobi nothing that is not already in my answer above. Using `public` has quite some drawbacks tho (as written above).\n- How can you get this to work with dynamic images in Nuxt 3?\n- Just import all images that you may need dynamically. you may place them in an object or array. If you have a ton of images and is not doable for you, most probably must move your images on a CDN and get full URLs from there. Another option would be to place your images in the `public/` folder. I would also like to know if there's a better way to dynamically import assets in Nuxt 3. Will come up with an update if I find out.\n- I have the same issue on asset and used a public folder for now but it is the recommended way?\n- This won't work once you deploy your application\n- another way and more proper in nuxt is to put your image in public folder, for example un public/img/1.png, then Nuxt will take by default resources from public and you can reference with @/assets","metadata":{"transformedAt":"2026-08-18T18:33:07.865Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":265,"estimatedTokens":1840}}404{"id":"stack-68858098","source":"stackoverflow","questionId":68858098,"title":"How to redirect to an external site with a Nuxt middleware?","tags":["vue.js","http-redirect","nuxt.js","middleware","server-side-rendering"],"text":"Title: How to redirect to an external site with a Nuxt middleware?\nTags: vue.js, http-redirect, nuxt.js, middleware, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nI would like to redirect a certain group of users to another URL (external) before the page is loaded, i.e. with middleware.\n\nSince I use nuxt in ssr-mode and redirect the users in layouts/default via `window.location.replace()`, you see the \"mainsite\" for a second.\n\n========================================\n\nTop Answer:\nYou can use the `navigateTo` method with the `external` options set to `true`, like the following:\n\n```\nreturn navigateTo(EXTERNAL_URL, {\n external: true\n})\n```\n\nReference: https://nuxt.com/docs/api/utils/navigate-to#external-url\n\n========================================\n\nCode:\n```text\nwindow.location.replace()\n```\n\n```js\nexport default ({ redirect }) => {\n if (myCoolCondition === 'cool') {\n redirect('https://www.google.com')\n }\n}\n```\n\n```html\n<script>\nexport default {\n middleware: ['google']\n}\n</script>\n```\n\n```text\nmiddleware/google.js\n```\n\n```js\nreturn navigateTo(EXTERNAL_URL, {\n external: true\n})\n```\n\n```text\nnavigateTo\n```\n\n```text\nexternal\n```\n\n```text\ntrue\n```\n\n========================================\n\nComments:\n- You can add the midleware globally for any route you hit, but you need to add this to nuxt.config file. `js router: { middleware: [ \"google\"], base: `${process.env.ROUTER_BASE}`, }`\n- it's nuxt2 question","metadata":{"transformedAt":"2026-08-18T18:33:07.865Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":72,"estimatedTokens":359}}405{"id":"stack-47864147","source":"stackoverflow","questionId":47864147,"title":"How do I configure dynamic og tags in nuxt.js (vue.js)?","tags":["facebook","vue.js","facebook-opengraph","server-side-rendering","nuxt.js"],"text":"Title: How do I configure dynamic og tags in nuxt.js (vue.js)?\nTags: facebook, vue.js, facebook-opengraph, server-side-rendering, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI started the nuxt app with vue init nuxt / express myprojectstart.\n\nHere is my directory.\n\n```\npage\n|- _project.vue\n|- project\n | - index.vue\n```\n\nThe configuration of _project.vue\n\n```\nexport default {\n head () {\n return {\n title: this.project.title,\n meta: [\n {property: 'fb:app_id', content: '12873892173892'},\n {property: 'og:title', content: this.project.title},\n {property: 'og:image', content: this.project.image},\n ],\n }\n }\n},\nasync asyncData ({app, params, error}) {\n const project = await app. $ axios. $ get (`/ project`)\n return {\n project: project.project,\n }\n }\n}\n```\n\nHowever, if you press the Facebook button, the desired title and image will not appear.\n\nI think this is a server side rendering issue. But I could not solve this problem.\n\nI would appreciate your help.\n\n========================================\n\nTop Answer:\nThis code overwrites the main meta tags in head. So if you need to a single article or single page and need to overwrite the `og` tags this is how it should work.\n\n```\nmeta: [\n {\n 'property': 'og:title',\n 'content': `${this.news.title}`,\n },\n {\n 'property': 'og:description',\n 'content': `${this.project.content}`.replace(/]+(>|$)/g, \"\"),\n },\n {\n 'property': 'og:image',\n 'content': `${this.project.image[0]}`\n }\n ],\n```\n\n========================================\n\nCode:\n```text\npage\n|- _project.vue\n|- project\n | - index.vue\n```\n\n```text\nexport default {\n head () {\n return {\n title: this.project.title,\n meta: [\n {property: 'fb:app_id', content: '12873892173892'},\n {property: 'og:title', content: this.project.title},\n {property: 'og:image', content: this.project.image},\n ],\n }\n }\n},\nasync asyncData ({app, params, error}) {\n const project = await app. $ axios. $ get (`/ project`)\n return {\n project: project.project,\n }\n }\n}\n```\n\n```text\nmeta: [\n { hid: 'fb:app_id', name: 'fb:app_id', content: '12873892173892' },\n { hid: 'og:title', name: 'og:title', content: this.project.title },\n { hid: 'og:image', name: 'og:image', content: this.project.image },\n ],\n```\n\n```text\nmeta: [\n {\n 'property': 'og:title',\n 'content': `${this.news.title}`,\n },\n {\n 'property': 'og:description',\n 'content': `${this.project.content}`.replace(/<\\/?[^>]+(>|$)/g, \"\"),\n },\n {\n 'property': 'og:image',\n 'content': `${this.project.image[0]}`\n }\n ],\n```\n\n```text\nog\n```\n\n```text\nhead() {\n//console.log(this.article.title);\nreturn {\n title: this.article.title,\n meta: [\n {\n hid: \"description\",\n name: \"description\",\n content: this.article.description,\n },\n ],\n};\n```\n\n========================================\n\nComments:\n- Probably this helps: github.com/jvandemo/angular-update-meta/issues/13 or this: stackoverflow.com/questions/17127980/… , Not nuxtjs specific but similar problem.\n- This answer can be improved by explaining what it does and how it solves the issue.\n- @CtrlS This code overwrites the main meta tags in head.So if need to a single article or single page and need to overwrite the og tags this is how it should work.\n- That should be included in your answer! :)\n- this doesn't work, none of the tags work on facebook debugger tool\n- You have unclosed comments in your answer\n- Most websites won't pick the data if it's under the attribute `name=\"\"`. According to the opengraph documentation, you have to use the `property=\"\"` attribute. What you suggested in your answer is unfortunately invalid. To fix this he only needed to add the `hid` attribute.\n- Doesn't work in 2022","metadata":{"transformedAt":"2026-08-18T18:33:07.865Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":155,"estimatedTokens":941}}406{"id":"stack-65017205","source":"stackoverflow","questionId":65017205,"title":"Use Cypress with NuxtJS and wait for server startup before starting e2e tests","tags":["vue.js","cypress","e2e-testing","package.json","nuxt.js"],"text":"Title: Use Cypress with NuxtJS and wait for server startup before starting e2e tests\nTags: vue.js, cypress, e2e-testing, package.json, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI set up a NuxtJS project with Cypress.\nIn my tests, I go to one of the pages of my application, for example the home page (/)\n\n```\ndescribe('Index page', function () {\n it('should show index page of app', function () {\n cy.visit('/')\n cy.get('h1.title').contains('frontend')\n })\n})\n```\n\nSo I need to launch my development server to be able to build my Nuxt application (Vue) and then launch my e2e tests.\n\nThe problem is that when I launch it (which is quite long, at least 15 seconds), it doesn't give me control, the process remains active so I can't launch my yarn command to run the tests.\n\nhttps://i.sstatic.net/Pv4ig.png\n\n```\n\"scripts\": {\n \"dev\": \"nuxt-ts\",\n \"build\": \"nuxt-ts build\",\n \"start\": \"nuxt-ts start\",\n \"generate\": \"nuxt-ts generate\",\n \"lint:js\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"lint:style\": \"stylelint **/*.{vue,css} --ignore-path .gitignore\",\n \"lint\": \"yarn lint:js && yarn lint:style\",\n \"test\": \"jest\",\n \"e2e\": \"cypress open\",\n \"e2e:slient\": \"yarn run dev & cypress run\"\n },\n```\n\nAs a result, I really don't know how to launch my tests once the server is properly launched.\n\nThank you.\n\n========================================\n\nTop Answer:\nUse the `pm2` and `wait-on` packages for a more general solution\n\n```\nyarn pm2 start \"yarn nuxt\"\nyarn wait-on http://localhost:3000\nyarn cypress run\nyarn pm2 kill\n```\n\n`Pm2` allows multiple applications to run on your server. Sending the `yarn nuxt` command to pm2 runs your application in dev mode. `wait-on` waits for a response from localhost to ensure you application is being served before staring tests. You then run cypress as normal. Dont forget to kill pm2 on finish otherwise your application will continue to run.\n\n========================================\n\nCode:\n```text\ndescribe('Index page', function () {\n it('should show index page of app', function () {\n cy.visit('/')\n cy.get('h1.title').contains('frontend')\n })\n})\n```\n\n```json\n\"scripts\": {\n \"dev\": \"nuxt-ts\",\n \"build\": \"nuxt-ts build\",\n \"start\": \"nuxt-ts start\",\n \"generate\": \"nuxt-ts generate\",\n \"lint:js\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"lint:style\": \"stylelint **/*.{vue,css} --ignore-path .gitignore\",\n \"lint\": \"yarn lint:js && yarn lint:style\",\n \"test\": \"jest\",\n \"e2e\": \"cypress open\",\n \"e2e:slient\": \"yarn run dev & cypress run\"\n },\n```\n\n```text\n\"scripts\": {\n \"dev\": \"nuxt-ts\",\n \"build\": \"nuxt-ts build\",\n \"start\": \"nuxt-ts start\",\n \"generate\": \"nuxt-ts generate\",\n \"lint:js\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"lint:style\": \"stylelint **/*.{vue,css} --ignore-path .gitignore\",\n \"lint\": \"yarn lint:js && yarn lint:style\",\n \"test\": \"jest\",\n \"cypress:open\": \"cypress open\",\n \"cypress:run\": \"cypress run\",\n \"e2e\": \"start-server-and-test dev http://localhost:3000 cypress:open\",\n \"pree2e:slient\": \"npm run build\",\n \"e2e:silent\": \"start-server-and-test start http://localhost:3000 cypress:run\"\n },\n \"devDependencies\": {\n .\n .\n .\n \"start-server-and-test\": \"^1.11.5\",\n }\n```\n\n```text\nyarn pm2 start \"yarn nuxt\"\nyarn wait-on http://localhost:3000\nyarn cypress run\nyarn pm2 kill\n```\n\n```text\npm2\n```\n\n```text\nwait-on\n```\n\n```text\nPm2\n```\n\n```text\nyarn nuxt\n```\n\n```text\nwait-on\n```\n\n========================================\n\nComments:\n- I might missed something, but did you try to open a second console to run tests?\n- I can't. Because I'll set up Github Actions in order to start tests automatically, so after the server is started, I've to start tests, but I'm not able to detect when the server is started because the process stay active. And even if I start tests in the same time, if the server take time to boot, I'll have an error :/\n- Can you show the github actions yaml?\n- I don't have set up github actions for the moment. I only want to be able to start server then tests in the same time.","metadata":{"transformedAt":"2026-08-18T18:33:07.865Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":141,"estimatedTokens":1012}}407{"id":"stack-76693564","source":"stackoverflow","questionId":76693564,"title":"How do I disable Nuxt3 default loading indicator?","tags":["javascript","vue.js","nuxt.js","nuxt3.js"],"text":"Title: How do I disable Nuxt3 default loading indicator?\nTags: javascript, vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI have been looking in documentation and googling for a long time and for some reason I can't seem to figure out how to disable the default Nuxt3 loading indicator. Does anyone know how to deal with this?\n\nIt only appears for a split second when I refresh page on the \"/\" path, so the page that displays the index.vue page. Attaching an image for reference.\n\n========================================\n\nTop Answer:\nYou can add your own custom loader by creating an `app-loading.html` in root directory of your application and adding it in the `nuxt.config.ts` file like this `{ spaLoadingTemplate: './app-loading.html' }`\n\nyour `app-loading.html` can look like this\n\n```\n\n \n \n \n Title\n \n .loader{\n position: fixed;\n inset: 0rem;\n display: grid;\n place-items: center;\n background-color: white;\n z-index: 50;\n }\n .loader__img{\n width: 4.5rem;\n animation: bounce 1s linear infinite;\n }\n\n @keyframes bounce {\n 0%, 100% {\n transform: translateY(-25%);\n animation-timing-function: cubic-bezier(0.8, 0, 1, 1);\n }\n 50% {\n transform: translateY(0);\n animation-timing-function: cubic-bezier(0, 0, 0.2, 1);\n }\n }\n \n\n \n \n \n\n```\n\n========================================\n\nCode:\n```text\n{ spaLoadingTemplate: false }\n```\n\n```text\nnuxt.config.ts\n```\n\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"accept-ch\" content=\"DPR\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Title</title>\n <style>\n .loader{\n position: fixed;\n inset: 0rem;\n display: grid;\n place-items: center;\n background-color: white;\n z-index: 50;\n }\n .loader__img{\n width: 4.5rem;\n animation: bounce 1s linear infinite;\n }\n\n @keyframes bounce {\n 0%, 100% {\n transform: translateY(-25%);\n animation-timing-function: cubic-bezier(0.8, 0, 1, 1);\n }\n 50% {\n transform: translateY(0);\n animation-timing-function: cubic-bezier(0, 0, 0.2, 1);\n }\n }\n </style>\n</head>\n<body>\n <div class=\"loader\">\n <img src=\"/loader.png\" class=\"loader__img\"/>\n </div>\n</body>\n</html>\n```\n\n```text\napp-loading.html\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n{ spaLoadingTemplate: './app-loading.html' }\n```\n\n```text\napp-loading.html\n```\n\n========================================\n\nComments:\n- Please provide enough code so others can better understand or reproduce the problem.","metadata":{"transformedAt":"2026-08-18T18:33:07.865Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":127,"estimatedTokens":633}}408{"id":"stack-74678449","source":"stackoverflow","questionId":74678449,"title":"How to use the @nuxtjs/axios module with Nuxt3?","tags":["javascript","vue.js","axios","nuxt.js","nuxt3.js"],"text":"Title: How to use the @nuxtjs/axios module with Nuxt3?\nTags: javascript, vue.js, axios, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI have this code to get API data from https://fakestoreapi.com/products/\n\n```\n\n \n definePageMeta({\n layout: \"products\"\n })\n\nexport default {\n data () {\n return {\n data: '',\n }\n },\n async fetch() {\n const res = await this.$axios.get('https://fakestoreapi.com/products/')\n console.log(res.data)\n },\n}\n\n```\n\nI have installed axios and in `nuxt.config.ts` I have:\n\n```\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n\n app: {\n head: {\n title: 'Nuxt',\n meta: [\n { name: 'description', content: 'Everything about - Nuxt-3'}\n ],\n link: [\n {rel: 'stylesheet', href: 'https://fonts.googleapis.com/icon?family=Material+Icons' }\n ]\n }\n },\n runtimeConfig: {\n currencyKey: process.env.CURRENCY_API_KEY\n },\n modules: [\n \"@nuxtjs/tailwindcss\",\n ],\n buildModules: [\n \"@nuxtjs/axios\"\n ],\n axios: {\n baseURL: '/',\n }\n})\n```\n\nI have the following in my console\n\n is an experimental feature and its API will likely change.\n\nI am not getting API data in the console.\n\n========================================\n\nTop Answer:\nWith nuxtjs3 I prefer to use a composable, it is flexible and self-imported throughout the app.\n\n`composables/useApi.ts`\n\n```\nimport axios from 'axios'\n\nexport const useApi = () => {\n const baseURL = 'https://BASE_URL.com'\n const storeUser = useStoreUser()\n\n return axios.create({\n baseURL,\n headers: {\n Authorization: `Bearer ${storeUser.token}`\n }\n })\n}\n```\n\nNow what I do is simply\n\n```\n\nconst api = useApi()\n\nconst { data } = await api({\n method: 'get',\n url: '/auth/login'\n})\n\n```\n\n========================================\n\nCode:\n```html\n<template>\n<div>\n\n\n</div>\n</template>\n\n\n <script> \n definePageMeta({\n layout: \"products\"\n })\n\nexport default {\n data () {\n return {\n data: '',\n }\n },\n async fetch() {\n const res = await this.$axios.get('https://fakestoreapi.com/products/')\n console.log(res.data)\n },\n}\n</script>\n```\n\n```js\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n\n app: {\n head: {\n title: 'Nuxt',\n meta: [\n { name: 'description', content: 'Everything about - Nuxt-3'}\n ],\n link: [\n {rel: 'stylesheet', href: 'https://fonts.googleapis.com/icon?family=Material+Icons' }\n ]\n }\n },\n runtimeConfig: {\n currencyKey: process.env.CURRENCY_API_KEY\n },\n modules: [\n \"@nuxtjs/tailwindcss\",\n ],\n buildModules: [\n \"@nuxtjs/axios\"\n ],\n axios: {\n baseURL: '/',\n }\n})\n```\n\n```text\nnuxt.config.ts\n```\n\n```js\nexport default defineNuxtConfig({\n app: {\n head: {\n title: 'Nuxt Dojo',\n meta: [\n { name: 'description', content: 'Everything about - Nuxt-3' }\n ],\n link: [\n { rel: 'stylesheet', href: 'https://fonts.googleapis.com/icon?family=Material+Icons' }\n ]\n }\n },\n runtimeConfig: {\n currencyKey: process.env.CURRENCY_API_KEY\n },\n modules: [\n \"@nuxtjs/tailwindcss\"\n ],\n})\n```\n\n```html\n<template>\n <div>\n <p v-for=\"user in users\" :key=\"user.id\">ID: {{ user.id }} 👉 {{ user.name }}</p>\n </div>\n</template>\n\n\n<script>\ndefinePageMeta({\n layout: \"products\"\n})\n\nexport default {\n data () {\n return {\n users: '',\n }\n },\n async mounted() {\n this.users = await $fetch('https://jsonplaceholder.typicode.com/users')\n },\n}\n</script>\n```\n\n```text\n@nuxtjs/axios\n```\n\n```text\nohmyfetch\n```\n\n```text\n$axios\n```\n\n```text\n/pages/products/index.vue\n```\n\n```text\nSuspense\n```\n\n```text\n<Suspense>\n```\n\n```js\nimport axios from 'axios'\n\nexport const useApi = () => {\n const baseURL = 'https://BASE_URL.com'\n const storeUser = useStoreUser()\n\n return axios.create({\n baseURL,\n headers: {\n Authorization: `Bearer ${storeUser.token}`\n }\n })\n}\n```\n\n```js\n<script lang=\"ts\" setup>\nconst api = useApi()\n\nconst { data } = await api({\n method: 'get',\n url: '/auth/login'\n})\n</script>\n```\n\n```text\ncomposables/useApi.ts\n```\n\n========================================\n\nComments:\n- Build Modules are deprecated as far as I know, move it to regular `modules` section. Also, the suspense thing is a warning should not cause any error so far. Set the value to your `data` state and check your Vue devtools to see if something is wrong. Otherwise, please provide a minimal reproducible example or a public Github repo.\n- @kissu github.com/AzizxonZufarov/newsnuxt/blob/main/pages/products/‌​… Please visit github repo\n- That's great. Thanks but one question how can I do : limit the data count, order by desc/asc, sortby date with $fetch? When I use axios it has built-in features, but does $fetch has this kinda features? if yes, please give an example or link for reading. Thanks!\n- @AzizxonZufarov Nuxt3 have plenty of helpers like `useAsyncFetch` with various options that could help you with that (based on `ohmyfetch`). Also, I never saw that `axios` could do such things since it's not its purpose. You can always create a composable with the desired behavior and some `sort/fliter/map/etc` array methods of yours if Nuxt3 doesn't have enough already.\n- You can probably skip `axios` in 2023, Nuxt has better defaults baked-in.\n- It's not better. You can't even change the default base_url\n- @jTiKey You don't have to now with server APIs in Nuxt 3.\n- Does anyone worked with with `withCredentials: true` option in axios? how to use it with fetch? inside options 'credentials: 'include' seems not working","metadata":{"transformedAt":"2026-08-18T18:33:07.865Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":281,"estimatedTokens":1403}}409{"id":"stack-64206283","source":"stackoverflow","questionId":64206283,"title":"How to import the mdi icons module inside nuxt.config.js in Nuxt","tags":["nuxt.js","vuetify.js"],"text":"Title: How to import the mdi icons module inside nuxt.config.js in Nuxt\nTags: nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nI have installed the https://materialdesignicons.com/ with\n\n```\nnpm install @mdi/font\n```\n\n**In nuxt.config.js file, I am not sure how to import the icons module... Please help!**\n\n```\nexport default {\n build: {\n /*\n ** You can extend webpack config here\n */\n\n extend(config, ctx) {}\n },\n buildModules: [\n // Simple usage\n '@nuxtjs/vuetify',\n \n // With options\n // ['@nuxtjs/vuetify', { /* module options */ }]\n ]\n}\n```\n\nHere is an example of a Vuetify tab using a MDI icon.\n\n```\nmdi-message-text\n```\n\n========================================\n\nTop Answer:\nThe solution provided by SMAKSS worked, but i had to configure `defaultAssets: false` in vuetify module configuration to avoid download from CDNs.\n\nhttps://github.com/nuxt-community/vuetify-module#defaultassets\n\n========================================\n\nCode:\n```text\nnpm install @mdi/font\n```\n\n```text\nexport default {\n build: {\n /*\n ** You can extend webpack config here\n */\n\n extend(config, ctx) {}\n },\n buildModules: [\n // Simple usage\n '@nuxtjs/vuetify',\n \n // With options\n // ['@nuxtjs/vuetify', { /* module options */ }]\n ]\n}\n```\n\n```text\n<v-icon large color=\"blue darken-2\">mdi-message-text</v-icon>\n```\n\n```js\nexport default {\n css : [\n '@mdi/font/css/materialdesignicons.min.css'\n ],\n build: {\n /*\n ** You can extend webpack config here\n */\n\n extend(config, ctx) {}\n }\n /* Rest of configs */\n}\n```\n\n```js\nexport default {\n css : [\n '@mdi/font/css/materialdesignicons.min.css'\n ],\n buildModules: [\n '@nuxtjs/vuetify',\n ['@nuxtjs/vuetify', { iconfont: 'mdi' }]\n ]\n /* Rest of configs */\n}\n```\n\n```text\n@mdi/font/css/materialdesignicons.min.css\n```\n\n```text\nnuxt.config.js\n```\n\n```text\niconfont: 'mdi'\n```\n\n```text\ndefaultAssets: false\n```\n\n========================================\n\nComments:\n- This actually made me score worse on lighthouse.. :/ i am trying a way to be better, cause vuetify is just BAD!\n- How would this be done using the 'md' package instead, e.g the custom repo which vuetify docs talk about: github.com/jossef/material-design-icons-iconfont Been trying different solutions but can't seem to get it right","metadata":{"transformedAt":"2026-08-18T18:33:07.865Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":125,"estimatedTokens":588}}410{"id":"stack-63777371","source":"stackoverflow","questionId":63777371,"title":"nuxt on local domain?","tags":["vue.js","nuxt.js"],"text":"Title: nuxt on local domain?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI've setup my .hosts file to:\n127.0.0.1 local.mydomain.dk\n\nAnd then in my nuxt config file i've setup:\n\n```\nserver: {\n port: 3000, // default: 3000\n host: 'local.mydomain.dk' // default: localhost\n},\n```\n\nAnd last but not least, in package.json:\n\n\"dev\": \"nuxt --hostname local.mydomain.dk --port 3000\",\n\nHowever, when running npm run dev, Nuxt still starts up on localhost:3000, and not my custom domain? And if I try going to my custom domain in the browser, I get a message \"Site cannot be reached\"\n\nIs there anything else to setup Nuxt for running on a local domain ?\n\n========================================\n\nTop Answer:\nFirst add the host name in my etc/hosts file:\n\n```\n127.0.0.1 local.mydomain.dk\n```\n\nFor nuxt3 add below config in nuxt.config.ts file:\n\n```\ndevServer: {\n port: 3000, // default: 3000\n host: 'local.mydomain.dk' // default: localhost\n},\n```\n\n========================================\n\nCode:\n```text\nserver: {\n port: 3000, // default: 3000\n host: 'local.mydomain.dk' // default: localhost\n},\n```\n\n```text\nserver: {\n port: 80,\n host: '0.0.0.0',\n}\n```\n\n```text\nserver: {\n port: 3000,\n host: 'http://local.mydomain.dk',\n}\n```\n\n```text\nworker_processes 1;\n\nevents {\n worker_connections 1024;\n}\n\nhttp {\nmap_hash_bucket_size 128;\n\n map $sent_http_content_type $expires {\n \"text/html\" epoch;\n \"text/html; charset=utf-8\" epoch;\n default off;\n } \n\n server {\n listen 80;\n server_name quest.localhost;\n\n gzip on;\n gzip_types text/plain application/xml text/css application/javascript;\n gzip_min_length 1000;\n \n location / {\n expires $expires;\n proxy_redirect off;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_read_timeout 1m;\n proxy_connect_timeout 1m;\n proxy_pass http://localhost:3000; # set the address of the Node.js instance here\n }\n\n}\n```\n\n```text\n127.0.0.1 local.mydomain.dk\n```\n\n```text\ndevServer: {\n port: 3000, // default: 3000\n host: 'local.mydomain.dk' // default: localhost\n},\n```\n\n========================================\n\nComments:\n- I am at the same situation. Did you find anything that helps?\n- How to revert this (trying to troubleshoot SSL by disabling custom domain)? I disabled my custom domain in hosts file, flushed OS dns, and configured Nuxt to *not* use my custom domain. Yet Nuxt is still building links using the custom domain!\n- @MarsAndBack have you tried to clear browser's cached data?\n- Eventually some cache must have been cleared. I reverted commits, re-built everything and in the end there was no more problem. Was really frustrating!","metadata":{"transformedAt":"2026-08-18T18:33:07.865Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":124,"estimatedTokens":756}}411{"id":"stack-57199709","source":"stackoverflow","questionId":57199709,"title":"How to variable with Nuxt.js from layout to pages?","tags":["variables","layout","nuxt.js"],"text":"Title: How to variable with Nuxt.js from layout to pages?\nTags: variables, layout, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI actually work on a project that consists of display data from Jsons on a Nuxt.js website using Vuetify. I have created a selector in my layout to choose which Json the user wants to display. I need to access this variable from all the different pages of my project.\n\nHere is what my `default.vue` looks like :\n\n```\n\n \n\nexport default {\n data() {\n return {\n selected_json: undefined,\n json_list: [\n {text: \"first.json\"},\n {text: \"second.json\"},\n ],\n }\n }\n}\n\n```\n\nThe variable I would like to access from all my different pages is `selected_json`.\n\nI see many things on the internet such as Vuex or a solution that consist to pass the variable with the URL. But I'm kind of newby in web programming (started Vue/Nuxt one week ago) and I don't really understand how to apply this in my project. So if there is a more easy way to do it or a good explaination, I'm interested!\n\nThanks in advance for your help :)\n\n========================================\n\nCode:\n```text\n<template>\n <v-overflow-btn\n :items=\"json_list\"\n label=\"Select an Json to display\"\n v-model=\"selected_json\"\n editable\n mandatory\n item-value=\"text\"\n ></v-overflow-btn>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n selected_json: undefined,\n json_list: [\n {text: \"first.json\"},\n {text: \"second.json\"},\n ],\n }\n }\n}\n</script>\n```\n\n```text\ndefault.vue\n```\n\n```text\nselected_json\n```\n\n```js\n//store/index.js\nexport const state = () => ({\n selected_json: null\n})\n```\n\n```js\n//store/index.js\nexport const mutations = {\n setSelectedJson(state, selectedJson) {\n state.selected_json = selectedJson\n }\n}\n```\n\n```js\n//layouts/default.vue\nexport default {\n watch: {\n selected_json(newValue) {\n this.$store.commit(\"setSelectedJson\", newValue)\n }\n }\n}\n```\n\n```js\n//store/index.js\nexport const getters = {\n getSelectedJson(state) {\n return state.selected_json\n }\n}\n```\n\n```js\nthis.$store.getters[\"getSelectedJson\"]\n```\n\n```text\nindex.js\n```\n\n```text\nstore\n```\n\n```text\nstore\n```\n\n```text\npages, plugins, layouts etc\n```\n\n```text\nindex.js\n```\n\n```text\nstate\n```\n\n```text\ndefault.vue\n```\n\n```text\nmutation\n```\n\n```text\nstate\n```\n\n```text\nindex.js\n```\n\n```text\nsetSelectedJson\n```\n\n```text\nstate\n```\n\n```text\nselected_json\n```\n\n```text\ndefault.vue\n```\n\n```text\nwatcher\n```\n\n```text\nselected_json\n```\n\n```text\nselected_json\n```\n\n```text\ngetter\n```\n\n```text\nselected_json\n```\n\n========================================\n\nComments:\n- Thanks a lot for this complete answer! Unfortunately, I still have an issue with Vuex. The getter works correctly but the setter didn't work at all. I tried a different mix between `newVal` and `newValue` but nothing happens. In the watch event how Nuxt know to pass the new value as the parameter of `selected_json(newValue)`?\n- In the setSelectedJson mutation function I made a mistake and mistyped the name of one variable. Both variables should have the same name and it all should work. I even tested it before posting the answer. Do you get any errors in the console? Also the watch event is directly from Vue.js. You can learn more about watchers on official vue.js docs or here: flaviocopes.com/vue-watchers\n- Ok thanks for the correction :) Here is the error I get in the console : `Property or method \"selected_json\" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.`\n- My bad, I easily fix it. Everything working well now. Thanks for your time!","metadata":{"transformedAt":"2026-08-18T18:33:07.865Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":27,"totalLines":194,"estimatedTokens":924}}412{"id":"stack-46388873","source":"stackoverflow","questionId":46388873,"title":"Vue/ Nuxt - mounted: () => Vs mounted: function()","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: Vue/ Nuxt - mounted: () => Vs mounted: function()\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhy the results are different for using `() =>` and `function()` in `mounted`:\n\n```\nexport default {\n mounted: () => {\n this.socket = 'something'\n console.log('mounted')\n },\n methods: {\n submitMessage() {\n console.log(this.socket) // undefined\n }\n }\n}\n```\n\nUsing `function()`:\n\n```\nexport default {\n mounted: function() {\n this.socket = 'something'\n console.log('mounted')\n },\n methods: {\n submitMessage() {\n console.log(this.socket) // something\n }\n }\n}\n```\n\nAny ideas?\n\n========================================\n\nCode:\n```text\nexport default {\n mounted: () => {\n this.socket = 'something'\n console.log('mounted')\n },\n methods: {\n submitMessage() {\n console.log(this.socket) // undefined\n }\n }\n}\n```\n\n```text\nexport default {\n mounted: function() {\n this.socket = 'something'\n console.log('mounted')\n },\n methods: {\n submitMessage() {\n console.log(this.socket) // something\n }\n }\n}\n```\n\n```text\n() =>\n```\n\n```text\nfunction()\n```\n\n```text\nmounted\n```\n\n```text\nfunction()\n```\n\n```text\nmounted: () => this.socket++\n```\n\n```text\nthis.socket\n```\n\n========================================\n\nComments:\n- This explains why: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…\n- This is good answer. But @laukok you should learn and understand about arrow function and keyword `this` binding concept in JavaScript. It will help you a lot later. `console.log(this)` help me to know what is `this`\n- Thats interesting.","metadata":{"transformedAt":"2026-08-18T18:33:07.865Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":100,"estimatedTokens":396}}413{"id":"stack-69593460","source":"stackoverflow","questionId":69593460,"title":"Markdown styles not getting loaded in Nuxt + Vue project","tags":["vue.js","nuxt.js","markdown","tailwind-css","javascript-marked"],"text":"Title: Markdown styles not getting loaded in Nuxt + Vue project\nTags: vue.js, nuxt.js, markdown, tailwind-css, javascript-marked\nSource: Stack Overflow\n\nQuestion:\nI am working on a Vue + Nuxt + Tailwind project and using the marked library to convert a text into markdown.\n\nThe issue is that some styles like \"Headings\" and \"Link\" are loading properly, while some basic styles like \"bold\", \"italics\" are working fine.\n\nFor example:\n\n- When I use \"*hello* world\", it gets converted to \"*hello* world\".\n\n- When I use \"# hello world\", it does not increase the size of the text.\n\n- When I use \"[google](https://google.com)\", it does create a link, but the link is not blue colored.\n\nNot sure what the issue is here. If any more details are required, please let me know.\n\n========================================\n\nTop Answer:\nIts because of the tailwind.css\nin tailwind, h1 - h6 headers dont work.\n\nOption 1)\nadd this to your `tailwind.config.js`:\n\n```\nmodule.exports = {\n corePlugins: {\n preflight: false,\n },\n....\n}\n```\n\nsource :https://github.com/tailwindlabs/tailwindcss/issues/1460\n\nOption 2)Try adding custom css for `h1`..`h6` in your `css` file.\n\nhttps://www.w3schools.com/tags/tag_hn.asp *copy the styles from here*\n\nSimilarly try add custom css for other issues.\n\n========================================\n\nCode:\n```text\n// tailwind.config.js\nmodule.exports = {\n theme: {\n // ...\n },\n plugins: [\n require('@tailwindcss/typography'),\n // ...\n ],\n}\n```\n\n```text\nnpm install @tailwindcss/typography\n```\n\n```text\nyarn add @tailwindcss/typography\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nprose\n```\n\n```text\n<div class=\"prose\" v-html=\"cleanedMarkdown\"></div>\n```\n\n```js\nmodule.exports = {\n corePlugins: {\n preflight: false,\n },\n....\n}\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nh1\n```\n\n```text\nh6\n```\n\n```text\ncss\n```\n\n========================================\n\nComments:\n- Option 1 wont work because it will remove all the core plugins..\n- If u inspect your markdown output, the link wont be blue because of the same reason..\n- for a `link` `css a:link { color: blue !important; background-color: transparent; text-decoration: none; }`\n- Thanks Kaartik. Adding custom CSS works, but I was wondering if there was a simpler way to do this. For example, lists also don't work here.\n- I was fighting this issue for hours. Thanks for the comment, man. I can add this documentation resources in addition to the github link you provided: tailwindcss.com/docs/typography-plugin\n- Worked for me, thanks. I'm very interested in why the styling does not work out of the box as the docs say, does tailwind do something to the default markdown styling?","metadata":{"transformedAt":"2026-08-18T18:33:07.865Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":115,"estimatedTokens":666}}414{"id":"stack-62874486","source":"stackoverflow","questionId":62874486,"title":"Prevent closing Toast when closing Modal in BootstrapVue","tags":["vue.js","nuxt.js","bootstrap-vue"],"text":"Title: Prevent closing Toast when closing Modal in BootstrapVue\nTags: vue.js, nuxt.js, bootstrap-vue\nSource: Stack Overflow\n\nQuestion:\nI would like to prevent closing Toast when closing Modal in BootstrapVue.\n\nScenario:\n\n- Open the Modal and Toast on the page\n\n- Close the modal\n\n- then Modal and Toast closed at the same time\n\n**Question: how to keep Toast stays**\n\n```\ncreated() {\n this.$bvModal.show('modal-form-id')\n const errorToaster = {\n title: 'Success',\n toaster: 'b-toaster-top-center',\n variant: 'success'\n }\n this.$bvToast.toast('Success', errorToaster)\n },\n methods: {\n closeModal() {\n this.$bvModal.hide('modal-form-id')\n }\n }\n```\n\n========================================\n\nTop Answer:\nIn you `errorToaster` add this `no-auto-hide: true`.\n\nExample:\n\n```\nconst errorToaster = {\n title: 'Success',\n toaster: 'b-toaster-top-center',\n variant: 'success',\n 'no-auto-hide': true,\n}\n```\n\n========================================\n\nCode:\n```text\ncreated() {\n this.$bvModal.show('modal-form-id')\n const errorToaster = {\n title: 'Success',\n toaster: 'b-toaster-top-center',\n variant: 'success'\n }\n this.$bvToast.toast('Success', errorToaster)\n },\n methods: {\n closeModal() {\n this.$bvModal.hide('modal-form-id')\n }\n }\n```\n\n```text\nthis.$root.$bvToast.toast(\"Success\", errorToaster);\n```\n\n```text\nconst errorToaster = {\n title: 'Success',\n toaster: 'b-toaster-top-center',\n variant: 'success',\n autoHideDelay: // default is 5000,\n noAutoHide: true // in order to stay it open forever\n }\n```\n\n```text\nauto-hide-delay\n```\n\n```js\nconst errorToaster = {\n title: 'Success',\n toaster: 'b-toaster-top-center',\n variant: 'success',\n 'no-auto-hide': true,\n}\n```\n\n```text\nerrorToaster\n```\n\n```text\nno-auto-hide: true\n```\n\n========================================\n\nComments:\n- I try with this: const errorToaster = { title: 'Success', toaster: 'b-toaster-top-center', variant: 'success', autoHideDelay: 1000000 } But it still closed with Modal\n- Add this property: `noAutoHide: true`\n- @CHHUMSina did `noAutoHide: true` help you?\n- it's still the same issue. const errorToaster = { title: 'Success', toaster: 'b-toaster-top-center', variant: 'success', autoHideDelay: 10000, noAutoHide: true } this.$bvToast.toast('Success', errorToaster) >>\n- I try with this: const errorToaster = { title: 'Success', toaster: 'b-toaster-top-center', variant: 'success', 'no-auto-hide': true } But it still closed with Modal\n- Works perfectly! Can you explain a bit more why adding $root solves the problem?","metadata":{"transformedAt":"2026-08-18T18:33:07.865Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":114,"estimatedTokens":650}}415{"id":"stack-63436923","source":"stackoverflow","questionId":63436923,"title":"Nuxt.js + Auth ( jwt refresh token )","tags":["javascript","html","node.js","vue.js","nuxt.js"],"text":"Title: Nuxt.js + Auth ( jwt refresh token )\nTags: javascript, html, node.js, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have used Auth library for my Vue/Nuxt project. JWT Authentication works for me just fine, but there is a problem with refresh token.\n\nFirst of all refreshToken cookie is always set to null:\n\nhttps://i.sstatic.net/nRhu7.png\n\nSecondly, when i call this.$auth.refreshTokens() i got an error:\n\nthis.$auth.refreshTokens is not a function\n\nI have been trying for a long time to solve this, but i finally give up :(\n\nYou can see my server side and client side code on my GitHub.\n\nFor a shortcat, below is fragment of nuxt.config.js file:\n\n```\nauth: {\n strategies: {\n local: {\n scheme: 'refresh',\n token: {\n property: 'token',\n maxAge: 30,\n // type: 'Bearer'\n },\n refreshToken: {\n property: 'refreshToken',\n data: 'refreshToken',\n maxAge: 60\n },\n user: {},\n endpoints: {\n login: { url: 'users/login', method: 'post' },\n refresh: { url: 'users/refreshToken', method: 'post' },\n user: { url: 'users/me', method: 'get', propertyName: '' },\n logout: false\n },\n // autoLogout: false\n }\n }\n },\n```\n\nI have already checked if all names in the client config file and server are meet.\nThank you in advance for your help and i am so sorry for mistakes in my English, i did my best...\n\n========================================\n\nTop Answer:\nYou have been looking at DEV docs. The refreshToken will be available from version 5 of nuxt-auth. Try installing dev branch of auth module to have access to refreshToken()\n\nhttps://github.com/nuxt-community/auth-module/issues/761\n\n========================================\n\nCode:\n```text\nauth: {\n strategies: {\n local: {\n scheme: 'refresh',\n token: {\n property: 'token',\n maxAge: 30,\n // type: 'Bearer'\n },\n refreshToken: {\n property: 'refreshToken',\n data: 'refreshToken',\n maxAge: 60\n },\n user: {},\n endpoints: {\n login: { url: 'users/login', method: 'post' },\n refresh: { url: 'users/refreshToken', method: 'post' },\n user: { url: 'users/me', method: 'get', propertyName: '' },\n logout: false\n },\n // autoLogout: false\n }\n }\n },\n```\n\n```text\nconst strategy = 'local'\nconst FALLBACK_INTERVAL = 900 * 1000 * 0.75\n\nasync function refreshTokenF($auth, $axios, refreshToken) {\n try {\n const response = await $axios.post('/refresh')\n let token = 'Bearer ' + response.data.token\n console.log(refreshToken);\n console.log(token);\n $auth.setToken(strategy, token)\n $axios.setToken(token)\n return decodeToken.call(this, token).exp\n } catch (error) {\n $auth.logout()\n throw new Error('Error while refreshing token')\n }\n}\n\nexport default async function ({app}) {\n\n const {$axios, $auth} = app\n\n let token = $auth.getToken(strategy)\n let refreshInterval = FALLBACK_INTERVAL\n if (token) {\n $axios.get('/me').then((resp) => {\n $auth.setUser(resp.data.data)\n }).catch(async () => {\n try {\n await refreshTokenF($auth,$axios,token);\n } catch (e) {\n $auth.logOut();\n }\n })\n }\n\n setInterval(async function () {\n token = $auth.getToken(strategy)\n await refreshTokenF($auth, $axios, token)\n }, refreshInterval)\n\n}\n```\n\n```text\n<?php\n\n\nnamespace App\\Http\\Controllers\\Api\\Auth;\n\n\nuse App\\Http\\Controllers\\Controller;\nuse Illuminate\\Http\\Request;\nuse Mpdf\\Tag\\THead;\nuse Tymon\\JWTAuth\\JWTAuth;\n\nclass RefreshController extends Controller\n{\n\n protected $auth;\n /**\n * Create a new controller instance.\n *\n * @return void\n */\n public function __construct(JWTAuth $auth)\n {\n $this->auth = $auth;\n }\n\n public function refresh(Request $request)\n {\n $this->auth->setRequest($request);\n $arr = $this->auth->getToken();\n $arr = $this->auth->refresh();\n $this->auth->setToken($arr);\n return response()->json([\n 'success' => true,\n 'data' => $request->user(),\n 'token' => $arr\n ], 200); }\n\n}\n```\n\n```text\n/refresh\n```\n\n```text\nrefresh\n```\n\n```text\nstrategies: {\n refresh: {\n scheme: 'refresh',\n token: {\n property: 'access_token',\n maxAge: 1800,\n global: true,\n },\n refreshToken: {\n property: 'refresh_token',\n data: 'refresh_token',\n maxAge: 60 * 60 * 24 * 30,\n },\n user: {\n property: false,\n },\n endpoints: {\n login: {\n url: `${process.env.OAUTH_URL}/oauth/token`,\n method: \"post\",\n propertyName: false\n },\n user: {\n url: `${process.env.OAUTH_URL}/api/user`,\n method: 'get',\n },\n logout: false,\n }\n },\n }\n```\n\n```text\n{\n id: '',\n email: '',\n name: '',\n role: '',\n}\n```\n\n```text\nawait this.$auth.loginWith(\"refresh\", {\n data: {\n grant_type: \"password\",\n client_id: process.env.CLIENT_OAUTH_ID,\n client_secret: process.env.CLIENT_OAUTH_KEY,\n scope: \"*\",\n username: this.credentials.email,\n password: this.credentials.password\n }\n });\n```\n\n```text\nnpm install --save @nuxtjs/auth-next\n```\n\n```text\nproperty: false\n```\n\n```text\nyarn add @nuxt/auth-next\n```\n\n```text\nexport default {\n ...\n modules = [\n ...\n \"@nuxtjs/axios\",\n \"@nuxt/auth-next\"\n ],\n ...\n auth: {\n strategies: {\n local: {\n scheme: 'refresh',\n token: {\n property: 'access',\n maxAge: 300,\n global: true,\n // type: 'Bearer'\n },\n refreshToken: {\n property: 'refresh',\n data: 'refresh',\n maxAge: 60 * 60 * 24\n },\n user: {\n property: 'data',\n // autoFetch: true\n },\n endpoints: {\n login: { url: 'api/token/', method: 'post' },\n refresh: { url: 'api/token/refresh/', method: 'post' },\n user: { url: 'api/current_user/', method: 'get' },\n logout: false\n }\n }\n }\n },\n ...\n```\n\n```text\n< 5\n```\n\n```text\n@nuxt/auth\n```\n\n```text\n@nuxt/auth-next\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n@nuxt/auth\n```\n\n```text\nrefresh\n```\n\n========================================\n\nComments:\n- Any Updates Bro ?\n- Unfortunately not. I guess i need to write refresh token mechanism by my own. I am currently working at the other parts of my application.\n- You have been looking at DEV docs. The refreshToken will be available from version 5 of nuxt-auth. Try installing dev branch of auth module to have access to refreshToken()\n- is this still dev documentation? I'm looking at auth.nuxtjs.org/schemes/refresh which seems official and I stull have the same problems as OP\n- I wonder how I could do this with CI4 and php-jwt library :')\n- Oh also, how do you make a request to `/refresh` endpoint while the jwt-auth (php) module require the token must not expired yet?\n- saved my day, thank you! works with @nuxt/auth-next\n- thanks a lot! it wasn't clear in the docs around the web we had to use @nuxt/auth-next for supporting refresh tokens\n- You should explain why it works or what part makes it work. And one thing, it looks like you are sending the client and secret from the client side, that an easy way to abuse your authentication system.","metadata":{"transformedAt":"2026-08-18T18:33:07.866Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":327,"estimatedTokens":2016}}416{"id":"stack-63865836","source":"stackoverflow","questionId":63865836,"title":"Laravel Sanctum + Nuxt JS I cannot pass CORS","tags":["laravel","nuxt.js"],"text":"Title: Laravel Sanctum + Nuxt JS I cannot pass CORS\nTags: laravel, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nBefore start, I'd like to say that I searched and tried many approaches and none of them seem to work properly. I also created a fresh Laravel installation but still, no success.\n\nThe problem is CORS, I get blocked by CORS always.\n\n- The setup uses `Laravel Valet`.\n\n- The Laravel Application runs at `https://sanctum.test`\n\n- The NuxtJs Application runs at `https://nuxt.sanctum.test`\n\nIt's a fresh installation.\n\nMy `.env` file has the required settings:\n\n```\nSESSION_DOMAIN=.sanctum.test \nSANCTUM_STATEFUL_DOMAINS=sanctum.test,nuxt.sanctum.test\n```\n\nMy `cors.php` has the required settings:\n\n```\n...\n 'supports_credentials' => true,\n...\n```\n\nMy `Http/Kernel.php`\n\n```\n...\n 'api' => [\n EnsureFrontendRequestsAreStateful::class,\n 'throttle:api',\n \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\n ],\n ];\n```\n\nMy NuxtJs App runs on http://localhost:3000 and I have a Laravel Valet reverse proxy so I can access it from `https://nuxt.sanctum.test` and I can confirm that's working as expected.\n\nHere's my `nuxt.config.js`:\n\n```\nexport default {\n ssr: false,\n\n target: 'server',\n\n head: {\n title: process.env.npm_package_name || '',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n {\n hid: 'description',\n name: 'description',\n content: process.env.npm_package_description || '',\n },\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],\n },\n\n css: [],\n\n plugins: [],\n\n components: true,\n\n buildModules: ['@nuxtjs/eslint-module', '@nuxtjs/tailwindcss'],\n\n modules: [\n '@nuxtjs/axios',\n '@nuxtjs/auth-next',\n '@nuxtjs/pwa',\n '@nuxtjs/dotenv',\n ],\n\n auth: {\n strategies: {\n laravelSanctum: {\n provider: 'laravel/sanctum',\n url: 'https://sanctum.test',\n },\n cookie: {\n cookie: {\n name: 'XSRF-TOKEN',\n },\n },\n },\n },\n\n router: {\n middleware: ['auth'],\n },\n\n axios: {\n proxy: true,\n credentials: true,\n },\n proxy: {\n '/laravel': {\n target: 'https://sanctum.test',\n pathRewrite: { '^/laravel': '/' },\n },\n },\n\n build: {},\n}\n```\n\nNow, no matter what I do, I always get the same error from the Laravel Application:\n\n```\nAccess to XMLHttpRequest at 'https://sanctum.test/sanctum/csrf-cookie' from origin 'https://nuxt.sanctum.test.test' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.\n```\n\nAs you can see above, the request is being made from the subdomain to the main domain. And as I showed above, the `SANCTUM_STATEFUL_DOMAINS` is correct.\n\n========================================\n\nTop Answer:\nIn my case I missed to add `SANCTUM_STATEFUL_DOMAINS` in the `.env` file of Laravel app as below.\n\n`SANCTUM_STATEFUL_DOMAINS=http://localhost:3000`\n\nIf you go to config/sanctum.php you will see a variable `SANCTUM_STATEFUL_DOMAINS`\n\n========================================\n\nCode:\n```text\nSESSION_DOMAIN=.sanctum.test \nSANCTUM_STATEFUL_DOMAINS=sanctum.test,nuxt.sanctum.test\n```\n\n```php\n...\n 'supports_credentials' => true,\n...\n```\n\n```php\n...\n 'api' => [\n EnsureFrontendRequestsAreStateful::class,\n 'throttle:api',\n \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\n ],\n ];\n```\n\n```js\nexport default {\n ssr: false,\n\n target: 'server',\n\n head: {\n title: process.env.npm_package_name || '',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n {\n hid: 'description',\n name: 'description',\n content: process.env.npm_package_description || '',\n },\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],\n },\n\n css: [],\n\n plugins: [],\n\n components: true,\n\n buildModules: ['@nuxtjs/eslint-module', '@nuxtjs/tailwindcss'],\n\n modules: [\n '@nuxtjs/axios',\n '@nuxtjs/auth-next',\n '@nuxtjs/pwa',\n '@nuxtjs/dotenv',\n ],\n\n auth: {\n strategies: {\n laravelSanctum: {\n provider: 'laravel/sanctum',\n url: 'https://sanctum.test',\n },\n cookie: {\n cookie: {\n name: 'XSRF-TOKEN',\n },\n },\n },\n },\n\n router: {\n middleware: ['auth'],\n },\n\n axios: {\n proxy: true,\n credentials: true,\n },\n proxy: {\n '/laravel': {\n target: 'https://sanctum.test',\n pathRewrite: { '^/laravel': '/' },\n },\n },\n\n build: {},\n}\n```\n\n```text\nAccess to XMLHttpRequest at 'https://sanctum.test/sanctum/csrf-cookie' from origin 'https://nuxt.sanctum.test.test' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.\n```\n\n```text\nLaravel Valet\n```\n\n```text\nhttps://sanctum.test\n```\n\n```text\nhttps://nuxt.sanctum.test\n```\n\n```text\n.env\n```\n\n```text\ncors.php\n```\n\n```text\nHttp/Kernel.php\n```\n\n```text\nhttps://nuxt.sanctum.test\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nSANCTUM_STATEFUL_DOMAINS\n```\n\n```php\n<?php\n\nreturn [\n 'paths' => ['api/*', 'sanctum/*', 'login', 'logout'],\n\n 'allowed_methods' => ['*'],\n\n 'allowed_origins' => ['*'],\n\n 'allowed_origins_patterns' => [],\n\n 'allowed_headers' => ['*'],\n\n 'exposed_headers' => [],\n\n 'max_age' => 0,\n\n 'supports_credentials' => true,\n];\n```\n\n```text\nconfig/cors.php\n```\n\n```text\nSANCTUM_STATEFUL_DOMAINS\n```\n\n```text\n.env\n```\n\n```text\nSANCTUM_STATEFUL_DOMAINS=http://localhost:3000\n```\n\n```text\nSANCTUM_STATEFUL_DOMAINS\n```\n\n========================================\n\nComments:\n- Perhaps related to this issue: github.com/fruitcake/laravel-cors/issues/421\n- I found the problem, please check the answer below.","metadata":{"transformedAt":"2026-08-18T18:33:07.866Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":312,"estimatedTokens":1440}}417{"id":"stack-53343151","source":"stackoverflow","questionId":53343151,"title":"How to redirect from /pages to layouts/error.vue?","tags":["javascript","vue.js","nuxt.js"],"text":"Title: How to redirect from /pages to layouts/error.vue?\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have created a error.vue file within the layouts folder which should show the UI for a 400, 404, 410 and 500 error. But, it is not showing the ones I created, it is still showing the default NuxtServerError page.\n\nSo, my question is how can I show my created UI within a page.\n\nBelow is the code that I am using within the layouts/error.vue\n\nHTML:\n\n```\n\n \n \n \n \n\n### Sorry, the page you were looking for doesn't exist.\n\n You can return to our home page or contact us if you can't find what you are looking for.\n\n \n \n \n\n \n \n \n\n### Sorry, the page you are looking for doesn't exist anymore.\n\n You can return to our home page or contact us if you can't find what you are looking for.\n\n \n \n \n\n \n \n \n\n### Sorry, the page you are looking for has been deleted.\n\n You can return to our home page or contact us if you can't find what you are looking for.\n\n \n \n \n\n \n \n \n\n### Sorry, the page you were looking for doesn't exist.\n\n You can return to our home page or contact us if you can't find what you are looking for.\n\n \n \n \n \n\n```\n\nJavascript:\n\n```\n\nexport default {\n head() {\n return {\n title: 'Lost?'\n }\n },\n props: ['error'],\n layout: 'error'\n}\n\n```\n\nCSS:\n\n```\n\n.error-container {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100%;\n}\n\n.error-content {\n width: 90%;\n max-width: 800px;\n margin: auto;\n display: grid;\n grid-template: auto / auto 200px;\n grid-column-gap: 10px;\n text-align: center;\n}\n\n.error-content > div {\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n}\n\n.error-content > div > h1 {\n font-size: 30px;\n margin: 0;\n}\n\n.error-content > img {\n width: 200px;\n}\n\na {\n text-decoration: unset;\n color: var(--color-tpBlue);\n}\n\n```\n\nMany thanks in advance!\n\n========================================\n\nTop Answer:\nAs a complement to @aBiscuit answer:\n\nFor the ones who want to redirect to the error page in another context than `asyncData` in your component, you can access the `error` function in `this.$nuxt.error`.\n\n========================================\n\nCode:\n```text\n<template>\n <div class=\"error-container\">\n <div class=\"error-content\" v-if=\"error.statusCode === 404\">\n <div>\n <h1>Sorry, the page you were looking for doesn't exist.</h1>\n <p>You can return to our <nuxt-link to=\"/\">home page</nuxt-link> or <a href=\"mailto:contact@web.co\">contact</a> us if you can't find what you are looking for.</p>\n </div>\n <img src=\"~/assets/Images/404.png\">\n </div>\n\n <div class=\"error-content\" v-if=\"error.statusCode === 400\">\n <div>\n <h1>Sorry, the page you are looking for doesn't exist anymore.</h1>\n <p>You can return to our <nuxt-link to=\"/\">home page</nuxt-link> or <a href=\"mailto:contact@web.co\">contact</a> us if you can't find what you are looking for.</p>\n </div>\n <img src=\"~/assets/Images/404.png\">\n </div>\n\n <div class=\"error-content\" v-if=\"error.statusCode === 410\">\n <div>\n <h1>Sorry, the page you are looking for has been deleted.</h1>\n <p>You can return to our <nuxt-link to=\"/\">home page</nuxt-link> or <a href=\"mailto:contact@web.co\">contact</a> us if you can't find what you are looking for.</p>\n </div>\n <img src=\"~/assets/Images/404.png\">\n </div>\n\n <div class=\"error-content\" v-if=\"error.statusCode === 500\">\n <div>\n <h1>Sorry, the page you were looking for doesn't exist.</h1>\n <p>You can return to our <nuxt-link to=\"/\">home page</nuxt-link> or <a href=\"mailto:contact@web.co\">contact</a> us if you can't find what you are looking for.</p>\n </div>\n <img src=\"~/assets/Images/404.png\">\n </div>\n </div> \n</template>\n```\n\n```text\n<script>\nexport default {\n head() {\n return {\n title: 'Lost?'\n }\n },\n props: ['error'],\n layout: 'error'\n}\n</script>\n```\n\n```text\n<style scoped>\n.error-container {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100%;\n}\n\n.error-content {\n width: 90%;\n max-width: 800px;\n margin: auto;\n display: grid;\n grid-template: auto / auto 200px;\n grid-column-gap: 10px;\n text-align: center;\n}\n\n.error-content > div {\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n}\n\n.error-content > div > h1 {\n font-size: 30px;\n margin: 0;\n}\n\n.error-content > img {\n width: 200px;\n}\n\na {\n text-decoration: unset;\n color: var(--color-tpBlue);\n}\n</style>\n```\n\n```text\nexport default {\n async asyncData ({ params, error }) {\n try {\n const { data } = await axios.get(`https://my-api/posts/${params.id}`)\n return { title: data.title }\n } catch (e) {\n error({ statusCode: 404, message: 'Post not found' })\n }\n }\n}\n```\n\n```text\nerror\n```\n\n```text\nerror\n```\n\n```text\nstatusCode\n```\n\n```text\nmessage\n```\n\n```text\nlayout/error.vue\n```\n\n```text\nstatusCode\n```\n\n```text\nasyncData\n```\n\n```text\nerror\n```\n\n```text\nthis.$nuxt.error\n```\n\n========================================\n\nComments:\n- Thank you for that, it has helped. But, I have another question, how can I place more than one error message statusCode within the catch? Many thanks!\n- One option is to check status code of error response from axios and call `error` method with appropriate props. Another is to create a helper function that will return valid props depending on error response (for example, with `switch` statement check).","metadata":{"transformedAt":"2026-08-18T18:33:07.866Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":287,"estimatedTokens":1369}}418{"id":"stack-57559472","source":"stackoverflow","questionId":57559472,"title":"Is it possible to variable between SASS and Javascript in Vuex(Nuxt)?","tags":["sass","vuejs2","vuex","nuxt.js"],"text":"Title: Is it possible to variable between SASS and Javascript in Vuex(Nuxt)?\nTags: sass, vuejs2, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nAs in question. I use Vue, Vuex(Nuxt) and we also all mixins and sass variables using:\n@nuxtjs/style-resources\": \"^1.0.0\"\n\nWhich is newer version of \"nuxt-sass-resources-loader\": \"^2.0.5\"\n\nI know that there i spossibility with Webpack such as here\nSo my question is - is it posiibile to do it in similar way and how to configure it? What should I have installed and how can I add it to my nuxt.config.js?\n\nEDIT:\nI also found that article but for me it is not working.\n\n========================================\n\nCode:\n```text\n// in assets/scss/variables.scss\n\n$white-color: #fcf5ed;\n\n// the :export directive is the magic sauce for webpack\n:export {\n whitecolor: #{$white-color};\n}\n```\n\n```text\n// in store.js\n\nimport Styles from '~/assets/scss/variables.scss'\n\nexport const state = () => ({\n styles: {...Styles}\n})\n```\n\n```text\n// in component\n...\ncomputed: {\n styles() {\n return this.$store.state.styles;\n }\n}\n```\n\n```text\n// in assets/scss/variables.scss\n\n$white-color: #fcf5ed;\n\n:root {\n --whitecolor: #{$white-color};\n}\n```\n\n```text\n// in component\n...\nmounted() {\n this.$el.style.color = 'var(--whitecolor)';\n}\n\n<style>\n.component {\n color: var(--whitecolor);\n}\n</style>\n```\n\n========================================\n\nComments:\n- vue-loader.vuejs.org/guide/css-modules.html#usage\n- @Aldarund I don't want to modularize my css. Sometimes we use external library and we need to add some styles as js parameters. That's why I want to sass variable with js.\n- so the way to use css vars in js is to use css modules. And your article that u linked is for react. And its still use css modules in the end\n- I'm also interested by this question. The way I see is to hook on nuxt build and write json files with all sass variables. I'm currently trying to do that but missing a way to get all sass variables... I'm struggle with webpack :/\n- I am looking for better approach. I have all mixins, style shared across components and I just want to have access to variables not only inside style but also in components script section so I can even style thing inline with sass variables. So I believe it is more like Webpack configuration but I don't know for sure and how can I achieve this. @ManUtopiK please add +1 for better SEO\n- Thanks for editing and sharing article you found. It's working for me!\n- A little update to the CSS trick, in the `:root` body, `--whitecolor: $white-color;` should be changed to `--whitecolor: #{$white-color};` Source: sass-lang.com/documentation/breaking-changes/css-vars","metadata":{"transformedAt":"2026-08-18T18:33:07.866Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":84,"estimatedTokens":664}}419{"id":"stack-71806035","source":"stackoverflow","questionId":71806035,"title":"Is using nuxt.js components auto import bad for performance?","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: Is using nuxt.js components auto import bad for performance?\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt.js v2 for my project. Right now, I've enabled nuxt.js auto import for components by setting `components: true` in my `nuxt.config.js` file. I'm wondering if using components auto import has any negative effect on performance of my site in production?\n\nShould I import components manually like what you do in vue.js?\n\n========================================\n\nCode:\n```text\ncomponents: true\n```\n\n```text\nnuxt.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.866Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":19,"estimatedTokens":142}}420{"id":"stack-52613136","source":"stackoverflow","questionId":52613136,"title":"How can I transpile a dependency in node_modules with Nuxt 2?","tags":["javascript","vue.js","babeljs","nuxt.js","nuxt-edge"],"text":"Title: How can I transpile a dependency in node_modules with Nuxt 2?\nTags: javascript, vue.js, babeljs, nuxt.js, nuxt-edge\nSource: Stack Overflow\n\nQuestion:\nI have read of issues with transpiling `node_modules` with Nuxt, but the new Nuxt 2 is said to have solved this with a `transpile` option in the `nuxt.config.js` file.\n\nhttps://nuxtjs.org/api/configuration-build/#transpile\n\nHere is what I have:\n\n```\nexport default {\n router: {\n base: '/',\n },\n build: {\n transpile: [\n 'choices.js',\n 'lazysizes',\n 'swiper',\n 'vee-validate'\n ],\n extractCSS: true\n },\n srcDir: 'src/',\n performance: {\n gzip: true\n },\n render: {\n compressor: {\n threshold: 100\n }\n },\n dev: false\n}\n```\n\nI removed a few things that are unrelated to make it easier to read.\n\nWhen I run `npm run build` (`nuxt build`) the compiled JS files contain references to es6 and es7 code such as `const` and `let` etc when it should be `var`.\n\nI have isolated this issue to be coming from **Swiper**. It appears to internally depend on something called Dom7 that seems to be causing the problem.\n\nI am wanting to compile these `node_modules` dependencies to es5 if possible. I'm not sure my current setup is actually doing anything at all in that regard.\n\nI believe Nuxt uses `vue-app` for Babel, but I even tried the following to no success:\n\n```\nbabel: {\n presets: [\n '@babel/preset-env'\n ],\n plugins: [\n '@babel/plugin-syntax-dynamic-import'\n ]\n}\n```\n\nNot much joy there either. Nothing appears differently in the final build.\n\nI am using Nuxt `2.1.0`\n\nAny help appreciated. Thanks!\n\n========================================\n\nTop Answer:\nI have the exact same issue.\n\nThe vendor option under build is deprecated, so it's simply ignored I believe from what I read here https://medium.com/nuxt/nuxt-2-is-coming-oh-yeah-212c1a9e1a67#a688\n\nI managed to isolate my case to the \"swiper\" library. If I remove that from my project, all references to `let`, `const` or `class` are gone. I've tried the transpile option too, but it does not seem to have any effect.\n\nWill you try to exclude swiper from your project to see if we can isolate the issue?\n\n========================================\n\nCode:\n```text\nexport default {\n router: {\n base: '/',\n },\n build: {\n transpile: [\n 'choices.js',\n 'lazysizes',\n 'swiper',\n 'vee-validate'\n ],\n extractCSS: true\n },\n srcDir: 'src/',\n performance: {\n gzip: true\n },\n render: {\n compressor: {\n threshold: 100\n }\n },\n dev: false\n}\n```\n\n```text\nbabel: {\n presets: [\n '@babel/preset-env'\n ],\n plugins: [\n '@babel/plugin-syntax-dynamic-import'\n ]\n}\n```\n\n```text\nnode_modules\n```\n\n```text\ntranspile\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnpm run build\n```\n\n```text\nnuxt build\n```\n\n```text\nconst\n```\n\n```text\nlet\n```\n\n```text\nvar\n```\n\n```text\nnode_modules\n```\n\n```text\nvue-app\n```\n\n```text\n2.1.0\n```\n\n```text\nbuild: {\n transpile: [\n 'swiper',\n 'dom7',\n ],\n}\n```\n\n```text\nlet\n```\n\n```text\nconst\n```\n\n```text\nclass\n```\n\n========================================\n\nComments:\n- Are u sure that code is from the modules u trying to transpile? Can u setup a reproduction repository on codesandbox or github?\n- I will try and do that but wasn’t sure how to do Codesandbox with Nuxt. I’ll give it a go.\n- Codesandbox added SSR support in last week or so, and there is Nuxt template now there\n- Yes, I forgot to mention that it is Swiper causing the issue. It appears to internally depend on something called Dom7. I see references to that all over. I really need to crack this! So frustrating. I just updated my question to mention this. Thanks for your help.\n- Yea, I know. I'm trying to replicate with a bare-bone nuxt app now, but for some reason it seems to be working there. Although if I use the same settings in my original project it doesn't work. Did you configure nuxt with a server-side framework like express, koa etc?\n- Would you mind adding a word about *why* that's necessary?","metadata":{"transformedAt":"2026-08-18T18:33:07.866Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":191,"estimatedTokens":988}}421{"id":"stack-55348119","source":"stackoverflow","questionId":55348119,"title":"Nuxt.js - fonts preload in production","tags":["vue.js","nuxt.js"],"text":"Title: Nuxt.js - fonts preload in production\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nEverything is fine during development - preload has fonts, images, scripts. But when I build production, the fonts do not fall into preload. There is everything except fonts.\n\n```\nrender: {\n http2: {\n push: true,\n pushAssets: (req, res, publicPath, preloadFiles) => console.log(preloadFiles)\n }\n}\n```\n\nOutput in dev (`nuxt`)\n\n```\n[ \n {\n file: 'runtime.js',\n extension: 'js',\n fileWithoutQuery: 'runtime.js',\n asType: 'script'\n },\n {\n file: 'vendors.app.js',\n extension: 'js',\n fileWithoutQuery: 'vendors.app.js',\n asType: 'script'\n },\n {\n file: 'app.js',\n extension: 'js',\n fileWithoutQuery: 'app.js',\n asType: 'script'\n },\n {\n file: 'assets/fonts/Play.woff',\n extension: 'woff',\n fileWithoutQuery: 'assets/fonts/Play.woff',\n asType: 'font'\n },\n {\n file: 'assets/fonts/Play.woff2',\n extension: 'woff2',\n fileWithoutQuery: 'assets/fonts/Play.woff2',\n asType: 'font'\n },\n {\n file: 'pages/index.js',\n extension: 'js',\n fileWithoutQuery: 'pages/index.js',\n asType: 'script'\n },\n {\n file: 'assets/images/logo.svg',\n extension: 'svg',\n fileWithoutQuery: 'assets/images/logo.svg',\n asType: 'image'\n },\n]\n```\n\nOutput in production (`nuxt build; nuxt start`):\n\n```\n[ \n {\n file: '5e0bcb963558b2151b59.js',\n extension: 'js',\n fileWithoutQuery: '5e0bcb963558b2151b59.js',\n asType: 'script'\n },\n {\n file: 'a8df7e6ca1b41b6ba1f3.js',\n extension: 'js',\n fileWithoutQuery: 'a8df7e6ca1b41b6ba1f3.js',\n asType: 'script'\n },\n {\n file: 'da6509a7baaff1386039.js',\n extension: 'js',\n fileWithoutQuery: 'da6509a7baaff1386039.js',\n asType: 'script'\n },\n {\n file: '834b4e9b65d7391ff800.js',\n extension: 'js',\n fileWithoutQuery: '834b4e9b65d7391ff800.js',\n asType: 'script'\n },\n {\n file: 'img/0b5b752.svg',\n extension: 'svg',\n fileWithoutQuery: 'img/0b5b752.svg',\n asType: 'image'\n },\n]\n```\n\nI can't figure it out. Maybe someone faced such problem? How to decide?\n\nI had to write this text because I couldn't publish so much code, and I don't know what else to say. Sorry for such cheating\n\nUPD: Repo with minimal reproduction https://github.com/NomNes/nuxtjs-fonts-preload-bug.git\n\n========================================\n\nTop Answer:\nhey i had the same problem and of course it was one of the gtmetrix warnings , so after many searches i found out i can put my code in layouts/default.vue ( the name of directory can be different in some projects but this is file that u can define your header and footer components like this:\n\n```\n\n ( your content )\n\n```\n\nany way in the template of this default.vue u can simply add your code like other sites:\n\n```\n\n```\n\nhope this be helpful\n\n========================================\n\nCode:\n```text\nrender: {\n http2: {\n push: true,\n pushAssets: (req, res, publicPath, preloadFiles) => console.log(preloadFiles)\n }\n}\n```\n\n```text\n[ \n {\n file: 'runtime.js',\n extension: 'js',\n fileWithoutQuery: 'runtime.js',\n asType: 'script'\n },\n {\n file: 'vendors.app.js',\n extension: 'js',\n fileWithoutQuery: 'vendors.app.js',\n asType: 'script'\n },\n {\n file: 'app.js',\n extension: 'js',\n fileWithoutQuery: 'app.js',\n asType: 'script'\n },\n {\n file: 'assets/fonts/Play.woff',\n extension: 'woff',\n fileWithoutQuery: 'assets/fonts/Play.woff',\n asType: 'font'\n },\n {\n file: 'assets/fonts/Play.woff2',\n extension: 'woff2',\n fileWithoutQuery: 'assets/fonts/Play.woff2',\n asType: 'font'\n },\n {\n file: 'pages/index.js',\n extension: 'js',\n fileWithoutQuery: 'pages/index.js',\n asType: 'script'\n },\n {\n file: 'assets/images/logo.svg',\n extension: 'svg',\n fileWithoutQuery: 'assets/images/logo.svg',\n asType: 'image'\n },\n]\n```\n\n```text\n[ \n {\n file: '5e0bcb963558b2151b59.js',\n extension: 'js',\n fileWithoutQuery: '5e0bcb963558b2151b59.js',\n asType: 'script'\n },\n {\n file: 'a8df7e6ca1b41b6ba1f3.js',\n extension: 'js',\n fileWithoutQuery: 'a8df7e6ca1b41b6ba1f3.js',\n asType: 'script'\n },\n {\n file: 'da6509a7baaff1386039.js',\n extension: 'js',\n fileWithoutQuery: 'da6509a7baaff1386039.js',\n asType: 'script'\n },\n {\n file: '834b4e9b65d7391ff800.js',\n extension: 'js',\n fileWithoutQuery: '834b4e9b65d7391ff800.js',\n asType: 'script'\n },\n {\n file: 'img/0b5b752.svg',\n extension: 'svg',\n fileWithoutQuery: 'img/0b5b752.svg',\n asType: 'image'\n },\n]\n```\n\n```text\nnuxt\n```\n\n```text\nnuxt build; nuxt start\n```\n\n```text\n{t.exports=n.p+\"fonts/860685f.woff2\"}\n```\n\n```text\n<style data-vue-ssr-id=\"17cfdfa9:0 aab9a468:0\">\n.nuxt-progress{position:fixed;top:0;left:0;right:0;height:2px;width:0;opacity:1;transition:width .1s,opacity .4s;background-color:#000;z-index:999999}\n.nuxt-progress.nuxt-progress-notransition{transition:none}.nuxt-progress-failed{background-color:red}\n @font-face{font-family:Play;src:url(/_nuxt/fonts/860685f.woff2) format(\"woff2\");font-weight:400;font-style:normal;font-display:swap}\n</style>\n```\n\n```text\n/***/ \"./assets/Play.woff2\":\n/*!***************************!*\\\n !*** ./assets/Play.woff2 ***!\n \\***************************/\n/*! no static exports found */\n```\n\n```text\nnuxt start\n```\n\n```text\nnuxt start\n```\n\n```text\n<link rel=\"preload\" href=\"/_nuxt/e54b54068d4c2a981747.js\" as=\"script\">\n```\n\n```text\nnuxt start\n```\n\n```text\nnuxt dev\n```\n\n```text\n:)\n```\n\n```text\n<SiteHeader />\n\n<nuxt /> ( your content )\n\n<SiteFooter />\n```\n\n```text\n<template>\n<div>\n<link rel=\"preload\" as=\"style\" href=\"https://pro.fontawesome.com/releases/v5.10.0/css/all.css\" crossorigin=\"anonymous\" onload=\"this.rel='stylesheet'\"/>\n</dive>\n</template>\n```\n\n```js\n<style lang=\"scss\">\n@import url(~/assets/font);\n.\n.\n.\n</style>\n```\n\n```text\ndefault.vue\n```\n\n========================================\n\nComments:\n- font from global css? Than it wont be in preloadedFiles. Try to move your fonts into inline style in your layout\n- Thanks. I moved the font import to `layouts/default.vue`, but nothing has changed. In `console.log` from `shouldPreload` also no fonts\n- @NikitaUmnov create reproduction then\n- added to the question\n- @NikitaUmnov ye, sorry, it wont work in layout too. Same problem as with external css. It will work only in pages, but thats not a solution. So we wait for feedback on PR in vue and if all fine, PR in nuxt will be merged and released in the next patch release after it","metadata":{"transformedAt":"2026-08-18T18:33:07.866Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":310,"estimatedTokens":1593}}422{"id":"stack-49090240","source":"stackoverflow","questionId":49090240,"title":"Nuxt / Vue.js in TypeScript: Object literal may only specify known properties, but 'components' does not exist in type 'VueClass'","tags":["typescript","vue.js","nuxt.js"],"text":"Title: Nuxt / Vue.js in TypeScript: Object literal may only specify known properties, but 'components' does not exist in type 'VueClass'\nTags: typescript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm not quite sure why I'm getting this error message when I use a decorator with components and middleware:\n\nhttps://i.sstatic.net/dutqx.png\n\nUpon inspection, the error reads:\n`TS2345: Argument of type '{ components: { Test: typeof Nav; }; middleware: string[]; }' is not assignable to parameter of type 'VueClass'.\n Object literal may only specify known properties, but 'components' does not exist in type 'VueClass'. Did you mean to write 'component'?`\n\nhttps://i.sstatic.net/vEr1p.png\n\nWithout middleware, the @Component decorator no longer fusses:\n\nhttps://i.sstatic.net/FMp5P.png\n\nAny idea why this might be?\n\n========================================\n\nCode:\n```text\nTS2345: Argument of type '{ components: { Test: typeof Nav; }; middleware: string[]; }' is not assignable to parameter of type 'VueClass'.\n Object literal may only specify known properties, but 'components' does not exist in type 'VueClass'. Did you mean to write 'component'?\n```\n\n```text\n// references.d.ts\n/**\n * Extends interfaces in Vue.js\n */\n\nimport Vue, { ComponentOptions } from \"vue\";\n\ndeclare module \"vue/types/options\" {\n interface ComponentOptions<V extends Vue> {\n // This adds the `middleware` property to the existing `vue/types/options/ComponentOptions` type\n middleware?: string | string[];\n }\n}\n```\n\n```text\nmiddleware\n```\n\n```text\ncomponents\n```\n\n```text\n{components: ..., middleware: ...}\n```\n\n```text\nComponentOptions\n```\n\n```text\nmiddleware\n```\n\n```text\n.d.ts\n```\n\n```text\nreferences.d.ts\n```\n\n```text\nstore\n```\n\n```text\nvuex/types/vue.d.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.866Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":80,"estimatedTokens":439}}423{"id":"stack-64563322","source":"stackoverflow","questionId":64563322,"title":"Vuex, Nuxt: Unknown action type","tags":["javascript","vue.js","nuxt.js","vuex"],"text":"Title: Vuex, Nuxt: Unknown action type\nTags: javascript, vue.js, nuxt.js, vuex\nSource: Stack Overflow\n\nQuestion:\nI'm building a simple app using nuxt + vuex. When commiting/dispatching I constantly get error \"unknown action/mutation type: **name**\". Also my mutations and actions don't display in vue devtools. On the other hand getters and state displaying as they should be.\n\nstore/products.js:\n\n```\nimport getProducts from \"~/api/products\";\n\nexport const state = () => ({\n all: [{ isAvailable: false }, { isAvailable: true }],\n});\n\nexport const getters = {\n available(state) {\n return state.all.filter((p) => p.isAvailable);\n },\n};\n\nexport const actions = {\n async fetchProducts(context) {\n const response = await getProducts(true);\n const products = await response.json();\n context.commit(\"setProducts\", products);\n },\n};\n\nexport const mutations = {\n setProducts(state, products) {\n state.products = products;\n },\n};\n```\n\npages/products/index.vue\n\n```\n\n \n\nexport default {\n async created() {\n await this.$store.dispatch(\"fetchProducts\");\n },\n};\n\n```\n\n**What I've tried**\n\n- Writing actions/mutations as following via arrow function\n\n```\nexport const actions = {\n fetchProducts: async (context) => {\n const response = await getProducts(true);\n const products = await response.json();\n context.commit(\"setProducts\", products);\n },\n};\n```\n\nWriting actions/mutations in index.js\n\nCopied example from docs. State is working, mutations don't.\n\nAll above mentioned points didn't work. Any Ideas?\n\n========================================\n\nCode:\n```text\nimport getProducts from \"~/api/products\";\n\nexport const state = () => ({\n all: [{ isAvailable: false }, { isAvailable: true }],\n});\n\nexport const getters = {\n available(state) {\n return state.all.filter((p) => p.isAvailable);\n },\n};\n\nexport const actions = {\n async fetchProducts(context) {\n const response = await getProducts(true);\n const products = await response.json();\n context.commit(\"setProducts\", products);\n },\n};\n\nexport const mutations = {\n setProducts(state, products) {\n state.products = products;\n },\n};\n```\n\n```text\n<template>\n <div class=\"container\"></div>\n</template>\n\n<script>\nexport default {\n async created() {\n await this.$store.dispatch(\"fetchProducts\");\n },\n};\n</script>\n\n<style lang=\"scss\" scoped></style>\n```\n\n```text\nexport const actions = {\n fetchProducts: async (context) => {\n const response = await getProducts(true);\n const products = await response.json();\n context.commit(\"setProducts\", products);\n },\n};\n```\n\n```js\nawait this.$store.dispatch(\"products/fetchProducts\");\n```\n\n```js\nexport default {\n mode: 'spa',\n devtools: true //<--------- make sure this is set to true\n}\n```\n\n```text\nawait this.$store.dispatch(\"fetchProducts\")\n```\n\n```text\nmodule/actionName\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- That's worked, but is there a way not to specify module? Also in dev tools I still don't see mutations and actions.\n- @Neistow you can specify module name by assigning a `property name`\n- Is this a `nuxt` thing or new `vuex` feature? actions didn't require addressing the module in vuex.\n- Looks, it's not working with Nuxt 3","metadata":{"transformedAt":"2026-08-18T18:33:07.866Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":158,"estimatedTokens":800}}424{"id":"stack-76488291","source":"stackoverflow","questionId":76488291,"title":"How to fetch data as part of server start up in Nuxt 3?","tags":["vue.js","nuxt.js","vuejs3","nuxt3.js","runtime-configuration"],"text":"Title: How to fetch data as part of server start up in Nuxt 3?\nTags: vue.js, nuxt.js, vuejs3, nuxt3.js, runtime-configuration\nSource: Stack Overflow\n\nQuestion:\nI have a web app in Nuxt 3 that is being migrated from Nuxt 2. We also have a companion API that handles all data fetching from databases. When starting the webserver, the nuxt app must fetch a JSON object with some settings (stuff required for start up and some constant variables to use as runtime params) from this API. These values can be different per deployment and only change when the API and the app are updated (meaning both will need to be restarted). I do not want to fetch this data in a plugin everytime a user enters the app because the call will always yield the same result. The current Nuxt 2 config looks like this:\n\n```\n// nuxt.config.js (Nuxt 2)\n\nexport default async () => {\n const result = await someAsyncCall()\n\n return {\n // actual config, use result in runtime parameters here, exposed under this.$config\n }\n}\n```\n\nAccording to the migration guide (https://nuxt.com/docs/migration/configuration#async-configuration) this way of working is now deprecated in Nuxt 3 and it's recommended to use Nuxt hooks but I cannot find the correct way to achieve this. The goal is to have the app fetch this json data once on start up and to make this data available for use everywhere. I have tried the following approaches:\n\n```\n// This is the Nuxt 3 equivalent, but it's deprecated and for some reason it calls the data twice:\n\n// nuxt.config.ts\n\nexport default async () => { \n const result = await someAsyncCall()\n\n return defineNuxtConfig({\n runtimeConfig:{\n // use result here\n }\n })\n}\n```\n\n```\n// This doesn't update the runtime config\n\n//nuxt.config.ts\n\nexport default defineNuxtConfig({\n runtimeConfig: {\n public: {\n myparam: ''\n }\n },\n hooks: {\n ready: async (nuxt) => { // not sure if 'ready' is available at deploy since it's a build hook anyway\n console.log('READY')\n const settings = await getRuntimeConfig()\n nuxt.options.runtimeConfig.public.myparam = settings\n }\n },\n})\n```\n\n```\n// It's not allowed to import from nuxt.config.ts so this doesn't work.\n\n// nuxt.config.ts\n\nexport const settings = {}\n\nexport default defineNuxtConfig({\n hooks: {\n ready: async (nuxt) => {\n console.log('READY')\n const _settings = await getRuntimeConfig()\n settings = _settings\n }\n },\n})\n\n// myPlugin.ts\nimport { settings } from 'nuxt.config' // not allowed\n\nexport default defineNuxtPlugin(() => {\n return { provide: { settings } }\n})\n```\n\nI also checked https://nuxt.com/docs/api/advanced/hooks but nothing seems suited. How can I achieve the desired result?\n\n========================================\n\nTop Answer:\n### You're looking to make a custom Nuxt 3 module\n\nThe Nuxt 3 plugins will only work during runtime and **modules** are now build time only.\n\nI think this section in the docs may solve your issue: Exposing Options to Runtime\n\nHere is an example of how I was able to achieve this (I'm using Nuxt v3.6.1):\n\n```\nimport {\n defineNuxtModule,\n useLogger,\n createResolver,\n addImportsDir,\n addRouteMiddleware,\n addTypeTemplate,\n} from 'nuxt/kit'\nimport { $fetch } from 'ofetch'\n\nexport default defineNuxtModule({\n meta: {\n // Usually the npm package name of your module\n name: '@nuxtjs/my-module',\n // The key in `nuxt.config` that holds your module options\n configKey: 'my-module',\n // Compatibility constraints\n compatibility: {\n // Semver version of supported nuxt versions\n nuxt: '^3.6.1',\n },\n },\n\n defaults: {\n // Your Defuault Options\n },\n async setup(options, nuxt) {\n // Create the path resolver\n const resolver = createResolver(import.meta.url)\n\n // Create the consola logger\n const logger = useLogger('my-module')\n logger.start('Starting...')\n\n const URL = `some-api/endpoint`\n const data = await $fetch(URL) // I type my responses\n if (data) { //! I don't know what your response is going to look like\n // You could put these in public or merge existing ones with defu from unjs\n nuxt.options.runtimeConfig.options.myModuleOptions = data\n logger.success('Successfuly Loaded!')\n }\n \n //* Add Feature Specific Composables\n addImportsDir(resolver.resolve('runtime/composables'))\n\n //* Add Feature Specific Middleware\n addRouteMiddleware({\n name: 'myModuleMiddleware',\n path: resolver.resolve('runtime/middleware/someMiddleware'),\n global: true,\n })\n\n //* Add the Feature Specific Types\n addTypeTemplate({\n filename: 'types/my-module-types.d.ts',\n src: resolver.resolve('runtime/types.ts'),\n write: true,\n })\n },\n})\n```\n\nThere actually isn't a lot of documentation for around type templates or middleware in Nuxt 3 so I hope this helps someone.\n\n========================================\n\nCode:\n```js\n// nuxt.config.js (Nuxt 2)\n\nexport default async () => {\n const result = await someAsyncCall()\n\n return {\n // actual config, use result in runtime parameters here, exposed under this.$config\n }\n}\n```\n\n```js\n// This is the Nuxt 3 equivalent, but it's deprecated and for some reason it calls the data twice:\n\n// nuxt.config.ts\n\nexport default async () => { \n const result = await someAsyncCall()\n\n return defineNuxtConfig({\n runtimeConfig:{\n // use result here\n }\n })\n}\n```\n\n```text\n// This doesn't update the runtime config\n\n//nuxt.config.ts\n\nexport default defineNuxtConfig({\n runtimeConfig: {\n public: {\n myparam: ''\n }\n },\n hooks: {\n ready: async (nuxt) => { // not sure if 'ready' is available at deploy since it's a build hook anyway\n console.log('READY')\n const settings = await getRuntimeConfig()\n nuxt.options.runtimeConfig.public.myparam = settings\n }\n },\n})\n```\n\n```text\n// It's not allowed to import from nuxt.config.ts so this doesn't work.\n\n// nuxt.config.ts\n\nexport const settings = {}\n\nexport default defineNuxtConfig({\n hooks: {\n ready: async (nuxt) => {\n console.log('READY')\n const _settings = await getRuntimeConfig()\n settings = _settings\n }\n },\n})\n\n// myPlugin.ts\nimport { settings } from 'nuxt.config' // not allowed\n\nexport default defineNuxtPlugin(() => {\n return { provide: { settings } }\n})\n```\n\n```text\n// /server/plugins/01.fetchSettings.ts\n\nimport { useLogger } from '@nuxt/kit'\nimport type { Settings } from '@/types/api'\n\nexport default defineNitroPlugin(async () => {\n const storage = useStorage('SOME_KEY')\n const consola = useLogger()\n\n const endpoint = useRuntimeConfig().settingsEndpoint\n\n async function fetchSettings() {\n consola.start('Fetching settings...')\n\n const result = await $fetch<Settings>(endpoint)\n await storage.setItem<Settings>('settings', result)\n\n consola.success(`Settings fetched succesfully!`)\n }\n try {\n fetchSettings()\n } catch (e) {\n consola.error('Error fetching settings.')\n // Error handling here\n }\n})\n```\n\n```text\n// /server/api/settings.ts\n\nimport type { Settings } from '@/types/api'\n\nexport default cachedEventHandler(async () => {\n return await useStorage('SOME_KEY').getItem<Settings>('settings')\n})\n```\n\n```text\n// /plugins/01.injectSettings.ts\n\nexport default defineNuxtPlugin(async () => {\n const asyncData = await useFetch('/api/settings')\n\n return {\n provide: {\n settings: asyncData.data.value\n }\n }\n})\n```\n\n```text\n<template>\n <div>{{ $settings }}</div>\n</template>\n\n<script lang=\"ts\" setup>\n // Only required if you use the settings inside <script>\n const { $settings } = useNuxtApp()\n</script>\n```\n\n```text\nuseStorage\n```\n\n```text\n/server/api/\n```\n\n```text\ncachedEventHandler\n```\n\n```text\nEventHandler\n```\n\n```text\ncachedEventHandler\n```\n\n```text\nuseFetch\n```\n\n```text\n$fetch\n```\n\n```text\nimport {\n defineNuxtModule,\n useLogger,\n createResolver,\n addImportsDir,\n addRouteMiddleware,\n addTypeTemplate,\n} from 'nuxt/kit'\nimport { $fetch } from 'ofetch'\n\nexport default defineNuxtModule({\n meta: {\n // Usually the npm package name of your module\n name: '@nuxtjs/my-module',\n // The key in `nuxt.config` that holds your module options\n configKey: 'my-module',\n // Compatibility constraints\n compatibility: {\n // Semver version of supported nuxt versions\n nuxt: '^3.6.1',\n },\n },\n\n defaults: {\n // Your Defuault Options\n },\n async setup(options, nuxt) {\n // Create the path resolver\n const resolver = createResolver(import.meta.url)\n\n // Create the consola logger\n const logger = useLogger('my-module')\n logger.start('Starting...')\n\n\n const URL = `some-api/endpoint`\n const data = await $fetch<ResponseType>(URL) // I type my responses\n if (data) { //! I don't know what your response is going to look like\n // You could put these in public or merge existing ones with defu from unjs\n nuxt.options.runtimeConfig.options.myModuleOptions = data\n logger.success('Successfuly Loaded!')\n }\n \n //* Add Feature Specific Composables\n addImportsDir(resolver.resolve('runtime/composables'))\n\n //* Add Feature Specific Middleware\n addRouteMiddleware({\n name: 'myModuleMiddleware',\n path: resolver.resolve('runtime/middleware/someMiddleware'),\n global: true,\n })\n\n //* Add the Feature Specific Types\n addTypeTemplate({\n filename: 'types/my-module-types.d.ts',\n src: resolver.resolve('runtime/types.ts'),\n write: true,\n })\n },\n})\n```\n\n```text\n// `server.prepare.ts`\nimport { defineNuxtPrepareHandler } from 'nuxt-prepare/config'\nimport { useLogger } from '@nuxt/kit'\nimport { API } from './api/downloads'\n\nexport default defineNuxtPrepareHandler(async () => {\n const consola = useLogger()\n const apiBaseUrl = process.env.API_BASE_URL\n let ok = true\n let publicConfig = {}\n\n async function fetchVersions() {\n consola.start('Fetching versions...')\n\n const response = await fetch(`${apiBaseUrl}/${API.ALL_VERSION}?product=MQTTX`)\n const { data: versions } = await response.json()\n\n consola.success(`Versions fetched succesfully!`)\n\n return {\n versions,\n latestVersion: versions[0],\n }\n }\n\n try {\n publicConfig = await fetchVersions()\n }\n catch (e) {\n consola.error('Error fetching versions.')\n ok = false\n }\n\n return {\n ok,\n runtimeConfig: {\n public: { ...publicConfig },\n },\n }\n})\n```\n\n```text\n// `plugins/01.injectVersions.ts`\n\nexport default defineNuxtPlugin(async () => {\n const { versions, latestVersion } = useRuntimeConfig().public\n\n return {\n provide: {\n versions,\n latestVersion,\n },\n }\n})\n```\n\n```js\n<script setup lang=\"ts\">\nconst { $versions } = useNuxtApp()\n</script>\n\n<template>\n <ul class=\"version-list\">\n <li v-for=\"(item, index) in $versions\" :key=\"index\" class=\"is-size-5 my-2\">\n <nuxt-link :to=\"i18nLocalePath(`/changelogs/${item}`)\">\n {{ item }}\n </nuxt-link>\n </li>\n </ul>\n</template>\n```\n\n```text\nnuxt-prepare\n```\n\n```text\nsharedPrerenderData: true\n```\n\n========================================\n\nComments:\n- reading from the docs, it's better to defer this to a hook since nuxt will synchronously setup each module.\n- Thanks for the suggestion. I've investigated this option and my conclusion is that a module won't be able to inject anything at build time that could solve my problem at runtime that I couldn't just program into the main project directly. It did help me discover the fact Nitro plugins are a thing which might offer a solution.\n- From my testing, the plugins don't actually prevent the server from returning a response. I tried awaiting a 30s promise in the plugin as a test and nuxt rendered the page *before* the promise in the plugin resolved. Is there a way to block the startup? I also need to fetch some config & there is no point in returning a response if the config isn't present on the server. I'd like to make this as robust as possible.\n- Plugins run \"on the first Nitro initialisation.\" (nitro.unjs.io/guide/plugins) This sounds a bit vague IMO but it might mean just after start up. If you can't prevent the server from accepting requests before your config is available, I'd write a server middleware that returns a `503 Service Unavailable` response if the data is not yet available at the time of the request. \"The HyperText Transfer Protocol (HTTP) 503 Service Unavailable server error response code indicates that the server is not ready to handle the request.\"\n- Docs for writing server middleware in Nuxt 3: nuxt.com/docs/guide/directory-structure/…","metadata":{"transformedAt":"2026-08-18T18:33:07.866Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":484,"estimatedTokens":3146}}425{"id":"stack-59035905","source":"stackoverflow","questionId":59035905,"title":"Nuxt encode/decode URI with double colon","tags":["vue.js","nuxt.js"],"text":"Title: Nuxt encode/decode URI with double colon\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nMy URLs have double colon on them.\n\nI push a path to Nuxt router which has **:** as a part of it.\n\n```\nexport default {\n router: {\n extendRoutes (routes, resolve) {\n routes.push({\n name: 'custom',\n path: 'towns' + '(:[0-9].*)?/',\n component: resolve(__dirname, 'pages/404.vue')\n })\n }\n }\n}\n```\n\nWhen I point to http://localhost:3000/towns:3 , for example, the **:** is translated as `%3A`on the URL leading to this error message:\n\n```\nExpected \"1\" to match \":[0-9].*\", but received \"%3A2\"\n```\n\nHow to revert this to **:** ?\n\nI tried encodeURI(), decodeURI(), encodeURIComponent() and decodeURIComponent() in vain.\n\nA demo for the ones who wants to try: nuxt-extend-routes\n\nAny suggestions are welcome\n\n========================================\n\nTop Answer:\nVuex is using `vue-router` and vue-router is using path-to-regexp to parse router path configuration\n\nIt seems to me, that you are trying to use Unnamed Parameters which doesn't make sense because vue-router/vuex need the name of the parameter to pass it down to Vue component behind the route\n\nWhy don't just use named parameters ? \n\n```\n{\n path: '/towns:id(:\\\\d+)',\n name: 'Page 3',\n component: Page3\n }\n```\n\nSure, result will be that `$route.params.id` value will be prefixed with `:` and all `router-link` params must be `:XX` instead of 'XX' but that's something you can deal with. `vue-router` (`path-to-regexp`) is using `:` to \"mark\" named path parameters ...there's no way around it\n\nYou can take a look at this sandbox. Its not Nuxt but I'm pretty sure it will work in Nuxt same way....\n\n### Update\n\nWell it really doesn't work in Nuxt. It seems Nuxt is for some reason applying `encodeURIComponent()` on matched path segments and throws an error. It works when server-side rendering tho (it throws some error on client still)...\n\n========================================\n\nCode:\n```text\nexport default {\n router: {\n extendRoutes (routes, resolve) {\n routes.push({\n name: 'custom',\n path: 'towns' + '(:[0-9].*)?/',\n component: resolve(__dirname, 'pages/404.vue')\n })\n }\n }\n}\n```\n\n```text\nExpected \"1\" to match \":[0-9].*\", but received \"%3A2\"\n```\n\n```text\n%3A\n```\n\n```js\npath: 'towns' + '(:[0-9].*)?/',\n```\n\n```js\npath: 'towns(:[0-9].*)?/',\n```\n\n```js\npath: '/towns(:[0-9]+)?',\n```\n\n```js\npath: '/towns:([0-9]+)',\n```\n\n```js\npath: '/towns::town([0-9]+)',\n```\n\n```html\n<NuxtLink :to=\"{ name: 'custom', params: { town: 4 } }\">\n ...\n</NuxtLink>\n```\n\n```text\n:\n```\n\n```text\n%3A\n```\n\n```text\n:\n```\n\n```text\n%3A\n```\n\n```text\n/\n```\n\n```text\n/\n```\n\n```text\n.*\n```\n\n```text\ntowns:3abcd\n```\n\n```text\ntowns:3214\n```\n\n```text\n[0-9]+\n```\n\n```text\n:\n```\n\n```text\n:\n```\n\n```text\n/towns\n```\n\n```text\n/towns\n```\n\n```text\nnuxt-link\n```\n\n```text\n::\n```\n\n```text\n:\n```\n\n```text\n:\n```\n\n```text\ntown\n```\n\n```text\nnuxt-link\n```\n\n```js\n{\n path: '/towns:id(:\\\\d+)',\n name: 'Page 3',\n component: Page3\n }\n```\n\n```text\nvue-router\n```\n\n```text\n$route.params.id\n```\n\n```text\n:\n```\n\n```text\nrouter-link\n```\n\n```text\n:XX\n```\n\n```text\nvue-router\n```\n\n```text\npath-to-regexp\n```\n\n```text\n:\n```\n\n```text\nencodeURIComponent()\n```\n\n========================================\n\nComments:\n- `:` is not a valid URL character.\n- stackoverflow.com/questions/2053132/…\n- why not use `/towns/3` it's built-in and standard\n- You are right, that could be easier, but I can't change the URI formats by myself @LawrenceCherone\n- Could you please provide a reference for your statement ? In that case you can post it as an answer and I will be glad to accept it @tony19\n- That's fine. Change your regex as you wish, just make sure to prefix it with `:myparamname` so `vue-router` make the regex result available to you in `$route.params.myparamname`\n- Unfortunately for Nuxt, this did not work (getting the error message I shared above). But thank you very much for the feedback\n- Yes, that is how it behaves (before posting, I tried `path: '*' + 'towns' + decodeURIComponent('(:[0-9].*)?/'),` but got the same error message).\n- Changing `path` won't help. There is no problem with `:` in the route definition. Problem is with the code that is matching actual url (from browser nav bar or from `nuxt-link`) against that path during navigation. It's a bug in Nuxt IMHO...\n- Interesting solution. Works much better with Vue Router than mine. But unfortunately last example still doesn't work in Nuxt. Link works (parameter is passed to target component) but `href` is rendered as `/towns::` so parameter is lost after refresh....\n- @MichalLevý Interesting. I don't see that problem myself. I cloned the GitHub repo from the original question, so I'm using Nuxt 2.10.2 and Vue Router 3.0.7. I did originally experiment with `path: '/towns\\\\::town([0-9]+)',` as a way to explicitly escape the first colon but it didn't seem to be necessary so I didn't include it in my answer. As I can't reproduce the problem you're seeing it's difficult to know where to start trying to debug it...\n- Nevermind. I was testing it in Codesandbox and it apparently has it's quirks. After restarting the container, it works like a charm. Good job! This should be accepted answer ...","metadata":{"transformedAt":"2026-08-18T18:33:07.866Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":39,"totalLines":252,"estimatedTokens":1317}}426{"id":"stack-70516746","source":"stackoverflow","questionId":70516746,"title":"How to use Pug in Nuxt 3.x?","tags":["nuxt.js","pug","vite","nuxt3.js"],"text":"Title: How to use Pug in Nuxt 3.x?\nTags: nuxt.js, pug, vite, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nIf we create the Nuxt 3 application by `npx nuxi init nuxt3-app` and change the content of `app.vue` from\n\n```\n\n \n \n \n\n```\n\nto\n\n```\n\n div\n NuxtWelcome\n\n```\n\nwe'll get\n\n```\nERROR [unhandledRejection] Cannot find module 'pug' 17:05:54\nRequire stack:\n- D:\\IntelliJ IDEA\\Experiments\\nuxt3-app\\node_modules\\@vue\\compiler-sfc\\dist\\compiler-sfc.cjs.js\n- D:\\IntelliJ IDEA\\Experiments\\nuxt3-app\\node_modules\\vue\\compiler-sfc\\index.js\n- D:\\IntelliJ IDEA\\Experiments\\nuxt3-app\\node_modules\\@vitejs\\plugin-vue\\dist\\index.js\n```\n\nI did not expected the build-in Pug support but there is also no hint how to provide.\n\nAFAIK default Nuxt 3 setup use the Vite istead of Webpack. Maybe the answer is in Vite setup overriding?\n\n========================================\n\nTop Answer:\nI know it's been over a year since this question, but I recently had the same question and found an easier solution.\n\nYou can just install `pug` and it will work. No need for any plugins or other extra configs.\n\nJust in case: I am using `Nuxt@3.6.5` and `Pug@3.0.2`\n\nUPD: There is actually a need for a little bit of config. Mainly for IDE support. You should also add `@vue/language-plugin-pug` and extend your `tsconfig.json` with `vueCompilerOptions` like it shown below:\n\n```\n{\n // https://nuxt.com/docs/guide/concepts/typescript\n \"extends\": \"./.nuxt/tsconfig.json\",\n \"vueCompilerOptions\": {\n \"plugins\": [\"@vue/language-plugin-pug\"]\n }\n}\n```\n\n========================================\n\nCode:\n```xml\n<template>\n <div>\n <NuxtWelcome />\n </div>\n</template>\n```\n\n```text\n<template lang=\"pug\">\n\n div\n NuxtWelcome\n\n</template>\n```\n\n```text\nERROR [unhandledRejection] Cannot find module 'pug' 17:05:54\nRequire stack:\n- D:\\IntelliJ IDEA\\Experiments\\nuxt3-app\\node_modules\\@vue\\compiler-sfc\\dist\\compiler-sfc.cjs.js\n- D:\\IntelliJ IDEA\\Experiments\\nuxt3-app\\node_modules\\vue\\compiler-sfc\\index.js\n- D:\\IntelliJ IDEA\\Experiments\\nuxt3-app\\node_modules\\@vitejs\\plugin-vue\\dist\\index.js\n```\n\n```text\nnpx nuxi init nuxt3-app\n```\n\n```text\napp.vue\n```\n\n```json\n{\n // https://nuxt.com/docs/guide/concepts/typescript\n \"extends\": \"./.nuxt/tsconfig.json\",\n \"vueCompilerOptions\": {\n \"plugins\": [\"@vue/language-plugin-pug\"]\n }\n}\n```\n\n```text\npug\n```\n\n```text\nNuxt@3.6.5\n```\n\n```text\nPug@3.0.2\n```\n\n```text\n@vue/language-plugin-pug\n```\n\n```text\ntsconfig.json\n```\n\n```text\nvueCompilerOptions\n```\n\n========================================\n\nComments:\n- If you're taking the Pug path, be careful of a lot of bugs actually because when you add a middleware between your HTML and your code, you will have some issues at some point.\n- Also, please accept this answer.\n- @kissu Thank you for the comment! I will accept this answer once Stack Overflow will permit it (own answers could be accepted in 3 days).\n- you can include this in `eslintrc` to IDE support `{ \"extends\": [ \"@nuxt/eslint-config\", \"plugin:prettier/recommended\", \"plugin:vue-pug/vue3-recommended\" ] }`","metadata":{"transformedAt":"2026-08-18T18:33:07.866Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":136,"estimatedTokens":809}}427{"id":"stack-69149171","source":"stackoverflow","questionId":69149171,"title":"Failed to execute 'put' on 'Cache' : workbox and nuxt","tags":["javascript","vue.js","nuxt.js","web-worker","workbox"],"text":"Title: Failed to execute 'put' on 'Cache' : workbox and nuxt\nTags: javascript, vue.js, nuxt.js, web-worker, workbox\nSource: Stack Overflow\n\nQuestion:\nI'm on Nuxtjs 2.15.7 and recently getting this error in my console\n\nhttps://i.sstatic.net/pvjv9.png\n\nhttps://i.sstatic.net/A3nrF.png\n\nas I searched, only got to `@nuxt/pwa` issue . But I don't have pwa module in my project!!\n\nhere is my package.json\n\n```\n{\n \"name\": \"my-app\",\n \"version\": \"2.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"dev:host\": \"nuxt --hostname 0.0.0.0 --port 8000\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"@nuxtjs/auth\": \"^4.9.1\",\n \"@nuxtjs/axios\": \"^5.13.1\",\n \"@nuxtjs/device\": \"^2.1.0\",\n \"@nuxtjs/google-gtag\": \"^1.0.4\",\n \"@nuxtjs/gtm\": \"^2.4.0\",\n \"cookie-universal-nuxt\": \"^2.1.4\",\n \"core-js\": \"^3.15.1\",\n \"nuxt\": \"^2.15.7\",\n \"swiper\": \"^5.4.5\",\n \"v-viewer\": \"^1.5.1\",\n \"vee-validate\": \"^3.3.7\",\n \"vue-awesome-swiper\": \"^4.1.1\",\n \"vue-cropperjs\": \"^4.1.0\",\n \"vue-easy-dnd\": \"^1.12.2\",\n \"vue-persian-datetime-picker\": \"^2.2.0\",\n \"vue-product-zoomer\": \"^3.0.1\",\n \"vue-sweetalert2\": \"^4.2.1\",\n \"vue2-editor\": \"^2.10.2\",\n \"vuedraggable\": \"^2.24.0\"\n },\n \"devDependencies\": {\n \"@fortawesome/fontawesome-free\": \"^5.15.1\",\n \"@mdi/font\": \"^5.9.55\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"@nuxtjs/vuetify\": \"1.12.1\",\n \"flipclock\": \"^0.10.8\",\n \"font-awesome\": \"^4.7.0\",\n \"glob\": \"^7.1.7\",\n \"noty\": \"^3.2.0-beta\",\n \"nuxt-gsap-module\": \"^1.2.1\",\n \"sass\": \"1.32.13\"\n }\n}\n```\n\ncan anybody help?\n\n**UPDATE**\n\nI only get the error in dev mode\n\nI cleared Cache Storage and re run nuxt and still got error and a cache for workbox has been created again:\n\nhttps://i.sstatic.net/pBSPu.png\n\n========================================\n\nCode:\n```json\n{\n \"name\": \"my-app\",\n \"version\": \"2.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"dev:host\": \"nuxt --hostname 0.0.0.0 --port 8000\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"@nuxtjs/auth\": \"^4.9.1\",\n \"@nuxtjs/axios\": \"^5.13.1\",\n \"@nuxtjs/device\": \"^2.1.0\",\n \"@nuxtjs/google-gtag\": \"^1.0.4\",\n \"@nuxtjs/gtm\": \"^2.4.0\",\n \"cookie-universal-nuxt\": \"^2.1.4\",\n \"core-js\": \"^3.15.1\",\n \"nuxt\": \"^2.15.7\",\n \"swiper\": \"^5.4.5\",\n \"v-viewer\": \"^1.5.1\",\n \"vee-validate\": \"^3.3.7\",\n \"vue-awesome-swiper\": \"^4.1.1\",\n \"vue-cropperjs\": \"^4.1.0\",\n \"vue-easy-dnd\": \"^1.12.2\",\n \"vue-persian-datetime-picker\": \"^2.2.0\",\n \"vue-product-zoomer\": \"^3.0.1\",\n \"vue-sweetalert2\": \"^4.2.1\",\n \"vue2-editor\": \"^2.10.2\",\n \"vuedraggable\": \"^2.24.0\"\n },\n \"devDependencies\": {\n \"@fortawesome/fontawesome-free\": \"^5.15.1\",\n \"@mdi/font\": \"^5.9.55\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"@nuxtjs/vuetify\": \"1.12.1\",\n \"flipclock\": \"^0.10.8\",\n \"font-awesome\": \"^4.7.0\",\n \"glob\": \"^7.1.7\",\n \"noty\": \"^3.2.0-beta\",\n \"nuxt-gsap-module\": \"^1.2.1\",\n \"sass\": \"1.32.13\"\n }\n}\n```\n\n```text\n@nuxt/pwa\n```\n\n========================================\n\nComments:\n- This one is maybe coming from another project that you once ran locally?\n- @kissu actually I have another clone of this project that has been customized and that project has pwa installed!! is that possible!!?\n- @kissu there was two workbox in my browser cache storage, so deleted them and ran nuxt again and it created another workbox (updated question with its image) . so if it's because of another projects pwa, how can i clear that!!?\n- I actually clear the whole browser cache and history! :D\n- how to \"Unregister the SW in your devtools. \"?\n- @MartianMartian first screenshot of the question (the devtools one), on the middle right: `Network requests, Update, Unregister`.","metadata":{"transformedAt":"2026-08-18T18:33:07.867Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":137,"estimatedTokens":932}}428{"id":"stack-67824862","source":"stackoverflow","questionId":67824862,"title":"How to make a dynamic import in Nuxt?","tags":["vue.js","nuxt.js","server-side-rendering","ace-editor"],"text":"Title: How to make a dynamic import in Nuxt?\nTags: vue.js, nuxt.js, server-side-rendering, ace-editor\nSource: Stack Overflow\n\nQuestion:\nIn my nuxt component I want to use the ace editor:\n\n```\nimport Ace from \"ace-builds/src-noconflict/ace\"\n```\n\nwhen the component is mounted I am doing the following:\n\n```\nthis.editor = Ace.edit...\n```\n\nObviously `the window is not defined` on the server on page reload. But unfortunately I just can't find a solution to fix this issue.\n\nIs there a way to import a package on the `mounted()` hook?\nI already tried\n\n```\nconst Ace = require(\"ace-builds/src-noconflict/ace\")\n```\n\nBut that doesn't quite seem to work. Do you have any ideas to solve this issue?\n\nI already tried to register a plugin `plugins/ace.js`:\n\n```\nimport Vue from \"vue\"\nimport Ace from \"ace-builds/src-noconflict/ace\"\nVue.use(Ace)\n```\n\nregistered it in `nuxt.config.js`:\n\n```\nplugins: [\n { src: \"~/plugins/ace\", mode: \"client\" }\n],\n```\n\nBut how do I use Ace in my component now? It is still undefined...\n\n========================================\n\nTop Answer:\n**Nuxt Plugin**\n\nIMHO you were on the right track with the \"plugin\" solution. Only mistake was the\n`Vue.use(Ace)` part. This only works for vue plugins.\n\nThe plugin file could look somewhat like that:\n\n\r\n\r\n\n```\nimport Ace from 'ace-builds/src-noconflict/ace'\nimport Theme from 'ace-builds/src-noconflict/theme-monokai'\n\nexport default ({ app }, inject) => {\n inject('ace', {\n editor: Ace,\n theme: Theme\n })\n}\n```\n\n\r\n\r\n\r\n\nThen you could use this plugin and initiate the editor in a component this way:\n\n```\n\n \n function foo(items) {\n var x = \"All this is syntax highlighted\";\n return x;\n }\n \n\nexport default {\n data () {\n return {\n editor: {}\n }\n },\n mounted () {\n this.editor = this.$ace.editor.edit('editor')\n this.editor.setTheme(this.$ace.theme)\n }\n}\n\n```\n\n========================================\n\nCode:\n```js\nimport Ace from \"ace-builds/src-noconflict/ace\"\n```\n\n```js\nthis.editor = Ace.edit...\n```\n\n```js\nconst Ace = require(\"ace-builds/src-noconflict/ace\")\n```\n\n```js\nimport Vue from \"vue\"\nimport Ace from \"ace-builds/src-noconflict/ace\"\nVue.use(Ace)\n```\n\n```js\nplugins: [\n { src: \"~/plugins/ace\", mode: \"client\" }\n],\n```\n\n```text\nthe window is not defined\n```\n\n```text\nmounted()\n```\n\n```text\nplugins/ace.js\n```\n\n```text\nnuxt.config.js\n```\n\n```js\nasync mounted() {\n if (process.client) {\n const Ace = await import('ace-builds/src-noconflict/ace')\n Ace.edit...\n }\n},\n```\n\n```text\nmounted\n```\n\n```text\nprocess.client\n```\n\n```text\ncreated\n```\n\n```js\nimport Ace from 'ace-builds/src-noconflict/ace'\nimport Theme from 'ace-builds/src-noconflict/theme-monokai'\n\nexport default ({ app }, inject) => {\n inject('ace', {\n editor: Ace,\n theme: Theme\n })\n}\n```\n\n```html\n<template>\n <div id=\"editor\">\n function foo(items) {\n var x = \"All this is syntax highlighted\";\n return x;\n }\n </div>\n</template>\n\n<script>\nexport default {\n data () {\n return {\n editor: {}\n }\n },\n mounted () {\n this.editor = this.$ace.editor.edit('editor')\n this.editor.setTheme(this.$ace.theme)\n }\n}\n</script>\n```\n\n```text\nVue.use(Ace)\n```\n\n========================================\n\nComments:\n- As for the \"client side\" topic: this part of the plugin documentation should help\n- And you question how to access the plugin is answered here\n- Unfortunately, that doesn't work. The error gets thrown due to the import statement, not due to `Ace.edit`\n- Still, I have a minor question though. Since I am dynamically importing the package in my component now it only seems to work together with the plugin I stated in my inital question up above. So currently I am importing a package to my entire app even though I only need it in a single component. That doesn't look optimal :/\n- When you do **import** (and not **require**), Webpack will handle the tree-shaking of the editor. Even more, you could load on a click or a specific event. Until it's done, it will not be available globally into your app. So, actually this is the optimal way (to my knowledge) to import it into a single specific component. Using it as a Nuxt plugin will be the solution to use it globally through your app. Dynamic import => if you need it, import it. Require => import the **whole** package in any case. `require` is the bad boy and the old way of doing things.\n- Okay, so actually it should work by only importing it in the component, right? Somehow it doesn't make sense to me that I still need the nuxt plugin. Maybe I don't fully understand the concept of Nuxt here, but when I `console.log(\"hello\")` in my nuxt plugin. It is logged on every route of my application. Therefor the package is imported on every single route (on page reload). That's what I meant with not optimal.\n- Haha, sorry to have not explained this directly. You can totally ditch the plugin if you **only** want to use it locally in your component. Plugins are indeed imported globally at the start of your app. Local import in the component => local usage, Nuxt plugin => global usage. Both => non sense.\n- Okay, so I still kind of have an issue here. 1. If I only import the package in a plugin (globally), without dynamically importing it inside the component aswell, then `Ace is not defined`. 2. If I only import it dynamically inside my component, then `Ace is not defined`. 3. If I import it like every other package on top, then I get `window is not defined` 4. Only if I import it dynamically and in the plugin I don't get the error. That just doesn't make sense to me. I hope you understand my struggle haha.\n- Isn't the 2. a matter of scope? Try changing it to `let Ace`, and get it out of the `mounted()` scope and define it during the import if you're using it out of the `mounted()` hook.","metadata":{"transformedAt":"2026-08-18T18:33:07.867Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":217,"estimatedTokens":1435}}429{"id":"stack-55218951","source":"stackoverflow","questionId":55218951,"title":"Call mixin function from asyncData() method of the page component with Nuxt.js","tags":["vue.js","mixins","nuxt.js","asyncdata"],"text":"Title: Call mixin function from asyncData() method of the page component with Nuxt.js\nTags: vue.js, mixins, nuxt.js, asyncdata\nSource: Stack Overflow\n\nQuestion:\nCan I call mixin function from `asyncData()` method of the page component with Nuxt.js?\n\nMy code:\n\n```\n\n ...\n\n import api from \"@/plugins/api/api.js\"\n\n ...\n\n export default {\n\n ...\n\n async asyncData(context) {\n ...\n context.apiMethodName()\n ...\n }\n\n ...\n }\n\n ...\n\n```\n\n`api.js`\n\n```\nimport Vue from 'vue'\nimport API from '@/assets/js/api'\n\nVue.mixin({\n methods: {\n apiMethodName() { ... }\n }\n})\n```\n\n========================================\n\nTop Answer:\nI see it is quite late for the answer, but it is possible.\n\ntemplate.vue\n\n```\n\n...\n\n import api from \"~/mixins/api/api\"\n ...\n\n export default {\n ...\n\n async asyncData({context}) {\n ...\n // You don't need to use context\n // You have to use \"api\" like this:\n const collection = await api.methods.apiMethodName()\n ...\n\n // bear in mind you should return data from this function\n return {\n collection,\n ...\n }\n }\n ...\n }\n ...\n\n```\n\n~/mixins/api/api.js\n\n```\nconst api = {\n ...\n methods: {\n async apiMethodName() {\n ...\n // better use here try / catch or Promise with then / catch\n const data = await do_something()\n ...\n\n return data\n }\n ...\n }\n ...\n}\n\nexport api\n```\n\nA similar approach was tested with stack VueJS + NuxtJS and it is working on the live website https://elfinforce.com.\n\n========================================\n\nCode:\n```text\n<template>\n ...\n</template>\n<script>\n import api from \"@/plugins/api/api.js\"\n\n ...\n\n export default {\n\n ...\n\n async asyncData(context) {\n ...\n context.apiMethodName()\n ...\n }\n\n ...\n }\n\n ...\n</script>\n```\n\n```text\nimport Vue from 'vue'\nimport API from '@/assets/js/api'\n\nVue.mixin({\n methods: {\n apiMethodName() { ... }\n }\n})\n```\n\n```text\nasyncData()\n```\n\n```text\napi.js\n```\n\n```js\nexport default ({ app }, inject) => {\n inject('apiMethodName', () => {\n return 'some data!';\n })\n}\n```\n\n```js\nasync asyncData(context) {\n context.app.$apiMethodName();\n})\n```\n\n```text\nasyncData()\n```\n\n```text\napiMethodName()\n```\n\n```text\n<template>\n...\n</template>\n<script>\n import api from \"~/mixins/api/api\"\n ...\n\n export default {\n ...\n\n async asyncData({context}) {\n ...\n // You don't need to use context\n // You have to use \"api\" like this:\n const collection = await api.methods.apiMethodName()\n ...\n\n // bear in mind you should return data from this function\n return {\n collection,\n ...\n }\n }\n ...\n }\n ...\n</script>\n```\n\n```text\nconst api = {\n ...\n methods: {\n async apiMethodName() {\n ...\n // better use here try / catch or Promise with then / catch\n const data = await do_something()\n ...\n\n return data\n }\n ...\n }\n ...\n}\n\nexport api\n```\n\n```text\napp.router.app.gloablMethod()\n```\n\n========================================\n\nComments:\n- You CAN call a method from asyncData. See my answer.\n- @IgorPopov not true. You are not calling method of component from asyncData. You just calling external function without access to component this.\n- What makes you unable to write asyncData in a page component? However according to the documentation while running asyncData function Vue instance is not yet created. So if we are talking about \"this\" - it doesn't exist yet. And you forget about the purpose of asyncData: this is a hook that can only be placed on page components, it blocks route navigation until it is resolved and must return data.\n- Meanwhile, the key question from the author is: Can I call mixin function from asyncData? And the answer is YES, you can. Author did not ask to call a \"method of component\", but \"mixin function\". In the first comment, I made a mistake. I meant to call the function from mixin from a separate file.\n- @IgorPopov the question was about calling mixin function from asyncData. Thats it. Your solution is just call external function which you obv can do from anywhere and it has nothing to do with quesiton. What you propose isnt calling mixin function. Mixin is a specific thing is vue, not some random external function in other file.\n- Literally, a mixin is a JS object which can contain instance options like normal instance objects. During the creation of Vue instance, it merged against the eventual options using the certain option merging logic. But before creating Vue instance being imported mixin is simply yet another random external JS Object. And while it is still in a Vue life cycle it is acceptable. You can argue for whole your life, or use the working approach posted by me :)\n- @IgorPopov lol, ofc your approach working. its essentialy same as writing all code inside asyncData but just moving it outside into function. But again its nothing to do with question that op asked. In mixin you have access to instance in your approach no\n- You don't need any injection. You CAN call a method from asyncData. See my answer.\n- That's not true. It is possible.","metadata":{"transformedAt":"2026-08-18T18:33:07.867Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":243,"estimatedTokens":1258}}430{"id":"stack-74777076","source":"stackoverflow","questionId":74777076,"title":"Nuxt 3 - How to refresh fetched data every n minutes","tags":["typescript","vue.js","nuxt.js","nuxt3.js"],"text":"Title: Nuxt 3 - How to refresh fetched data every n minutes\nTags: typescript, vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nSo in my database data gets refreshed every minute(data actually updates, I checked) and then I display this data on the page. Data gets fetched when I switch between pages and when I manually refresh the page as it should, but if I sit on one page for example 5 min, data does not get refreshed on the page side even tho data updates in the database.\n\nIs it possible to refresh fetch data let's say every minute when user is active on page, without hitting refresh button all the time?\n\nI fetch data using useFetch(), but I don't use any additional parameters because I don't need them. In documentation specifically says, that params have to change in order to get refresh work.\n\n```\nvar {data: fixture, refresh, pending, error} = await useFetch('/api/getFixture')``\n```\n\nI've tried something like that:\n\n```\nfunction refreshing(){\n refresh\n console.log(\"refreshing\")\n}\nsetInterval(() => refreshing(), 10000);\n```\n\nThe function gets executed but the data does not refresh because if I understand correctly, there was no change in params right?\nI also tried using:\n\n```\nrefreshNuxtData()\n```\n\nwhich should \"execute\" fetch again, but no luck either.\n\nThank you and best regards,\n\n========================================\n\nCode:\n```text\nvar {data: fixture, refresh, pending, error} = await useFetch('/api/getFixture')``\n```\n\n```text\nfunction refreshing(){\n refresh\n console.log(\"refreshing\")\n}\nsetInterval(() => refreshing(), 10000);\n```\n\n```text\nrefreshNuxtData()\n```\n\n```html\n<script setup>\nimport { useIntervalFn } from '@vueuse/core' // VueUse helper, install it\n\nconst { pending, data, error, refresh } = await useFetch('https://jsonplaceholder.typicode.com/todos/1')\n\nuseIntervalFn(() => {\n console.log(`refreshing the data again ${new Date().toISOString()}`)\n refresh() // will call the 'todos' endpoint, just above\n}, 3000) // call it back every 3s\n</script>\n\n<template>\n <div v-if=\"!pending\">\n <pre>{{ data }}</pre>\n </div>\n</template>\n```\n\n```html\n<button @click=\"refresh\">force</button>\n```\n\n```text\nuseFetch\n```\n\n```text\nrefresh\n```\n\n========================================\n\nComments:\n- Hi, please give a try to that one: stackoverflow.com/a/74697681/8816585\n- Unfortunately it does not work for me, it executes the function after 60 seconds but refresh() does nothing\n- Posted an answer with even more details + a minimal reproducible example.\n- Hmm, interesting, thank you very much. If I use your example it works as it should\n- @Lolek no, nothing related to dev/production. Something else is not behaving properly. Be sure to be using the stable `v3.0.0` of Nuxt, not having any errors in your console + no middleware or weird plugins.","metadata":{"transformedAt":"2026-08-18T18:33:07.867Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":94,"estimatedTokens":700}}431{"id":"stack-56874285","source":"stackoverflow","questionId":56874285,"title":"NUXT Duplicating Styles","tags":["vue.js","nuxt.js"],"text":"Title: NUXT Duplicating Styles\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWithin my NUXT project it seems that CSS is being duplicated, not only on individual components, but when compiled duplicates styles from my nuxt.config.js - styleResources -> scss into the `head` tag. \n\nThis seems to be a problem for me pre NUXT 2.0 as well as post (current ver: 2.8.1). I've tried a bunch of things on build but I must be missing something...\n\nMy config for the global styles:\n\n```\nmodule.exports = {\n...\n styleResources: {\n scss: [\n '~/styles/variables.scss',\n '~/styles/normalize.scss',\n '~/styles/forms.scss',\n '~/styles/mixins.scss',\n '~/styles/type.scss',\n '~/styles/buttons.scss',\n '~/styles/font.scss',\n '~/styles/loader.scss'\n ],\n },\n build: {\n path: '',\n parallel: true,\n cache: true,\n\n optimization: {\n minimize: true,\n runtimeChunk: true,\n concatenateModules: true,\n splitChunks: {\n chunks: 'all',\n minSize: 30000,\n maxSize: 0,\n minChunks: 1,\n maxAsyncRequests: 20,\n maxInitialRequests: 3,\n automaticNameDelimiter: '~',\n name: true,\n cacheGroups: {\n vendors: {\n test: /[\\\\/]node_modules[\\\\/]/,\n priority: -10\n },\n default: {\n minChunks: 2,\n priority: -20,\n reuseExistingChunk: true\n }\n }\n }\n },\n // extractCSS: true,\n optimizeCSS: true,\n publicPath: process.env.CDN_URL || '',\n /*\n ** Run ESLint on save\n */\n extend (config, { isDev, isClient }) {\n if (isDev && isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n // loader: 'pug-plain-loader',\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n },\n plugins: [\n new webpack.ProvidePlugin({\n mapboxgl: 'mapbox-gl'\n })\n ]\n }\n...\n}\n```\n\n!https://i.sstatic.net/wviJ3.png\n!https://i.sstatic.net/tBoRE.png\n\nThe end goal is to obviously not have duplicate styles.\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n...\n styleResources: {\n scss: [\n '~/styles/variables.scss',\n '~/styles/normalize.scss',\n '~/styles/forms.scss',\n '~/styles/mixins.scss',\n '~/styles/type.scss',\n '~/styles/buttons.scss',\n '~/styles/font.scss',\n '~/styles/loader.scss'\n ],\n },\n build: {\n path: '',\n parallel: true,\n cache: true,\n\n optimization: {\n minimize: true,\n runtimeChunk: true,\n concatenateModules: true,\n splitChunks: {\n chunks: 'all',\n minSize: 30000,\n maxSize: 0,\n minChunks: 1,\n maxAsyncRequests: 20,\n maxInitialRequests: 3,\n automaticNameDelimiter: '~',\n name: true,\n cacheGroups: {\n vendors: {\n test: /[\\\\/]node_modules[\\\\/]/,\n priority: -10\n },\n default: {\n minChunks: 2,\n priority: -20,\n reuseExistingChunk: true\n }\n }\n }\n },\n // extractCSS: true,\n optimizeCSS: true,\n publicPath: process.env.CDN_URL || '',\n /*\n ** Run ESLint on save\n */\n extend (config, { isDev, isClient }) {\n if (isDev && isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n // loader: 'pug-plain-loader',\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n },\n plugins: [\n new webpack.ProvidePlugin({\n mapboxgl: 'mapbox-gl'\n })\n ]\n }\n...\n}\n```\n\n```text\nhead\n```\n\n```text\nstyleResources: {\n scss: [\n '~/styles/variables.scss',\n '~/styles/mixins.scss',\n ],\n },\n css: [\n '~/styles/normalize.scss',\n '~/styles/forms.scss',\n '~/styles/type.scss',\n '~/styles/buttons.scss',\n '~/styles/font.scss',\n '~/styles/loader.scss'\n ]\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.867Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":185,"estimatedTokens":1029}}432{"id":"stack-64001841","source":"stackoverflow","questionId":64001841,"title":"Nuxt change favicon by page","tags":["html","nuxt.js","favicon"],"text":"Title: Nuxt change favicon by page\nTags: html, nuxt.js, favicon\nSource: Stack Overflow\n\nQuestion:\nI have certain cases where certain routes need a different favicon.\nI've tried throwing this code in the head, and while this does work, it adds another favicon underneath the previous one, and does not overwrite it.\n\npage.vue:\n\n```\nhead () {\n return {\n title: 'my website title',\n link: [{\n rel: 'icon', type: 'image/x-icon', href: 'https://s.yimg.com/rz/l/favicon.ico'\n }]\n }\n}\n```\n\n```\n\n```\n\nHow do you go about overwriting a favicon?\n\n========================================\n\nTop Answer:\nI think this link can help you\n\nhttps://reactgo.com/nuxt-change-favicon/\n\n- Open the nuxt app in your favorite code editor.\n\n- Navigate to the static folder and delete the favicon.ico file.\n\n- Now, add a new favicon inside the static folder.\n\n- Reload your nuxt app to see the new favicon.\n\n========================================\n\nCode:\n```text\nhead () {\n return {\n title: 'my website title',\n link: [{\n rel: 'icon', type: 'image/x-icon', href: 'https://s.yimg.com/rz/l/favicon.ico'\n }]\n }\n}\n```\n\n```text\n<link data-n-head=\"ssr\" rel=\"icon\" type=\"image/x-icon\" href=\"/favicon.ico\">\n<link data-n-head=\"ssr\" rel=\"icon\" type=\"image/x-icon\" href=\"https://s.yimg.com/rz/l/favicon.ico\">\n```\n\n```js\nlink: [{\n hid: 'icon',\n rel: 'icon',\n type: 'image/x-icon',\n href: 'link-to-fallback-favicon.png'\n}]\n```\n\n```js\nhead()\n return {\n link: [{\n hid: 'icon',\n rel: 'icon',\n type: 'image/x-icon',\n href: 'link-to-new-favicon.png'\n}]\n```\n\n```text\nhid\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nhead\n```\n\n========================================\n\nComments:\n- That will change the favicon across the whole site. I wanted to change it dynamically on a page by page basis.\n- Ah maybe the hid is what I was missing, I'll give it a shot thanks!","metadata":{"transformedAt":"2026-08-18T18:33:07.867Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":98,"estimatedTokens":475}}433{"id":"stack-72592413","source":"stackoverflow","questionId":72592413,"title":"Can't generate Nuxt website with @googlemaps/js-api-loader","tags":["javascript","vue.js","google-maps","nuxt.js","vercel"],"text":"Title: Can't generate Nuxt website with @googlemaps/js-api-loader\nTags: javascript, vue.js, google-maps, nuxt.js, vercel\nSource: Stack Overflow\n\nQuestion:\nI am using `@googlemaps/js-api-loader` in my Nuxt 3 website. Everything works fine in local development, but when I try to build the project with `nuxt generate` (no matter if locally or on Vercel) I'm getting following error:\n\n```\n[nuxt] [request error] Named export 'Loader' not found. The requested module 'file:///path/to/website/node_modules/@googlemaps/js-api-loader/dist/index.umd.js' is a CommonJS module, which may not support all module.exports as named exports. CommonJS modules can always be imported via the default export, for example using:\n```\n\nThe important part of loading script looks like this:\n\n```\nimport { Loader } from '@googlemaps/js-api-loader';\n\nconst loader = new Loader({\n apiKey: config.googleMapsApiKey,\n version: 'weekly',\n});\n\nonMounted(async() => {\n await loader\n .load()\n\n ...\n```\n\nso I tried to import this package differently, e.g.:\n\n```\nimport * as gmaps from '@googlemaps/js-api-loader';\nconst { Loader } = gmaps;\n```\n\nand the previous error disappeared, but now I'm getting\n\n```\n[Vue warn]: Unhandled error during execution of setup function\n at I also can't import package by default export. Do you have any ideas what's going on and how can I fix this?\n\n========================================\n\nCode:\n```text\n[nuxt] [request error] Named export 'Loader' not found. The requested module 'file:///path/to/website/node_modules/@googlemaps/js-api-loader/dist/index.umd.js' is a CommonJS module, which may not support all module.exports as named exports. CommonJS modules can always be imported via the default export, for example using:\n```\n\n```js\nimport { Loader } from '@googlemaps/js-api-loader';\n\nconst loader = new Loader({\n apiKey: config.googleMapsApiKey,\n version: 'weekly',\n});\n\nonMounted(async() => {\n await loader\n .load()\n\n ...\n```\n\n```text\nimport * as gmaps from '@googlemaps/js-api-loader';\nconst { Loader } = gmaps;\n```\n\n```text\n[Vue warn]: Unhandled error during execution of setup function\n at <DynamicLocations class=\"contact__map\" locations= [\n {\n id: 1,\n\n...\n\n\n[nuxt] [request error] gmaps.Loader is not a constructor\n at setup (./.nuxt/prerender/chunks/app/server.mjs:5536:20) \n at _sfc_main$t.setup (./.nuxt/prerender/chunks/app/server.mjs:5582:25) \n at callWithErrorHandling (./.nuxt/prerender/chunks/renderer.mjs:2654:23) \n at setupStatefulComponent (./.nuxt/prerender/chunks/renderer.mjs:9548:30) \n at setupComponent (./.nuxt/prerender/chunks/renderer.mjs:9503:12) \n at renderComponentVNode (./.nuxt/prerender/chunks/renderer.mjs:12068:17) \n at Object.ssrRenderComponent (./.nuxt/prerender/chunks/renderer.mjs:12504:12) \n at ./.nuxt/prerender/chunks/app/server.mjs:5628:36 \n at renderComponentSubTree (./.nuxt/prerender/chunks/renderer.mjs:12149:13) \n at renderComponentVNode (./.nuxt/prerender/chunks/renderer.mjs:12084:16)\n```\n\n```text\n@googlemaps/js-api-loader\n```\n\n```text\nnuxt generate\n```\n\n```text\nbuild: {\n transpile: ['@googlemaps/js-api-loader'],\n },\n```\n\n```text\nbuild.transpile\n```\n\n========================================\n\nComments:\n- Importing the entire library worked for me, which of course is not ideal. I opened an issue on GH. github.com/googlemaps/js-api-loader/issues/692\n- Thank you so much! You made my day! The documentation page link is broken BTW. This is the newer one: nuxt.com/docs/guide/concepts/esm#troubleshooting-esm-issues. I've tried to edit it, but it seems to be \"to many pending edits on Stack Overflow\", so it can't be done now.","metadata":{"transformedAt":"2026-08-18T18:33:07.867Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":113,"estimatedTokens":910}}434{"id":"stack-72037842","source":"stackoverflow","questionId":72037842,"title":"how can i import and use a local .csv file in vuejs","tags":["vue.js","csv","nuxt.js","vite"],"text":"Title: how can i import and use a local .csv file in vuejs\nTags: vue.js, csv, nuxt.js, vite\nSource: Stack Overflow\n\nQuestion:\ni have a csv file in this structure\n\n```\nname,year,href,src\nParasite,2019,parasite-2019,film-poster/4/2/6/4/0/6/426406-parasite-0-460-0-690-crop.jpg\n```\n\ni would like to import this file as a list with each line as a dict in this way:\n\n```\n[{'name':'Parasite','year':'2019','href':'parasite-2019','src':'film-poster/4/2/6/4/0/6/426406-parasite-0-460-0-690-crop.jpg'}]\n```\n\ni tried using `import csv from './filmList.csv'` inside the `` tag, but that only gives me an error on load:\n\n```\n[plugin:vite:import-analysis] Failed to parse source for import analysis because the content contains invalid JS syntax. You may need to install appropriate plugins to handle the .csv file format.\n```\n\n========================================\n\nCode:\n```text\nname,year,href,src\nParasite,2019,parasite-2019,film-poster/4/2/6/4/0/6/426406-parasite-0-460-0-690-crop.jpg\n```\n\n```js\n[{'name':'Parasite','year':'2019','href':'parasite-2019','src':'film-poster/4/2/6/4/0/6/426406-parasite-0-460-0-690-crop.jpg'}]\n```\n\n```text\n[plugin:vite:import-analysis] Failed to parse source for import analysis because the content contains invalid JS syntax. You may need to install appropriate plugins to handle the .csv file format.\n```\n\n```text\nimport csv from './filmList.csv'\n```\n\n```text\n<script>\n```\n\n```text\nnpm i -D @rollup/plugin-dsv\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport dsv from '@rollup/plugin-dsv' 👈\n\nexport default defineConfig({\n plugins: [\n vue(),\n dsv(), 👈\n ],\n})\n```\n\n```html\n<script>\n// MyComponent.vue\nimport csv from './filmList.csv'\nconsole.log(csv) // => [{'name':'Parasite','year':'2019','href':'parasite-2019','src':'film-poster/4/2/6/4/0/6/426406-parasite-0-460-0-690-crop.jpg'}]\n</script>\n```\n\n```text\n@rollup/plugin-dsv\n```\n\n```text\n.csv\n```\n\n========================================\n\nComments:\n- I spent a few hours trying to understand, so if it may help someone else, **using it with TypeScript**, you need to add these lines in your .d.ts file: ``` declare module \"*.csv\" { export default Array; } ```","metadata":{"transformedAt":"2026-08-18T18:33:07.867Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":86,"estimatedTokens":552}}435{"id":"stack-54997320","source":"stackoverflow","questionId":54997320,"title":"How to output css files as .css files instead of inline in nuxt.js?","tags":["css","vuejs2","nuxt.js"],"text":"Title: How to output css files as .css files instead of inline in nuxt.js?\nTags: css, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHow can I convert inline-CSS to CSS-files in nuxt.js? I have both scoped styles and global scss file in my app.\nI have already tried below code but no luck.\n\n```\nbuild: {\n optimization: {\n splitChunks: {\n chunks: 'all',\n automaticNameDelimiter: '.',\n name: 'rameez',\n cacheGroups: {}\n }\n },\n optimizeCSS:true\n }\n```\n\nhere you can see all the CSS including my global.scss is shown as an inline style.\n\nhttps://i.sstatic.net/nsRnm.gif\n\n========================================\n\nCode:\n```text\nbuild: {\n optimization: {\n splitChunks: {\n chunks: 'all',\n automaticNameDelimiter: '.',\n name: 'rameez',\n cacheGroups: {}\n }\n },\n optimizeCSS:true\n }\n```\n\n```text\nbuild:{\n extractCSS: true\n}\n```\n\n========================================\n\nComments:\n- I was already using `extractCSS: true` but was checking the output in dev mode.. that made me confuse, I think it extracts CSS in prod mode by default. anyway thanks.\n- @RameezRami yes, it wont work on dev. But no, on prod it default to false too, u need to set it yourself\n- yes that's why I said I was already using extractCSS: true :)","metadata":{"transformedAt":"2026-08-18T18:33:07.867Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":55,"estimatedTokens":316}}436{"id":"stack-66964590","source":"stackoverflow","questionId":66964590,"title":"useMeta not updating title in Nuxt Composition API","tags":["vue.js","nuxt.js","html-meta"],"text":"Title: useMeta not updating title in Nuxt Composition API\nTags: vue.js, nuxt.js, html-meta\nSource: Stack Overflow\n\nQuestion:\nHere is my code inside the Component Script : Title tag doesn't show up when I inspect\n\n```\nimport { useMeta } from \"@nuxtjs/composition-api\";\n\nexport default {\n components: { }, \n\nhead: {},\n\nsetup() {\n\nuseMeta({\n title: 'My title',\n meta: [\n {\n hid: 'description',\n name: 'description',\n content: 'My description',\n },\n ],\n })\n\nconst screenType = ref(\"desktop\");\nvar deviceType = \"\"\n// const screenType = ref(\"mobile\")\n// const screenType = ref(\"landscape\")\n\nif (process.browser) {\n window.onNuxtReady(() => {\n if (window.innerWidth There is no head object in my `nuxt.config.js`\n\nWhat am I missing here?\n\n========================================\n\nTop Answer:\nYou should use defineComponent imported from \"@nuxtjs/composition-api\". Do not use defineComponent imported from \"@vue/composition-api\".\n\n========================================\n\nCode:\n```text\nimport { useMeta } from \"@nuxtjs/composition-api\";\n\nexport default {\n components: { }, \n\nhead: {},\n\nsetup() {\n\nuseMeta({\n title: 'My title',\n meta: [\n {\n hid: 'description',\n name: 'description',\n content: 'My description',\n },\n ],\n })\n\n\nconst screenType = ref(\"desktop\");\nvar deviceType = \"\"\n// const screenType = ref(\"mobile\")\n// const screenType = ref(\"landscape\")\n\nif (process.browser) {\n window.onNuxtReady(() => {\n if (window.innerWidth < 500) {\n screenType.value = \"mobile\";\n } else {\n screenType.value = \"desktop\";\n }\n\n \n \n\n if (navigator.userAgent.match(/mobile/i)) {\n deviceType = \"mobile\";\n } else if (navigator.userAgent.match(/iPad|Android|Touch/i)) {\n deviceType = \"tablet\";\n } else {\n deviceType = \"desktop\";\n }\n\n\n })\n }\n\n\n\n} }\n```\n\n```text\nnuxt.config.js\n```\n\n```js\nexport default defineComponent({\n head: {}, // Needed in nuxt 2\n setup() {\n const { title, meta } = useMeta()\n title.value = 'My title'\n meta.value = [\n {\n hid: 'description',\n name: 'description',\n content:\n 'My description',\n },\n ]\n },\n })\n```\n\n```text\ndefineComponent\n```\n\n========================================\n\nComments:\n- I tried this, doesn't seem to work. I'm able to log the title and meta values but it's not updating in the browser. I'm running this on dev, will it work only with build?\n- Make sure you use this only on a Page component\n- This is my file structure > pages > widgets > _id.vue. My code is in _id.vue\n- You also need to use defineComponent\n- Read How to Answer: Could you explain *why* the former should be used and not the latter?\n- The former should be used uniformly, because if the two are used together, it will cause invalidation caused by incompatibility.","metadata":{"transformedAt":"2026-08-18T18:33:07.867Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":137,"estimatedTokens":743}}437{"id":"stack-70393465","source":"stackoverflow","questionId":70393465,"title":"Http response at 400 or 500 level","tags":["javascript","django","nuxt.js","grpc","envoyproxy"],"text":"Title: Http response at 400 or 500 level\nTags: javascript, django, nuxt.js, grpc, envoyproxy\nSource: Stack Overflow\n\nQuestion:\nI'm novice in gRPC. My program is written with `nuxtjs` and is a simple `login page` that receives the `username` and `password` and sends it to the server using gRPC.\nEverything is fine when I submit a request with BloomRPC. But when using the browser, the request is not sent to the server.\n\nMy `auth` class is as :\n\n```\n// auth.js\n\nexport default class {\n constructor(vars) {\n this.tokenKey = vars.tokenKey\n this.proto = vars.proto\n this.client = new vars.proto.AuthenticationClient('http://127.0.0.1:50051', null, null)\n }\n\n async loginRequest(user) {\n const request = new this.proto.LoginRequest()\n request.setUsername(user.username.trim().toLowerCase())\n request.setPassword(user.password.trim()) \n return await this.client.login(request, {}) \n } \n}\n```\n\nThis error is shown when requesting to the server with the browser, whether the server is up or not.\n\n```\nnet ERROR_CONNECTION_REFUSED\nmessage: 'Http response at 400 or 500 level'\n...\n```\n\n***Chrome Screenshot:***\nhttps://i.sstatic.net/Du2Bz.png\n\n**Do I have to do a specific configuration?**\n\n*I just want a hint for configuring.*\n\n### **UPDATE:**\n\nThis link says that you should use Envoy. But why do we need it? And how do I configure it?\n\n***BloomRPC screenshot:***\n\nAs you can see on the right side of the image, the answer is returned correctly.\nhttps://i.sstatic.net/vzs7c.png\n\n========================================\n\nTop Answer:\nAccording to chrome screenshot you trying to access to `5005` port in JS, but according to BloomRPC, screenshot your service listening `50051`.\n\n========================================\n\nCode:\n```text\n// auth.js\n\nexport default class {\n constructor(vars) {\n this.tokenKey = vars.tokenKey\n this.proto = vars.proto\n this.client = new vars.proto.AuthenticationClient('http://127.0.0.1:50051', null, null)\n }\n\n async loginRequest(user) {\n const request = new this.proto.LoginRequest()\n request.setUsername(user.username.trim().toLowerCase())\n request.setPassword(user.password.trim()) \n return await this.client.login(request, {}) \n } \n}\n```\n\n```text\nnet ERROR_CONNECTION_REFUSED\nmessage: 'Http response at 400 or 500 level'\n...\n```\n\n```text\nnuxtjs\n```\n\n```text\nlogin page\n```\n\n```text\nusername\n```\n\n```text\npassword\n```\n\n```text\nauth\n```\n\n```text\nstatic_resources:\n listeners:\n - name: listener_0\n address:\n socket_address: { address: 0.0.0.0, port_value: 5000 }\n filter_chains:\n - filters:\n - name: envoy.filters.network.http_connection_manager\n config:\n codec_type: auto\n stat_prefix: ingress_http\n route_config:\n name: local_route\n virtual_hosts:\n - name: local_service\n domains: [\"*\"]\n routes:\n - match: { prefix: \"/\" }\n route:\n cluster: sample_cluster\n max_grpc_timeout: 0s\n cors:\n allow_origin_string_match:\n - prefix: \"*\"\n allow_methods: GET, PUT, DELETE, POST, OPTIONS\n allow_headers: keep-alive,user-agent,cache-control,content-type,content-transfer-encoding,x-accept-content-transfer-encoding,x-accept-response-streaming,x-user-agent,x-grpc-web,grpc-timeout\n max_age: \"1728000\"\n expose_headers: grpc-status,grpc-message\n http_filters:\n - name: envoy.filters.http.grpc_web\n - name: envoy.filters.http.cors\n - name: envoy.filters.http.router\n clusters:\n - name: sample_cluster\n connect_timeout: 0.25s\n type: logical_dns\n http2_protocol_options: {}\n lb_policy: round_robin\n hosts: [{ socket_address: { address: 0.0.0.0, port_value: 50051 }}]\n```\n\n```text\n# Dockerfile\nFROM envoyproxy/envoy:v1.14.3\nCOPY ./envoy.yaml /etc/envoy/envoy.yaml\nEXPOSE 5000\nCMD /usr/local/bin/envoy -c /etc/envoy/envoy.yaml\n```\n\n```text\ndocker build -t my-grpc-container:1.0.0 .\ndocker run -d --net=host my-grpc-container:1.0.0\n```\n\n```text\n# server block\nroot /root/site;\n```\n\n```text\n# server block\nlocation /rpc/ {\n proxy_http_version 1.1;\n proxy_pass http://127.0.0.1:5000/;\n }\n```\n\n```text\nsudo systemctl restart nginx\n```\n\n```text\nenvoy\n```\n\n```text\ngRPC\n```\n\n```text\nnuxt\n```\n\n```text\nroot/site\n```\n\n```text\nenvoy\n```\n\n```text\nenvoy.yaml\n```\n\n```text\nlisteners\n```\n\n```text\nclusters\n```\n\n```text\nlisteners\n```\n\n```text\nclusters\n```\n\n```text\nDockerfile\n```\n\n```text\nenvoy\n```\n\n```text\nenvoy\n```\n\n```text\nnginx\n```\n\n```text\n/etc/nginx/sites-enabled/\n```\n\n```text\ndefault\n```\n\n```text\nnginx\n```\n\n```text\nurl\n```\n\n```text\n/rpc/\n```\n\n```text\nenvoy\n```\n\n```text\nnginx\n```\n\n```text\nnginx\n```\n\n```text\n/rpc/\n```\n\n```text\nenvoy\n```\n\n```text\nnginx\n```\n\n```text\nenvoy\n```\n\n```text\nserver\n```\n\n```text\nnginx\n```\n\n```text\n5005\n```\n\n```text\n50051\n```\n\n========================================\n\nComments:\n- Is `nuxt` actually running and listening 5005 port? Does it log something?\n- @Anton Nuxt is running on 3000 port and as you can see in the code, the request is sent to port 50051, where the server is listening.\n- Sorry, you are right. But does gRPC server log something?\n- You can try `curl -v http://127.0.01:5005` to check that port actually listening.\n- @Anton No. Does not record any logs. This is probably because the request will not be sent to the server.\n- It seems like `127.0.0.1:5005` actually not listening (also, listening `localhost` is not the same as listening `127.0.0.1`).\n- @Anton Exactly. Adequate configuration to connect to the server should probably be done.\n- Can you show screenshots of BloomRPC, with success queries?\n- @Anton Thanks for continuing to help. I am sending now.\n- @Saeed I found this. The only answer said that you have to use grpc-web.\n- @GiovanniEsposito Thanks. I've seen this answer before. The upvoted question and answer was done by me. I'm using grpc-web but it looks like it has configurations that I do not know how it is. I need to read more.\n- @Saeed well if you find a solution add an answer here. Could be very usefull!\n- @GiovanniEsposito The problem was that the requests did not reach the server and I needed a proxy to send the requests from the client to the server. Please see my answer.\n- you can refer to this answer about configuring the envoy proxy\n- Please see the new screenshot. No change.\n- @Saeed I suggest you try to change port, and make sure you use same host for your app and server (i.e. both 127.0.0.1 or both localhost)\n- Also, is this your issue? - github.com/grpc/grpc-web/issues/1175\n- The problem was that the requests did not reach the server. Please see my answer. I hope it is useful.\n- Thank you so much @Saeed, clear and detailed answer.","metadata":{"transformedAt":"2026-08-18T18:33:07.867Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":43,"totalLines":320,"estimatedTokens":1757}}438{"id":"stack-67590515","source":"stackoverflow","questionId":67590515,"title":"Use vuetify `mdi` icons locally in nuxt.js and block `cdn.jsdelivr.net` cdn","tags":["javascript","vue.js","nuxt.js","vuetify.js"],"text":"Title: Use vuetify `mdi` icons locally in nuxt.js and block `cdn.jsdelivr.net` cdn\nTags: javascript, vue.js, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nI am using `vuetify` framework in the `nuxt.js` ecosystem and there's a problem! https://cdn.jsdelivr.net is blocked by my country `Iran` and every time user wants to load the Vue application it stuck loading this URI. so I want to use `mdi` icons locally in my app and somehow store them in the static directory or elsewhere.\n\nPlease let me know how can I avoid mdi CDN and use it just like another global CSS via nuxt.config.js\n\n### Nuxt Config\n\n```\ncss: [\n '@/assets/main.css',\n '@mdi/font/css/materialdesignicons.css'\n ],\nvuetify: {\n rtl: true,\n lang: {\n locales: {\n fa\n },\n current: 'fa'\n },\n options: {\n customProperties: true,\n },\n theme: {\n light: true,\n themes: {\n light: {\n primary: '#15977D',\n secondary: '#205072',\n accent: '#82B1FF',\n error: '#FF5252',\n danger: '#f62d51',\n success: '#36bea6',\n warning: '#FFC107'\n },\n },\n },\n customVariables: ['~/assets/variables.scss'],\n icons: {\n iconfont: 'mdi',\n },\n },\n```\n\n### Browser Network Panel\n\nhttps://i.sstatic.net/QAo55.png\n\n========================================\n\nTop Answer:\nYou should access the CDN's CSS file, copy it's content to a local `.css` file in your project and import it with something like `css: ['~/assets/css/materialicons.css']`.\n\n========================================\n\nCode:\n```js\ncss: [\n '@/assets/main.css',\n '@mdi/font/css/materialdesignicons.css'\n ],\nvuetify: {\n rtl: true,\n lang: {\n locales: {\n fa\n },\n current: 'fa'\n },\n options: {\n customProperties: true,\n },\n theme: {\n light: true,\n themes: {\n light: {\n primary: '#15977D',\n secondary: '#205072',\n accent: '#82B1FF',\n error: '#FF5252',\n danger: '#f62d51',\n success: '#36bea6',\n warning: '#FFC107'\n },\n },\n },\n customVariables: ['~/assets/variables.scss'],\n icons: {\n iconfont: 'mdi',\n },\n },\n```\n\n```text\nvuetify\n```\n\n```text\nnuxt.js\n```\n\n```text\nIran\n```\n\n```text\nmdi\n```\n\n```js\nvuetify: {\n defaultAssets: false,\n}\n```\n\n```text\n.css\n```\n\n```text\ncss: ['~/assets/css/materialicons.css']\n```\n\n========================================\n\nComments:\n- Thanks! but it makes another problem. Cause in that CSS file from `jsdeliver` which I downloaded it, there are some `src: url()` links that makes some errors like: `Error: Can't resolve 'materialdesignicons-webfont.eot?v=5.9.55'`. I looked into the file and it was another webfont icon file which cause this error. `src:url(\"../fonts/materialdesignicons-webfont.eot?v=5.9.55\")‌​;`. I can download it too. but there are pleanty of those...\n- Did you tried installing it via npm with this package? github.com/chungtran4078/nuxtjs-mdi-font\n- I downloaded all files via this link and put all fonts into `static/fonts` and put `materialicons.css` into `assets`. the final touch that make it working fine was renaming all `../fonts` to `/fonts`.\n- Thanks @Hasan. Do you have a link to where this is documented? Cheers","metadata":{"transformedAt":"2026-08-18T18:33:07.867Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":134,"estimatedTokens":791}}439{"id":"stack-66868348","source":"stackoverflow","questionId":66868348,"title":"Nuxt.js vuex store not persisted","tags":["vue.js","nuxt.js","state","vuex","store"],"text":"Title: Nuxt.js vuex store not persisted\nTags: vue.js, nuxt.js, state, vuex, store\nSource: Stack Overflow\n\nQuestion:\nI've got some strange issues with my Nuxt.js Setup.\nSome States in Store arent persistent, everytime I load another view, they went back to the default value.\n\n*pages/test.vue*\n\n```\n\n \n \n \n \n test | {{this.$store.state.test}} |\n \n \n \n \n\nexport default {\n name: 'test',\n methods: {\n setTest() {\n this.$store.commit(\"setTest\")\n },\n }\n}\n\n```\n\n*store/index.js*\n\n```\nexport const state = () => ({\n test: \"test\"\n})\n\nexport const mutations = {\n setTest: (state) => state.test = 'Hello'\n}\n```\n\nTestscenario is to hit the \"test\"-button who call the method with mutation-commit \"setTest\" which set the state to \"Hello\". Currently it works fine, but if I changed the view or reload the page, the state is set to default \"test\".\n\nWhat am I doing wrong?\n\n========================================\n\nCode:\n```html\n<template>\n <section class=\"section\">\n <b-container>\n <b-row>\n <b-col cols=12>\n <b-button @click=\"setTest\" variant=\"dark\">test</b-button> | {{this.$store.state.test}} |\n </b-col>\n </b-row>\n </b-container>\n </section>\n</template>\n\n<script>\nexport default {\n name: 'test',\n methods: {\n setTest() {\n this.$store.commit(\"setTest\")\n },\n }\n}\n</script>\n```\n\n```js\nexport const state = () => ({\n test: \"test\"\n})\n\nexport const mutations = {\n setTest: (state) => state.test = 'Hello'\n}\n```\n\n```text\nhref\n```\n\n```text\n<nuxt-link></nuxt-link>\n```\n\n```text\nto=\"/profile\"\n```\n\n```text\n<router-link></router-link>\n```\n\n```text\nwindow.location.href\n```\n\n```text\n<a href=\"...\"\n```\n\n```text\nnuxt-link\n```\n\n```text\nrouter-link\n```\n\n```text\nnuxt/auth\n```\n\n========================================\n\nComments:\n- It is totally legit that the Vuex store is \"reset\" if you F5 the page. What do you mean by \"changed the view\" ? vue-router or modifying the URL by yourself ?\n- Hey @kissu :-) I \"change the view\" by just clicking on by navbar-links, e.g.: {{ $t(\"my_profile\") }} So is it realy reloading? I use the common build-in things from nuxt.js\n- I can also suggest Vuex Persisted State plugin.","metadata":{"transformedAt":"2026-08-18T18:33:07.867Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":129,"estimatedTokens":536}}440{"id":"stack-54557966","source":"stackoverflow","questionId":54557966,"title":"Conditional module loading in Nuxt.js","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Conditional module loading in Nuxt.js\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a module for Google Tag Manager in my Nuxt.js config, like so:\n\n```\nmodules: [\n [\n '@nuxtjs/google-tag-manager',\n {\n id: 'GTM-XXXXXXX'\n }\n ]\n]\n```\n\nThis is working fine but I am wondering how I can conditionally load this module based on the value of a cookie set by the site?\n\nWe have a mechanism by which the user can select certain cookies to accept or deny and a part of that is to block tracking scripts.\n\nIs there any recommended way to do this with modules or scripts loaded via the config? Ideally, it would be possible to then load these should the values within the cookies change in the future as well.\n\nAny help or pointers are greatly appreciated.\n\n========================================\n\nCode:\n```text\nmodules: [\n [\n '@nuxtjs/google-tag-manager',\n {\n id: 'GTM-XXXXXXX'\n }\n ]\n]\n```\n\n```text\n// app/plugins/gtm.js\n\nimport Cookies from 'js-cookie'\n\nconst gtmKey = 'GTM-XXXXX' // <- insert your GTM key here\n\nexport default () => {\n /*\n ** Only run on client-side and only in production mode\n */\n if (process.env.NODE_ENV !== 'production') return\n /*\n ** Only run if it's not prevented by user\n */\n if (Cookies.get('disable-gtm')) return\n /*\n ** Include Google Tag Manager\n */\n (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\n m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');\n\n (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':\n new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],\n j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=\n 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);\n })(window,document,'script','dataLayer', gtmKey)\n}\n```\n\n```text\n@nuxtjs/google-tag-manager\n```\n\n```text\ndisable-gtm\n```\n\n```text\ngtm.js\n```\n\n========================================\n\nComments:\n- Nuxt modules are only executed during the building process. For example the GTM module allows you to use a function for the `id` and skips the including the whole GTM if `id` is `null` but it won't help you because the `id` function is only executed once and not at run time of the app/site. I'm currently at the same problem right now and will post the solution as soon as i'm done.\n- Yes, I figured the only way was to avoid the module. It's a shame! Thanks for your insight and help on this.","metadata":{"transformedAt":"2026-08-18T18:33:07.867Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":89,"estimatedTokens":666}}441{"id":"stack-56502474","source":"stackoverflow","questionId":56502474,"title":"Nuxt: Inside a plugin, how to add dynamic script tag to head?","tags":["vue.js","nuxt.js","head","gtag.js"],"text":"Title: Nuxt: Inside a plugin, how to add dynamic script tag to head?\nTags: vue.js, nuxt.js, head, gtag.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build a Google Analytics plugin to Nuxt that will fetch tracking IDs from the CMS. I am really close I think.\n\nI have a plugin file loading on client side only. The plugin is loaded from `nuxt.config.js` via the `plugins:[{ src: '~/plugins/google-gtag.js', mode: 'client' }]` array.\n\nFrom there the main problem is that the gtag script needs the UA code in it's URL, so I can't just add that into the regular script object in `nuxt.config.js`. I need to get those UA codes from the store (which is hydrated form `nuxtServerInit`.\n\nSo I'm using `head.script.push` in the plugin to add the gtag script with the UA code in the URL. But that doesn't result in the script being added on first page load, but it does for all subsequent page transitions. So clearly I'm running `head.script.push` too late in the render of the page.\n\nBut I don't know how else to fetch tracking IDs, then add script's to the head.\n\n```\n// plugins/google.gtag.client.js with \"mode\": \"client\nexport default ({ store, app: { head, router, context } }, inject) => {\n // Remove any empty tracking codes\n const codes = store.state.siteMeta.gaTrackingCodes.filter(Boolean)\n\n // Add script tag to head\n head.script.push({\n src: `https://www.googletagmanager.com/gtag/js?id=${codes[0]}`,\n async: true\n })\n console.log('added script')\n\n // Include Google gtag code and inject it (so this.$gtag works in pages/components)\n window.dataLayer = window.dataLayer || []\n function gtag() {\n dataLayer.push(arguments)\n }\n inject('gtag', gtag)\n gtag('js', new Date())\n\n // Add tracking codes from Vuex store\n codes.forEach(code => {\n gtag('config', code, {\n send_page_view: false // necessary to avoid duplicated page track on first page load\n })\n\n console.log('installed code', code)\n\n // After each router transition, log page event to Google for each code\n router.afterEach(to => {\n gtag('event', 'page_view', { page_path: to.fullPath })\n console.log('afterEach', code)\n })\n })\n}\n```\n\n========================================\n\nCode:\n```js\n// plugins/google.gtag.client.js with \"mode\": \"client\nexport default ({ store, app: { head, router, context } }, inject) => {\n // Remove any empty tracking codes\n const codes = store.state.siteMeta.gaTrackingCodes.filter(Boolean)\n\n // Add script tag to head\n head.script.push({\n src: `https://www.googletagmanager.com/gtag/js?id=${codes[0]}`,\n async: true\n })\n console.log('added script')\n\n // Include Google gtag code and inject it (so this.$gtag works in pages/components)\n window.dataLayer = window.dataLayer || []\n function gtag() {\n dataLayer.push(arguments)\n }\n inject('gtag', gtag)\n gtag('js', new Date())\n\n // Add tracking codes from Vuex store\n codes.forEach(code => {\n gtag('config', code, {\n send_page_view: false // necessary to avoid duplicated page track on first page load\n })\n\n console.log('installed code', code)\n\n // After each router transition, log page event to Google for each code\n router.afterEach(to => {\n gtag('event', 'page_view', { page_path: to.fullPath })\n console.log('afterEach', code)\n })\n })\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nplugins:[{ src: '~/plugins/google-gtag.js', mode: 'client' }]\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nhead.script.push\n```\n\n```text\nhead.script.push\n```\n\n```js\nexport default ({ store, app: { router, context } }, inject) => {\n // Remove any empty tracking codes\n let codes = _get(store, \"state.siteMeta.gaTrackingCodes\", [])\n codes = codes.filter(Boolean)\n\n // Abort if no codes\n if (!codes.length) {\n if (context.isDev) console.log(\"No Google Anlaytics tracking codes set\")\n inject(\"gtag\", () => {})\n return\n }\n\n // Abort if in Dev mode, but inject dummy functions so $gtag events don't throw errors\n if (context.isDev) {\n console.log(\"No Google Anlaytics tracking becuase your are in Dev mode\")\n inject(\"gtag\", () => {})\n return\n }\n\n // Abort if we already added script to head\n let gtagScript = document.getElementById(\"gtag\")\n if (gtagScript) {\n return\n }\n\n // Add script tag to head\n let script = document.createElement(\"script\")\n script.async = true\n script.id = \"gtag\"\n script.src = \"//www.googletagmanager.com/gtag/js\"\n document.head.appendChild(script)\n\n // Include Google gtag code and inject it (so this.$gtag works in pages/components)\n window.dataLayer = window.dataLayer || []\n function gtag() {\n dataLayer.push(arguments)\n }\n inject(\"gtag\", gtag)\n gtag(\"js\", new Date())\n\n // Add tracking codes from Vuex store\n codes.forEach(code => {\n gtag(\"config\", code, {\n send_page_view: false // Necessary to avoid duplicated page track on first page load\n })\n\n // After each router transition, log page event to Google for each code\n router.afterEach(to => {\n gtag(\"event\", code, { page_path: to.fullPath })\n })\n })\n}\n```\n\n========================================\n\nComments:\n- If you look at the nuxt-community/google-tag repo, it uses a module to do the script push because modules are built before plugins.\n- @Ohgodwhy yeah that's actually where I got this from. So I need a plugin and a module then? It's not possible to do this just as a plugin? I'm not sure if a module can get access to the store either.\n- Indeed! The module will fire earlier in the life cycle than the plugin will, allowing you to inject into the head pre-compile whereas the plugin executes post-compile pre-bundle, which is most likely why you have this issue.\n- @Ohgodwhy thanks. Any tips on how I can access store in a module?\n- I have exactly the same problem. Did you found a solution for that?\n- @PhilippS. just posted the solution, thanks for the prompt.\n- This is also a good read: vueschool.io/articles/vuejs-tutorials/…\n- the router transition should be an `event` not `config`: `gtag(\"event\", \"page_view\", { page_path: to.fullPath })`.","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":184,"estimatedTokens":1556}}442{"id":"stack-57592604","source":"stackoverflow","questionId":57592604,"title":"How to change the bottom border color of a Vuetify v-overflow-btn?","tags":["css","vuetify.js","nuxt.js"],"text":"Title: How to change the bottom border color of a Vuetify v-overflow-btn?\nTags: css, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm actually building a website in nuxt.js using Vuetify. I have created a menu based on one `v-overflow-btn`, one `v-text-field` and one `v-btn`.\nHere is what my menu looks like actually.\n\nCause I'm a little bit maniac, I would like to change the bottom border color of my `v-overflow-btn` to match all the different dividers color bar of my menu. By default, the color is black.\n\nI already tried to define my own CSS in the style section as below:\n\n```\n\n v-overflow-btn {\n border-color:grey !important;\n }\n\n```\n\nBut nothing changes...\n\nCould someone behelp me to change this border color? Thanks in advance :)\n\n========================================\n\nTop Answer:\nI had to add the deep selector in case someone else is having this issue.\n\n```\n.nbb >>> .v-input__slot:before {\n border-color: white !important;\n}\n```\n\n========================================\n\nCode:\n```text\n<style>\n v-overflow-btn {\n border-color:grey !important;\n }\n</style>\n```\n\n```text\nv-overflow-btn\n```\n\n```text\nv-text-field\n```\n\n```text\nv-btn\n```\n\n```text\nv-overflow-btn\n```\n\n```text\n<style>\n .v-overflow-btn .v-input__slot::before {\n border-color: grey !important;\n }\n</style>\n```\n\n```text\n.nbb >>> .v-input__slot:before {\n border-color: white !important;\n}\n```\n\n========================================\n\nComments:\n- Working great! Thanks a lot :) I had tried the `.v-input__slot` but I had forgotten the `::before` --'\n- You are welcome. Btw if you accept this answer with the tick button next to it you'll earn few reputation points.","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":81,"estimatedTokens":416}}443{"id":"stack-44786962","source":"stackoverflow","questionId":44786962,"title":"How to set global mutation in module vuex js store","tags":["javascript","vuejs2","vuex","nuxt.js"],"text":"Title: How to set global mutation in module vuex js store\nTags: javascript, vuejs2, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI need to be able to change the state of the global variable `alert` from any Vuex module.\n\n**store/index.js**:\n\n```\nexport const state = () => ({\n alert: null \n})\n```\n\n**store/child.js**:\n\n```\nexport const mutations = {\n SET_ALERT: function (rootState, alert) {\n rootState.alert = alert\n }\n}\nexport const actions = {\n setalert({commit}){\n commit('SET_ALERT', 'warning')\n }\n}\n```\n\nI want to call `setalert` and set the global `store.state.alert` to `\"warning\"`. Currently, `store.state.child.alert` is getting set to `\"warning\"` instead.\n\n========================================\n\nCode:\n```text\nexport const state = () => ({\n alert: null \n})\n```\n\n```text\nexport const mutations = {\n SET_ALERT: function (rootState, alert) {\n rootState.alert = alert\n }\n}\nexport const actions = {\n setalert({commit}){\n commit('SET_ALERT', 'warning')\n }\n}\n```\n\n```text\nalert\n```\n\n```text\nsetalert\n```\n\n```text\nstore.state.alert\n```\n\n```text\n\"warning\"\n```\n\n```text\nstore.state.child.alert\n```\n\n```text\n\"warning\"\n```\n\n```text\ncommit('SET_ALERT', 'warning', { root: true });\n```\n\n```text\nSET_ALERT\n```\n\n```text\nchild\n```\n\n```text\nchild\n```\n\n```text\nrootState\n```\n\n```text\nSET_ALERT\n```\n\n```text\nindex.js\n```\n\n```text\nchild\n```\n\n```text\nsetalert\n```\n\n```text\nnamespace: true\n```\n\n```text\ncommit\n```\n\n========================================\n\nComments:\n- not work: i move mutation `SET_ALERT` into `index.js`, and now i get error `[vuex] unknown local mutation type: SET_ALERT, global type: articles/SET_ALERT`, any ideas?\n- Are you using namespacing?\n- `commit('SET_ALERT', 'warning', { root: true });` - thats great! Now IT WORK, thanks! I'm not sure I understand you, I only learn this `vuex` in `nuxt` + `express`.\n- can you give a link to the documentation where you found out about `{ root: true }`?\n- @ВасилийБуторин sure thing, added it to the answer","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":130,"estimatedTokens":500}}444{"id":"stack-63384869","source":"stackoverflow","questionId":63384869,"title":"How to make a .post with Axios (VueJS, Nuxt)","tags":["vue.js","axios","nuxt.js"],"text":"Title: How to make a .post with Axios (VueJS, Nuxt)\nTags: vue.js, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am new to web development. I would like to ask about how to create a `.post` with Axios using Nuxt.\n\nAll that I need is just a button that sends three inputs to the NodeJS app.\n\n```\n\n \n \n \n \n \n \n **Name:**\n \n **Email:**\n \n **Password:**\n \n Submit\n \n \n \n \n\n export default {\n data() {\n return {\n name: '',\n email: '',\n password: ''\n };\n },\n\n methods: {\n //Would like to use the button to do this:\n async sendData () {\n await this.$axios.get('insert', {\n name: this.name, \n email: this.email,\n password: this.password })\n }\n }\n }\n\n```\n\nThank you for the help.\n\n========================================\n\nTop Answer:\nYou could also import axios locally to your component and use it this way:\n\n```\n\n \n \n \n \n \n \n **Name:**\n \n **Email:**\n \n **Password:**\n \n Submit\n \n \n \n \n \n\nimport axios from 'axios'\nexport default {\n data() {\n return {\n name: '',\n email: '',\n password: ''\n };\n },\n\n methods: {\n //Would like to use the button to do this:\n async formSubmit() {\n await axios.post('route/url', {\n name: this.name, \n email: this.email,\n password: this.password\n })\n .then(response => {\n console.log(response)\n })\n .catch(err => {\n console.log(err)\n })\n }\n }\n}\n\n```\n\nDo not forget to call the `formSubmit` method to actually make a `POST` request.\n\nMoreover, your form does not seem to have a closing tag ``.\n\n========================================\n\nCode:\n```html\n<template>\n <div class=\"container\">\n <div class=\"row justify-content-center\">\n <div class=\"col-md-8\">\n <div class=\"card\">\n <div class=\"card-body\">\n <form @submit=\"formSubmit\">\n <strong>Name:</strong>\n <input type=\"text\" class=\"form-control\" v-model=\"name\">\n <strong>Email:</strong>\n <input type=\"text\" class=\"form-control\" v-model=\"email\">\n <strong>Password:</strong>\n <input type=\"text\" class=\"form-control\" v-model=\"password\">\n <button class=\"btn btn-success\">Submit</button>\n </div>\n </div>\n </div>\n </div>\n</template>\n\n<script>\n export default {\n data() {\n return {\n name: '',\n email: '',\n password: ''\n };\n },\n\n methods: {\n //Would like to use the button to do this:\n async sendData () {\n await this.$axios.get('insert', {\n name: this.name, \n email: this.email,\n password: this.password })\n }\n }\n }\n</script>\n```\n\n```text\n.post\n```\n\n```text\n<form @submit=\"sendData\">\n```\n\n```text\nthis.$axios.post('insert', {\n name: this.name, \n email: this.email,\n password: this.password \n})\n.then(function (response) {\n console.log(response);\n})\n.catch(function (error) {\n console.log(error);\n});\n```\n\n```text\nPOST\n```\n\n```text\n<template>\n <div class=\"container\">\n <div class=\"row justify-content-center\">\n <div class=\"col-md-8\">\n <div class=\"card\">\n <div class=\"card-body\">\n <form @submit=\"formSubmit\">\n <strong>Name:</strong>\n <input type=\"text\" class=\"form-control\" v-model=\"name\">\n <strong>Email:</strong>\n <input type=\"text\" class=\"form-control\" v-model=\"email\">\n <strong>Password:</strong>\n <input type=\"text\" class=\"form-control\" v-model=\"password\">\n <button class=\"btn btn-success\">Submit</button>\n </form>\n </div>\n </div>\n </div>\n </div>\n</template>\n\n<script>\nimport axios from 'axios'\nexport default {\n data() {\n return {\n name: '',\n email: '',\n password: ''\n };\n },\n\n methods: {\n //Would like to use the button to do this:\n async formSubmit() {\n await axios.post('route/url', {\n name: this.name, \n email: this.email,\n password: this.password\n })\n .then(response => {\n console.log(response)\n })\n .catch(err => {\n console.log(err)\n })\n }\n }\n}\n</script>\n```\n\n```text\nformSubmit\n```\n\n```text\nPOST\n```\n\n```text\n</form>\n```\n\n========================================\n\nComments:\n- Thanks, yes I need more practice apparently.","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":255,"estimatedTokens":1125}}445{"id":"stack-43017928","source":"stackoverflow","questionId":43017928,"title":"nuxt.js -> Howto configure production/development settings","tags":["nuxt.js"],"text":"Title: nuxt.js -> Howto configure production/development settings\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a nuxt.js project with feathers. The client and server are to different entities, you start them seperatly. The client uses nuxt.js. I want to configure production and development settings.\n\nCurrently my nuxt.config.js looks like this:\n\n```\nmodule.exports = {\n head: {\n title: \"SITE TITLE\"\n },\n env: {\n backendUrl: 'http://localhost:3001'\n }\n};\n```\n\nWhat I would like is that if I start the client with 'npm run dev' development setting are used. I would like to have e.g. a different header and different backendUrl.\n\n**Question**\n\nWhat do I need to do to implement this?\n\n========================================\n\nTop Answer:\nI would do that HninYuKo has suggested but take it a step further. Install https://github.com/nuxt-community/dotenv-module and add a .env file, so that it becomes accessible to you anywhere in your Nuxt.js codebase. You now have environment-specific files that you can customize on dev or production, in addition to being able to invoke environment-specific builds from the command line.\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n head: {\n title: \"SITE TITLE\"\n },\n env: {\n backendUrl: 'http://localhost:3001'\n }\n};\n```\n\n```text\nconst config = {\n test: process.env.NODE_ENV !== 'production' ? 'devdevdevelopment' : 'proproproduction',\n apiserver: process.env.NODE_ENV !== 'production' ? 'developement apiserver' : 'production vbvbvbvbv apiserver',\n}\nmodule.exports = {\n env: {\n dev:config.test,\n server:config.apiserver\n },\n}\n```\n\n========================================\n\nComments:\n- If you want to use as production , you need to run `npm run build` and `npm run start`\n- If you want to do External Configuration check this link I'm ok with it . github.com/awronski/nuxtjs-examples/tree/master/…\n- And what happens if you have more than just development and production environments?\n- @Chris You make the chain deeper, e.g.: `test: process.env.NODE_ENV !== 'production' ? 'something' : process.env.NODE_ENV !== 'dev1' ? 'something1' : 'something2',`.","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":65,"estimatedTokens":549}}446{"id":"stack-65713431","source":"stackoverflow","questionId":65713431,"title":"How to add \"text/javascript\" to in Nuxt","tags":["nuxt.js"],"text":"Title: How to add \"text/javascript\" to in Nuxt\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have the following script I have to add in the `` tag. But in Nuxt I have to add it as an objext in nuxt.config.js.\n\nHow do I do this?\n\n```\n\n /* To enable Participant Auto Authentication, uncomment this code below (https://docs.growsurf.com/getting-started/participant-auto-authentication) */\n /*\n window.grsfConfig = {\n email: \"participant@email.com\",// Replace this with the participant's email address\n hash: \"HASH_VALUE\" // Replace this with the SHA-256 HMAC value\n };\n */\n (function(g,r,s,f){g.grsfSettings={campaignId:\"mpw47p\",version:\"2.0.0\"};s=r.getElementsByTagName(\"head\")[0];f=r.createElement(\"script\");f.async=1;f.src=\"https://app.growsurf.com/growsurf.js\"+\"?v=\"+g.grsfSettings.version;f.setAttribute(\"grsf-campaign\", g.grsfSettings.campaignId);!g.grsfInit?s.appendChild(f):\"\";})(window,document);\n\n```\n\n========================================\n\nTop Answer:\nThe right way in Nuxt is to create your own plugin for GrowSurf (see nuxt plugin docs).\n\nFirst, create your plugin in a new file `plugins/growsurf.js`:\n\n```\n/* eslint-disable */\n\nexport default ({ app }) => {\n /*\n ** Only run on client-side and only in production mode\n */\n if (process.env.NODE_ENV !== 'production') {\n return;\n }\n\n /* To enable Participant Auto Authentication, uncomment this code below (https://docs.growsurf.com/getting-started/participant-auto-authentication) */\n /*\n window.grsfConfig = {\n email: \"participant@email.com\",// Replace this with the participant's email address\n hash: \"HASH_VALUE\" // Replace this with the SHA-256 HMAC value\n };\n */\n (function(g,r,s,f){g.grsfSettings={campaignId:\"mpw47p\",version:\"2.0.0\"};s=r.getElementsByTagName(\"head\")[0];f=r.createElement(\"script\");f.async=1;f.src=\"https://app.growsurf.com/growsurf.js\"+\"?v=\"+g.grsfSettings.version;f.setAttribute(\"grsf-campaign\", g.grsfSettings.campaignId);!g.grsfInit?s.appendChild(f):\"\";})(window,document);\n\n}\n```\n\nThen tell Nuxt to import it in your main application:\n\n```\n// nuxt.config.js\n\nexport default {\n plugins: [{ src: '~plugins/growsurf.js', mode: 'client' }]\n}\n```\n\nIn addition, you can find a similar example for Google Analytics in the official Nuxt FAQ: https://nuxtjs.org/faq/ga\n\n========================================\n\nCode:\n```html\n<script type=\"text/javascript\">\n /* To enable Participant Auto Authentication, uncomment this code below (https://docs.growsurf.com/getting-started/participant-auto-authentication) */\n /*\n window.grsfConfig = {\n email: \"participant@email.com\",// Replace this with the participant's email address\n hash: \"HASH_VALUE\" // Replace this with the SHA-256 HMAC value\n };\n */\n (function(g,r,s,f){g.grsfSettings={campaignId:\"mpw47p\",version:\"2.0.0\"};s=r.getElementsByTagName(\"head\")[0];f=r.createElement(\"script\");f.async=1;f.src=\"https://app.growsurf.com/growsurf.js\"+\"?v=\"+g.grsfSettings.version;f.setAttribute(\"grsf-campaign\", g.grsfSettings.campaignId);!g.grsfInit?s.appendChild(f):\"\";})(window,document);\n</script>\n```\n\n```text\n<head>\n```\n\n```js\nexport default{\n head(){\n return {\n script: [\n {\n type:'text/javascript',\n innerHTML: `/* To enable Participant Auto Authentication, uncomment this code below (https://docs.growsurf.com/getting-started/participant-auto-authentication) */\n /*\n window.grsfConfig = {\n email: \"participant@email.com\",// Replace this with the participant's email address\n hash: \"HASH_VALUE\" // Replace this with the SHA-256 HMAC value\n };\n */\n (function(g,r,s,f){g.grsfSettings={campaignId:\"mpw47p\",version:\"2.0.0\"};s=r.getElementsByTagName(\"head\")[0];f=r.createElement(\"script\");f.async=1;f.src=\"https://app.growsurf.com/growsurf.js\"+\"?v=\"+g.grsfSettings.version;f.setAttribute(\"grsf-campaign\", g.grsfSettings.campaignId);!g.grsfInit?s.appendChild(f):\"\";})(window,document);`\n }\n ]\n }\n }\n}\n```\n\n```js\nmodule.exports = {\n head: {\n script: [\n {\n type:'text/javascript',\n innerHTML: `/* To enable Participant Auto Authentication, uncomment this code below (https://docs.growsurf.com/getting-started/participant-auto-authentication) */\n /*\n window.grsfConfig = {\n email: \"participant@email.com\",// Replace this with the participant's email address\n hash: \"HASH_VALUE\" // Replace this with the SHA-256 HMAC value\n };\n */\n (function(g,r,s,f){g.grsfSettings={campaignId:\"mpw47p\",version:\"2.0.0\"};s=r.getElementsByTagName(\"head\")[0];f=r.createElement(\"script\");f.async=1;f.src=\"https://app.growsurf.com/growsurf.js\"+\"?v=\"+g.grsfSettings.version;f.setAttribute(\"grsf-campaign\", g.grsfSettings.campaignId);!g.grsfInit?s.appendChild(f):\"\";})(window,document);`\n }\n ]\n }\n};\n```\n\n```html\n<!DOCTYPE html>\n<html {{ HTML_ATTRS }}>\n <head {{ HEAD_ATTRS }}>\n {{ HEAD }}\n<script type=\"text/javascript\">\n /* To enable Participant Auto Authentication, uncomment this code below (https://docs.growsurf.com/getting-started/participant-auto-authentication) */\n /*\n window.grsfConfig = {\n email: \"participant@email.com\",// Replace this with the participant's email address\n hash: \"HASH_VALUE\" // Replace this with the SHA-256 HMAC value\n };\n */\n (function(g,r,s,f){g.grsfSettings={campaignId:\"mpw47p\",version:\"2.0.0\"};s=r.getElementsByTagName(\"head\")[0];f=r.createElement(\"script\");f.async=1;f.src=\"https://app.growsurf.com/growsurf.js\"+\"?v=\"+g.grsfSettings.version;f.setAttribute(\"grsf-campaign\", g.grsfSettings.campaignId);!g.grsfInit?s.appendChild(f):\"\";})(window,document);\n</script>\n </head>\n <body {{ BODY_ATTRS }}>\n {{ APP }}\n </body>\n</html>\n```\n\n```text\nhead()\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nindex.html\n```\n\n```js\n/* eslint-disable */\n\nexport default ({ app }) => {\n /*\n ** Only run on client-side and only in production mode\n */\n if (process.env.NODE_ENV !== 'production') {\n return;\n }\n\n /* To enable Participant Auto Authentication, uncomment this code below (https://docs.growsurf.com/getting-started/participant-auto-authentication) */\n /*\n window.grsfConfig = {\n email: \"participant@email.com\",// Replace this with the participant's email address\n hash: \"HASH_VALUE\" // Replace this with the SHA-256 HMAC value\n };\n */\n (function(g,r,s,f){g.grsfSettings={campaignId:\"mpw47p\",version:\"2.0.0\"};s=r.getElementsByTagName(\"head\")[0];f=r.createElement(\"script\");f.async=1;f.src=\"https://app.growsurf.com/growsurf.js\"+\"?v=\"+g.grsfSettings.version;f.setAttribute(\"grsf-campaign\", g.grsfSettings.campaignId);!g.grsfInit?s.appendChild(f):\"\";})(window,document);\n\n}\n```\n\n```js\n// nuxt.config.js\n\nexport default {\n plugins: [{ src: '~plugins/growsurf.js', mode: 'client' }]\n}\n```\n\n```text\nplugins/growsurf.js\n```\n\n========================================\n\nComments:\n- I tried your solution with head(), but I'm getting unescaped quotation marks in the rendered HTML","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":199,"estimatedTokens":1737}}447{"id":"stack-52073581","source":"stackoverflow","questionId":52073581,"title":"Why nuxt-i18n module doesn't seem to be loaded? ( _vm.$t is not a function)","tags":["javascript","internationalization","nuxt.js"],"text":"Title: Why nuxt-i18n module doesn't seem to be loaded? ( _vm.$t is not a function)\nTags: javascript, internationalization, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSo I came to work on my project today and I got greated by this error with nuxt.js.\n\nI removed node_modules and .nuxt folder, reissue a `yarn install` but I still have this error, `_vm.$t is not a function`.\n\nWhere does it come from?\n\nI also got some `_vm.localePath is not a function`...\n\nI made sure it was in my modules too:\n\n```\nmodules: [\n ['nuxt-i18n', {\n locales: [\n { code: 'en', iso: 'en-US', name:'English', file: 'en-US.json' },\n { code: 'fr', iso: 'fr-FR', name:'Français', file: 'fr.js' },\n // { code: 'es', iso: 'es-ES', name:'English', file: 'es.js' }\n ],\n defaultLocale: 'en',\n // strategy: 'prefix_and_default',\n lazy: true,\n langDir: 'i18n/',\n // By default, custom routes are extracted from page files using acorn parsing,\n // set this to false to disable this\n parsePages: true,\n\n }],\n...\n```\n\nThanks!\n\nEDIT: Here's my package.json file:\n\n```\n{\n \"name\": \"myproj\",\n \"version\": \"1.0.0\",\n \"description\": \"My classy Nuxt.js project\",\n \"author\": \"\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"cross-env NODE_ENV=development nodemon server/index.js --watch server\",\n \"build\": \"nuxt build\",\n \"start\": \"cross-env NODE_ENV=production node server/index.js\",\n \"generate\": \"nuxt generate\",\n \"lint\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"precommit\": \"npm run lint\"\n },\n \"dependencies\": {\n \"@fortawesome/fontawesome-svg-core\": \"^1.2.2\",\n \"@fortawesome/pro-light-svg-icons\": \"^5.2.0\",\n \"@nuxtjs/axios\": \"^5.0.0\",\n \"fastify\": \"^1.11.0\",\n \"iview\": \"^3.0.1\",\n \"koa\": \"^2.3.0\",\n \"nuxt\": \"^1.0.0\",\n \"nuxt-fontawesome\": \"^0.3.0\",\n \"nuxt-i18n\": \"^5.2.1\",\n \"pg\": \"^7.4.3\",\n \"vuetify\": \"^1.0.19\"\n },\n \"devDependencies\": {\n \"babel-eslint\": \"^8.2.1\",\n \"cross-env\": \"^5.0.1\",\n \"eslint\": \"^5.0.1\",\n \"eslint-loader\": \"^2.0.0\",\n \"eslint-plugin-vue\": \"^4.0.0\",\n \"nodemon\": \"^1.11.0\",\n \"stylus\": \"^0.54.5\",\n \"stylus-loader\": \"^3.0.1\"\n }\n}\n```\n\nKoa and Vuetify will be replaced by fastify and iview, that is why they are there. \n\nAs spotted in the comments, nuxt is version 1.0.0 for a strange reason. I upgraded the package to nuxt 1.4.2. I still have the same issue.\n\nComplete stack trace:\n\n```\nServer listening on http://127.0.0.1:3000\n[Vue warn]: Property or method \"localePath\" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.\n\nfound in\n\n---> at layouts/default.vue\n \n[Vue warn]: Error in render: \"TypeError: _vm.localePath is not a function\"\n\nfound in\n\n---> at layouts/default.vue\n \n{ TypeError: _vm.localePath is not a function\n at Proxy.render (layouts/default.vue?2d02:32:0)\n at VueComponent.Vue._render (/media/drive/srv/node/ooo/node_modules/vue/dist/vue.runtime.common.js:4542:22)\n at renderComponentInner (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7532:25)\n at renderComponent (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7502:5)\n at RenderContext.renderNode (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7418:5)\n at RenderContext.next (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:2436:14)\n at cachedWrite (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:2295:9)\n at renderElement (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7656:5)\n at renderNode (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7420:5)\n at renderComponentInner (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7538:3)\n at renderComponent (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7502:5)\n at RenderContext.renderNode (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7418:5)\n at RenderContext.next (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:2436:14)\n at RenderContext.next (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:2449:12)\n at cachedWrite (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:2295:9)\n at renderElement (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7646:5) statusCode: 500, name: 'TypeError' }\n```\n\n========================================\n\nCode:\n```text\nmodules: [\n ['nuxt-i18n', {\n locales: [\n { code: 'en', iso: 'en-US', name:'English', file: 'en-US.json' },\n { code: 'fr', iso: 'fr-FR', name:'Français', file: 'fr.js' },\n // { code: 'es', iso: 'es-ES', name:'English', file: 'es.js' }\n ],\n defaultLocale: 'en',\n // strategy: 'prefix_and_default',\n lazy: true,\n langDir: 'i18n/',\n // By default, custom routes are extracted from page files using acorn parsing,\n // set this to false to disable this\n parsePages: true,\n\n }],\n...\n```\n\n```text\n{\n \"name\": \"myproj\",\n \"version\": \"1.0.0\",\n \"description\": \"My classy Nuxt.js project\",\n \"author\": \"\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"cross-env NODE_ENV=development nodemon server/index.js --watch server\",\n \"build\": \"nuxt build\",\n \"start\": \"cross-env NODE_ENV=production node server/index.js\",\n \"generate\": \"nuxt generate\",\n \"lint\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"precommit\": \"npm run lint\"\n },\n \"dependencies\": {\n \"@fortawesome/fontawesome-svg-core\": \"^1.2.2\",\n \"@fortawesome/pro-light-svg-icons\": \"^5.2.0\",\n \"@nuxtjs/axios\": \"^5.0.0\",\n \"fastify\": \"^1.11.0\",\n \"iview\": \"^3.0.1\",\n \"koa\": \"^2.3.0\",\n \"nuxt\": \"^1.0.0\",\n \"nuxt-fontawesome\": \"^0.3.0\",\n \"nuxt-i18n\": \"^5.2.1\",\n \"pg\": \"^7.4.3\",\n \"vuetify\": \"^1.0.19\"\n },\n \"devDependencies\": {\n \"babel-eslint\": \"^8.2.1\",\n \"cross-env\": \"^5.0.1\",\n \"eslint\": \"^5.0.1\",\n \"eslint-loader\": \"^2.0.0\",\n \"eslint-plugin-vue\": \"^4.0.0\",\n \"nodemon\": \"^1.11.0\",\n \"stylus\": \"^0.54.5\",\n \"stylus-loader\": \"^3.0.1\"\n }\n}\n```\n\n```text\nServer listening on http://127.0.0.1:3000\n[Vue warn]: Property or method \"localePath\" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.\n\nfound in\n\n---> <Default> at layouts/default.vue\n <Root>\n[Vue warn]: Error in render: \"TypeError: _vm.localePath is not a function\"\n\nfound in\n\n---> <Default> at layouts/default.vue\n <Root>\n{ TypeError: _vm.localePath is not a function\n at Proxy.render (layouts/default.vue?2d02:32:0)\n at VueComponent.Vue._render (/media/drive/srv/node/ooo/node_modules/vue/dist/vue.runtime.common.js:4542:22)\n at renderComponentInner (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7532:25)\n at renderComponent (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7502:5)\n at RenderContext.renderNode (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7418:5)\n at RenderContext.next (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:2436:14)\n at cachedWrite (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:2295:9)\n at renderElement (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7656:5)\n at renderNode (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7420:5)\n at renderComponentInner (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7538:3)\n at renderComponent (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7502:5)\n at RenderContext.renderNode (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7418:5)\n at RenderContext.next (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:2436:14)\n at RenderContext.next (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:2449:12)\n at cachedWrite (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:2295:9)\n at renderElement (/media/drive/srv/node/ooo/node_modules/vue-server-renderer/build.js:7646:5) statusCode: 500, name: 'TypeError' }\n```\n\n```text\nyarn install\n```\n\n```text\n_vm.$t is not a function\n```\n\n```text\n_vm.localePath is not a function\n```\n\n```js\nconst wrapper = mount(MyComponent, {\n mocks: {\n // Always returns the input\n $t: i => i,\n localePath: i => i\n }\n});\n```\n\n```js\n// https://github.com/nuxt/nuxt.js/issues/4115\nimport Vue from 'vue'\nimport { config } from '@vue/test-utils'\n\nVue.config.silent = true\n\n// Mock Nuxt components\nconfig.stubs['nuxt-link'] = true; // string stabs like '<a><slot /></a>' are now depreciated\nconfig.stubs['no-ssr'] = true;\nconfig.mocks.$t = i => i;\nconfig.mocks.localePath = i => i;\n```\n\n```text\nmodule.exports = {\n setupFiles: [\n '<rootDir>/tests/jest.setup.js'\n ],\n moduleNameMapper: {\n '^@/(.*)$': '<rootDir>/$1',\n '^~/(.*)$': '<rootDir>/$1',\n '^vue$': 'vue/dist/vue.common.js'\n },\n moduleFileExtensions: ['js', 'vue', 'json'],\n transform: {\n '^.+\\\\.js$': 'babel-jest',\n '.*\\\\.(vue)$': 'vue-jest'\n },\n collectCoverage: true,\n collectCoverageFrom: [\n '<rootDir>/components/**/*.vue',\n '<rootDir>/pages/**/*.vue'\n ],\n testPathIgnorePatterns: [\n 'node_modules',\n 'cypress',\n ],\n}\n```\n\n```text\n./tests/jest.setup.js\n```\n\n```text\n./jest.config.js\n```\n\n========================================\n\nComments:\n- Show your packages file\n- Oops, of course, edited.\n- @Aldarund do you see an issue? :\\ (I forgot to tag you earlier)\n- Nuxt version that installed is 1.0.0 or 1.4.1 ?\n- @Aldarund, it's suppose to be 1.4.1 as I cloned from github.com/nuxt-community/create-nuxt-app but indeed this file says 1.0.0. I'll try upgrading this.\n- I just ended up spending an hour recreating the project and transferring everything over. It works...\n- @HypeWolf I have the same error , how did you solve it ?\n- How does this answer resolve the issue? I actually have the same problem as in the question itself and there is nothing mentioned about a test. Is there any solution yet when I DONT want to mock the $t method?","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":298,"estimatedTokens":2573}}448{"id":"stack-72775878","source":"stackoverflow","questionId":72775878,"title":"Nuxt : @click does not work with Nuxt-link","tags":["vue.js","nuxt.js"],"text":"Title: Nuxt : @click does not work with Nuxt-link\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am expecting to include on my web application an effect that underlines the section where we are in the list of sections.\nI am working with Nuxt.\n\nI don't know why the following code does not change the value of the boolean `isActive`.\n\n```\n\n```\n\n```\nmethods: {\n selectSeason(filter) {\n this.$router.push(`${this.path}/${filter}`)\n },\n toggleUnderline() {\n this.isActive = !this.isActive\n }\n},\n```\n\n========================================\n\nTop Answer:\nSame as router-link, you need to use `v-on:click.native`\n\n```\n\n```\n\nHow do we v-on:click nuxt-link?\n\n========================================\n\nCode:\n```html\n<nuxt-link\n :to=\"`${path}/${filterItem.filter}`\"\n :style='{\"text-decoration\": (isActive ? \"underline\" : \"none\")}'\n @click=\"selectSeason(filterItem.filter) toggleUnderline()\" >\n```\n\n```js\nmethods: {\n selectSeason(filter) {\n this.$router.push(`${this.path}/${filter}`)\n },\n toggleUnderline() {\n this.isActive = !this.isActive\n }\n},\n```\n\n```text\nisActive\n```\n\n```html\n<template>\n <nuxt-link to=\"/about\" :custom=\"true\">\n <a @click=\"test\">go to about page</a>\n </nuxt-link>\n</template>\n\n<script>\nexport default {\n methods: {\n test() {\n console.log('called test method')\n },\n },\n}\n</script>\n```\n\n```text\nbutton\n```\n\n```text\n<NuxtLink>\n```\n\n```text\nclass=\"router-link-active router-link-exact-active\"\n```\n\n```html\n<nuxt-link\n :to=\"`${path}/${filterItem.filter}`\"\n :style='{\"text-decoration\": (isActive ? \"underline\" : \"none\")}'\n @click.native=\"selectSeason(filterItem.filter) toggleUnderline()\" \n>\n</nuxt-link>\n```\n\n```text\nv-on:click.native\n```\n\n```html\n<script lang=\"ts\" setup>\n const anyFunction = () => {\n console.log('easy')\n }\n</script>\n\n<template>\n <NuxtLink\n :to=\"'/'\"\n @click.prevent=\"anyFunction()\"\n >easy</NuxtLink>\n</template>\n```\n\n========================================\n\nComments:\n- Nuxt link have its own class active and you can use it to change style.\n- A link is supposed to make you move, not trigger an action. Use a `button` for that purpose.\n- Also, please try to use it like `selectSeason(filterItem.filter); toggleUnderline()`, with a `;` in between the 2 methods.\n- That worked! thank you\n- @stephenstrange Your welcome .","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":127,"estimatedTokens":576}}449{"id":"stack-72952665","source":"stackoverflow","questionId":72952665,"title":"vue/no-v-model-argument 'v-model' directives require no argument.eslint-plugin-vue","tags":["vue.js","nuxt.js"],"text":"Title: vue/no-v-model-argument 'v-model' directives require no argument.eslint-plugin-vue\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to display firstname and lastname through Introduction.vue. In InformationField.vue i am declaring the props. and calling them in Introduction.vue by v-model:propsname =\"form.introduction.propsname\" . i am getting error inside **Introduction.vue**\n\n```\n\n \n \n \n\nimport InformationField from './InformationField.vue';\nexport default {\n components: {\n InformationField,\n },\n setup(){\n const form = ref({\n introduction:{\n firstname: '',\n lastname: '',\n }\n })\n }\n};\n\n```\n\n**InformationField.vue**\n\n```\n\n \n \n Firstname\n \n \n \n Lastname\n \n \n \n\nexport default {\n props: {\n firstname: {\n type: String,\n default: \"\",\n },\n lastname: {\n type: String,\n default: \"\",\n }\n },\n};\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <form>\n <InformationField\n v-model:firstname=\"form.introduction.firstname\"\n v-model:lastname=\"form.introduction.lastname\"\n />\n </form>\n</template>\n\n<script>\nimport InformationField from './InformationField.vue';\nexport default {\n components: {\n InformationField,\n },\n setup(){\n const form = ref({\n introduction:{\n firstname: '',\n lastname: '',\n }\n })\n }\n};\n</script>\n```\n\n```text\n<template>\n <div>\n <label>\n Firstname\n <input\n type=\"text\"\n @input=\"$emit('update:firstname', $event.target.value)\"\n :value=\"firstname\"\n ref=\"firstnameRef\"\n placeholder=\"firstname\"\n />\n </label>\n <label>\n Lastname\n <input\n type=\"text\"\n @input=\"$emit('update:lastname', $event.target.value)\"\n :value=\"lastname\"\n placeholder=\"lastname\"\n />\n </label>\n </div>\n</template>\n\n<script>\nexport default {\n props: {\n firstname: {\n type: String,\n default: \"\",\n },\n lastname: {\n type: String,\n default: \"\",\n }\n },\n};\n</script>\n```\n\n```text\n\"vue/no-v-model-argument\": \"off\"\n```\n\n```text\nrules\n```\n\n```text\n.eslintrc.js\n```\n\n========================================\n\nComments:\n- Should firstname and lastname really be separate? If they aren't, they could be stored in a single object. Otherwise disable the rule, it's harmful.\n- Thanks @EstusFlask for your comment, Actually like firstname and last there will be more fields like these, so i have to make them separate.\n- I mean that you could do `v-model=\"form.introduction\"` in case it acts as form model\n- Hi @EstusFlask, then it is showing error in v-model(syntax error)\n- I'm not sure what the error refers to and what it looks like in your case. But it's supposed to be simple and documented syntax. Any way, that's the point. You don't need multiple named v-model directives if you can easily end up with default v-model only, that's what this linter rule is about\n- In my case I was using vue 2 rofl","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":153,"estimatedTokens":737}}450{"id":"stack-66444681","source":"stackoverflow","questionId":66444681,"title":"Nuxt: how to explicitly name JS chunks?","tags":["vue.js","nuxt.js"],"text":"Title: Nuxt: how to explicitly name JS chunks?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using `Nuxt` in static site generation mode. One requirement in my project is to deploy only certain routes, each with their respective assets.\n\nBut `Nuxt` gives chunks random names like `925446d.js`.\n\nSo I created a manual `router.js` and specified chunk names while importing my components:\n\n```\ncomponent: () => import(/* webpackChunkName: \"about\" */ '~/pages/about.vue').then(m => m.default || m)\n```\n\nBut `Nuxt` doesn't take my chunk names into account and continues to give chunks random names, making it super difficult to single out which chunk goes with which route.\n\nAny suggestion?\n\n========================================\n\nCode:\n```js\ncomponent: () => import(/* webpackChunkName: \"about\" */ '~/pages/about.vue').then(m => m.default || m)\n```\n\n```text\nNuxt\n```\n\n```text\nNuxt\n```\n\n```text\n925446d.js\n```\n\n```text\nrouter.js\n```\n\n```text\nNuxt\n```\n\n```js\n{\n // ...\n build: { filenames: { chunk: () => '[name].js' } }\n}\n```\n\n```text\nfilename\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- It looks like the correct way of writting things. Do you see it in the network tab ? Did you tried it in a basic component/page and see if it changes anything ?\n- You're the man! One thing, in the doc they warn \"Be careful when using non-hashed based filenames in production as most browsers will cache the asset and not detect the changes on first load.\" Any idea how to work around this issue with `Nuxt.js`?\n- @drake035 You probably still can add the hash after the name. `[name]_[contenthash].js` What matters here is that the filename is different so it's not cached by the browser.","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":67,"estimatedTokens":433}}451{"id":"stack-55986158","source":"stackoverflow","questionId":55986158,"title":"How to save JWT Token in Vuex with Nuxt Auth Module?","tags":["express","authentication","jwt","nuxt.js","bearer-token"],"text":"Title: How to save JWT Token in Vuex with Nuxt Auth Module?\nTags: express, authentication, jwt, nuxt.js, bearer-token\nSource: Stack Overflow\n\nQuestion:\nI am currently trying to convert a VueJS page to NuxtJS with VueJS. Unfortunately I have some problems with authenticating the user and I can't find a solution in Google. I only use Nuxt for the client. The API is completely separate in express and works with the existing VueJS site.\n\nIn Nuxt I send now with the Auth module a request with username and password to my express Server/Api. The Api receives the data, checks it, and finds the account in MongoDB. This works exactly as it should. Or as I think it should. Now I take the user object and generate the jwt from it. I can debug everything up to here and it works.\nNow I probably just don't know how to keep debugging it. I send an answer with res.json(user, token) back to the Nuxt client (code follows below). As I said, in my current VueJS page I can handle this as well. Also in the Nuxt page I see the answer in the dev console and to my knowledge the answer fits.\n\nNow some code.\nThe login part on the express Api:\n\n const User = require('../models/User')\n const jwt = require('jsonwebtoken')\n const config = require('../config/config')\n\n function jwtSignUser(user){\n const ONE_YEAR = 60 * 60 * 24 * 365\n return jwt.sign(user,config.authentication.jwtSecret, {\n expiresIn: ONE_YEAR\n })\n }\n module.exports = {\n async login (req, res){\n console.log(req.body)\n try{\n const {username, password} = req.body\n const user = await User.findOne({\n username: username\n })\n\n if(!user){\n return res.status(403).send({\n error: `The login information was incorrect.`\n })\n }\n\n const isPasswordValid = await user.comparePassword(password)\n if(!isPasswordValid) {\n return res.status(403).send({\n error: `The login information was incorrect.`\n })\n }\n\n const userJson = user.toJSON()\n res.json({\n user: userJson,\n token: jwtSignUser(userJson)\n })\n\n } catch (err) {\n console.log(err)\n res.status(500).send({\n error: `An error has occured trying to log in.`\n })\n }\n }\n }\n\nnuxt.config.js:\n\n auth: {\n strategies: {\n local: {\n endpoints: {\n login: {url: '/login', method: 'post' },\n user: {url: '/user', method: 'get' },\n logout: false,\n }\n }\n },\n redirect: {\n login: '/profile',\n logout: '/',\n user: '/profile',\n callback:'/'\n }\n }\n\neven tried it with nearly any possible \"propertyName\".\n\nand, last but not least, the method on my login.vue:\n\n async login() {\n try {\n console.log('Logging in...')\n await this.$auth.loginWith('local', {\n data: {\n \"username\": this.username,\n \"password\": this.password\n }\n }).catch(e => {\n console.log('Failed Logging In');\n })\n if (this.$auth.loggedIn) {\n console.log('Successfully Logged In');\n }\n }catch (e) { \n console.log('Username or Password wrong');\n console.log('Error: ', e);\n }\n }\n\nWhat I really don't understand here... I always get \"Loggin in...\" displayed in the console. None of the error messages.\n\nI get 4 new entries in the \"Network\" Tag in Chrome Dev Tools every time I make a request (press the Login Button). Two times \"login\" and directly afterwards two times \"user\".\n\nThe first \"login\" entry is as (in the General Headers):\n\nRequest URL: http://localhost:3001/login\nRequest Method: OPTIONS\nStatus Code: 204 No Content\nRemote Address: [::1]:3001\nReferrer Policy: no-referrer-when-downgrade\n\nThe first \"user\" entry:\n\nRequest URL: http://localhost:3001/user\nRequest Method: OPTIONS\nStatus Code: 204 No Content\nRemote Address: [::1]:3001\nReferrer Policy: no-referrer-when-downgrade\n\nBoth without any Response.\n\nThe second login entry:\n\nRequest URL: http://localhost:3001/login\nRequest Method: POST\nStatus Code: 200 OK\nRemote Address: [::1]:3001\nReferrer Policy: no-referrer-when-downgrade\n\nand the Response is the object with the token and the user object.\n\nThe second user entry:\n\nRequest URL: http://localhost:3001/user\nRequest Method: GET\nStatus Code: 200 OK\nRemote Address: [::1]:3001\nReferrer Policy: no-referrer-when-downgrade\n\nand the Response is the user object.\n\nI think for the login should only the login request be relevant, or I'm wrong? And the user request works because the client has asked for the user route and the user route, always send the answer with the actual user object in my Express API.\n\nBecause I think, the problem is in the login response? Here some screenshots from the Network Tab in Chrome Dev Tools with the Request/Response for login.\n\nFirst login request without response\n\nSecond login request\n\nResponse to second login request\n\nDo I have to do something with my Vuex Store? I never found any configured Vuex Stores in examples for using the Auth Module while using google so I thougt I do not have to change here anything.\n\nThats my Vuex Store (Vue Dev Tools in Chrome) after trying to login without success:\n\n{\"navbar\":false,\"token\":null,\"user\":null,\"isUserLoggedIn\":false,\"access\":false,\"auth\":{\"user\":\"__vue_devtool_undefined__\",\"loggedIn\":false,\"strategy\":\"local\",\"busy\":false},\"feedType\":\"popular\"}\n\nThere is also some logic I use for my actual VueJS site. I will remove that when the Auth Module is working.\n\nAsked by @imreBoersma :\nMy /user endpoint on Express looks like:\n\n app.get('/user', \n isAuthenticated,\n UsersController.getUser)\n\nI first check if the User is authenticated:\n\n const passport = require('passport')\n\n module.exports = function (req, res, next) {\n passport.authenticate('jwt', function (err, user) {\n if(err || !user) {\n res.status(403).send({\n error: 'You are not authorized to do this.'\n })\n } else {\n req.user = user\n next()\n }\n })(req, res, next)\n }\n\nAfter that I search the User document in MongoDB and send the document to the client:\n\n const User = require('../models/User')\n\n module.exports = {\n [...]\n getUser (req, res) {\n User.findById(req.user._id, function (error, user){\n if (error) { console.error(error); }\n res.send(user)\n })\n }\n [...]\n\n }\n\nFeel free to ask for more information.\n\n========================================\n\nCode:\n```text\nconst User = require('../models/User')\n const jwt = require('jsonwebtoken')\n const config = require('../config/config')\n\n function jwtSignUser(user){\n const ONE_YEAR = 60 * 60 * 24 * 365\n return jwt.sign(user,config.authentication.jwtSecret, {\n expiresIn: ONE_YEAR\n })\n }\n module.exports = {\n async login (req, res){\n console.log(req.body)\n try{\n const {username, password} = req.body\n const user = await User.findOne({\n username: username\n })\n\n if(!user){\n return res.status(403).send({\n error: `The login information was incorrect.`\n })\n }\n\n const isPasswordValid = await user.comparePassword(password)\n if(!isPasswordValid) {\n return res.status(403).send({\n error: `The login information was incorrect.`\n })\n }\n\n const userJson = user.toJSON()\n res.json({\n user: userJson,\n token: jwtSignUser(userJson)\n })\n\n } catch (err) {\n console.log(err)\n res.status(500).send({\n error: `An error has occured trying to log in.`\n })\n }\n }\n }\n```\n\n```text\nauth: {\n strategies: {\n local: {\n endpoints: {\n login: {url: '/login', method: 'post' },\n user: {url: '/user', method: 'get' },\n logout: false,\n }\n }\n },\n redirect: {\n login: '/profile',\n logout: '/',\n user: '/profile',\n callback:'/'\n }\n }\n```\n\n```text\nasync login() {\n try {\n console.log('Logging in...')\n await this.$auth.loginWith('local', {\n data: {\n \"username\": this.username,\n \"password\": this.password\n }\n }).catch(e => {\n console.log('Failed Logging In');\n })\n if (this.$auth.loggedIn) {\n console.log('Successfully Logged In');\n }\n }catch (e) { \n console.log('Username or Password wrong');\n console.log('Error: ', e);\n }\n }\n```\n\n```text\nRequest URL: http://localhost:3001/login\nRequest Method: OPTIONS\nStatus Code: 204 No Content\nRemote Address: [::1]:3001\nReferrer Policy: no-referrer-when-downgrade\n```\n\n```text\nRequest URL: http://localhost:3001/user\nRequest Method: OPTIONS\nStatus Code: 204 No Content\nRemote Address: [::1]:3001\nReferrer Policy: no-referrer-when-downgrade\n```\n\n```text\nRequest URL: http://localhost:3001/login\nRequest Method: POST\nStatus Code: 200 OK\nRemote Address: [::1]:3001\nReferrer Policy: no-referrer-when-downgrade\n```\n\n```text\nRequest URL: http://localhost:3001/user\nRequest Method: GET\nStatus Code: 200 OK\nRemote Address: [::1]:3001\nReferrer Policy: no-referrer-when-downgrade\n```\n\n```text\n{\"navbar\":false,\"token\":null,\"user\":null,\"isUserLoggedIn\":false,\"access\":false,\"auth\":{\"user\":\"__vue_devtool_undefined__\",\"loggedIn\":false,\"strategy\":\"local\",\"busy\":false},\"feedType\":\"popular\"}\n```\n\n```text\napp.get('/user', \n isAuthenticated,\n UsersController.getUser)\n```\n\n```text\nconst passport = require('passport')\n\n module.exports = function (req, res, next) {\n passport.authenticate('jwt', function (err, user) {\n if(err || !user) {\n res.status(403).send({\n error: 'You are not authorized to do this.'\n })\n } else {\n req.user = user\n next()\n }\n })(req, res, next)\n }\n```\n\n```text\nconst User = require('../models/User')\n\n module.exports = {\n [...]\n getUser (req, res) {\n User.findById(req.user._id, function (error, user){\n if (error) { console.error(error); }\n res.send(user)\n })\n }\n [...]\n\n }\n```\n\n```text\nauth: {\n strategies: {\n local: {\n endpoints: {\n login: {url: '/login', method: 'post', propertyName: 'token' },\n user: {url: '/user', method: 'get', propertyName: false },\n logout: false,\n }\n }\n }\n },\n```\n\n```text\n\"propertyName\"\n```\n\n```text\n\"user\"\n```\n\n```text\n\"propertyName: false\",\n```\n\n========================================\n\nComments:\n- Hi, what does your user endpoint look like?\n- @imreBoersma I wrote it in the accepted answer. Or do you mean the code on my express api?\n- Yeah, I ment the express code :)\n- @imreBoersma I added the code at the end of the question because it would be to much and ugly here in the comments.\n- How is your api response json ?\n- Hey @SyamkumarKK, thanks for that edit. My response is the total User document (MongoDB) right now exept the logged in devices, because they change to much. But yes, I know it's not the best way and I will change that behaviour any time in future.","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":410,"estimatedTokens":2785}}452{"id":"stack-67035260","source":"stackoverflow","questionId":67035260,"title":"Nuxt - can i run client side code from a middleware in Universal mode?","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Nuxt - can i run client side code from a middleware in Universal mode?\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm working on a universal Nuxt app that uses the standard Django session authentication.\nI need to restrict some pages in my project to logged in users only, so i decided to use a middleware.\n\nThe problem with the middleware is that it will run from server side, so it will always return `False` to the user even when the user is logged in, since it doesn't send any cookie in the request. This happens only when i refresh page or when i navigate directly to it, not when i navigate from another page to a restricted page, that's because in that case the middleware is executed client side and not server side.\n\nIs there any way i can \"force\" the following code to run client side instead of server side from the middleware? Or do i have to look for another solution?\n\n```\nexport default async function (context) {\n axios.defaults.withCredentials = true;\n return axios({\n method: 'get',\n url: 'http://127.0.0.1:8000/checkAuth',\n withCredentials: true,\n }).then(function (response) {\n //Check if user is authenticated - response is always False\n }).catch(function (error) {\n //Handle error\n });\n}\n```\n\nI tried to do the same with `nuxtServerInit` but the outcome is the same. If i run that code in the `beforeCreate` block from the page it will first load the page and then execute the request, which works but it's quite ugly since the user will see the page for a second before being redirected.\n\n========================================\n\nTop Answer:\nthere's some updates.\n\nInsted of `process.client` use `import.meta.client`\n\nInsted of `process.server` use `import.meta.server`\n\nCheck it here(Nuxt DOCS)\n\n========================================\n\nCode:\n```text\nexport default async function (context) {\n axios.defaults.withCredentials = true;\n return axios({\n method: 'get',\n url: 'http://127.0.0.1:8000/checkAuth',\n withCredentials: true,\n }).then(function (response) {\n //Check if user is authenticated - response is always False\n }).catch(function (error) {\n //Handle error\n });\n}\n```\n\n```text\nFalse\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nbeforeCreate\n```\n\n```text\nexport default async function (context) {\n if(process.client) {\n // your middleware code here\n }\n}\n```\n\n```text\nplugins: [ \n { src: '~/plugins/client-only.js', mode: 'client' }, // only on client side \n ]\n```\n\n```text\nprocess.client\n```\n\n```text\nimport.meta.client\n```\n\n```text\nprocess.server\n```\n\n```text\nimport.meta.server\n```\n\n========================================\n\nComments:\n- I guess you can check the route and then run the code or see if the auth check is done then don't run the script.\n- Thank you! I created the plugin, but it seems to run twice, one time from server side and another time from client side\n- I think you can use process.client to run the code in your plugin only on the client-side.\n- I have an issue with nuxt 3, where do I place router middleware in nuxt 3? @mostafa\n- currently, there is only a server middleware section in Nuxt3 documentation. As The Nuxt team suggested you should use the Nuxt bridge so you can use Nuxt 2 features without experiencing breaking changes. With Nuxt Bridge you place middleware same as before (like version 2) and your app should work while you have the new Nuxt3 features. also checkout the router middleware part for version 2: nuxtjs.org/examples/middlewares/router\n- There is a \"client\" Middleware directory in Nuxt 3: nuxt.com/docs/guide/directory-structure/middleware","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":109,"estimatedTokens":898}}453{"id":"stack-56273091","source":"stackoverflow","questionId":56273091,"title":"Cannot read property 'register' of undefined service worker Nuxt JS","tags":["vuejs2","service-worker","nuxt.js"],"text":"Title: Cannot read property 'register' of undefined service worker Nuxt JS\nTags: vuejs2, service-worker, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement a custom built service worker into my Nuxt JS site. I'm getting an error after generating the site as follows:\n\n```\nCannot read property 'register' of undefined\n```\n\n```\nfunction Notify (siteOptions) {\n /* Set Dependancies */\n this.siteOptions = siteOptions /* Register Applicant */\n this.register()\n} /** * Register Service Worker */\nNotify.prototype.register = function () {\n /** * Test Registration */\n navigator.serviceWorker.register('Notify-service-worker.js').then(function (registration) {\n console.log('SW: Available')\n }).catch(function (error) {\n console.error('SW: Not Available', error)\n })\n```\n\nIt appears that this is the line causing issues:\n\n`navigator.serviceWorker.register('Notify-service-worker.js')`\n\n========================================\n\nTop Answer:\nThe problem could be that service workers work only on https. I solved it by using \"Localhost:3000\" in the address instead of the IP.\n\nOtherwise, you can go to chrome://flags/#unsafely-treat-insecure-origin-as-secure and click on enabled and add the application localhost link!\n\n========================================\n\nCode:\n```text\nCannot read property 'register' of undefined\n```\n\n```text\nfunction Notify (siteOptions) {\n /* Set Dependancies */\n this.siteOptions = siteOptions /* Register Applicant */\n this.register()\n} /** * Register Service Worker */\nNotify.prototype.register = function () {\n /** * Test Registration */\n navigator.serviceWorker.register('Notify-service-worker.js').then(function (registration) {\n console.log('SW: Available')\n }).catch(function (error) {\n console.error('SW: Not Available', error)\n })\n```\n\n```text\nnavigator.serviceWorker.register('Notify-service-worker.js')\n```\n\n```text\n<script>\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', function () {\n navigator.serviceWorker.register('/service-worker.js');\n });\n }\n</script>\n```\n\n========================================\n\nComments:\n- Serve your page over HTTPS or use localhost. Service workers require a Secure Context. stackoverflow.com/a/52300901/194717","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":77,"estimatedTokens":564}}454{"id":"stack-66152901","source":"stackoverflow","questionId":66152901,"title":"Nuxt js - SSR page duplicates components","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Nuxt js - SSR page duplicates components\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am generating a simple static page with a list of components and when I visit the page from another page it renders everything correctly. When I land directly on the page some of the components are rendered again after the footer. If I inspect the element I can see that they are the same elements but rendered again after the footer. Anyone has any idea on why this is happening?\n\n```\n\n \n \n \n \n \n \n \n \n \n \n\n \n \n \n \n\n \n\n \n\n \n\n \n\n \n\n \n \n\n \n\n \n\n \n \n\n```\n\nThis is what the page template looks like\n\n========================================\n\nCode:\n```text\n<template>\n <div>\n <client-only>\n <MobileNav v-if=\"!isDesktop\" />\n <Topnav v-if=\"isDesktop\" />\n <div v-if=\"isDesktop\">\n <Navbar active-page=\"consumers\" />\n </div>\n </client-only>\n <Hero page=\"consumers\" hero-text=\"for consumers\" text-alignment=\"middle\" />\n <AnchorNav :anchor-nav-items=\"anchorNavData\" />\n\n <div id=\"for-consumers\">\n <Highlight :data=\"highlight1\" />\n <Highlight :data=\"highlight2\" />\n </div>\n\n <LazyCardsWithModal :data=\"cardsList\" />\n\n <LazyImageText :data=\"imageTextDirector\" />\n\n <LazyKeyCards :data=\"keyCards\" />\n\n <LazyAccordion :data=\"accordionData\" />\n\n <LazyOrderedList :data=\"orderedList\" />\n\n <LazyLogoCards :data=\"logoCards\" :index=\"1\" />\n <LazyLogoCards :data=\"logoCards2\" :index=\"2\" />\n\n <LazyCardsWithModal :data=\"productsCards\" class=\"consumers-cards-2\" />\n\n <Footer />\n\n <Modal\n v-show=\"this.$store.state.modal.active\"\n :id=\"this.$store.state.modal.id\"\n />\n </div>\n</template>\n```\n\n```text\nclient-only\n```\n\n========================================\n\nComments:\n- seems like Model after the footer is causing this issue. Since you are using vuex state, if you refresh then the data wont be persisted. log the this.$store.state.modal.active and check it out.\n- thanks for the comment @Lohith, I think it makes sense. How would you approach the modal? Shall I include it in the component and not at the page level?\n- If the problem is really uncontrolled state data, then you can keep default value in data(){modalActive:false} , update the value with mapState, then refer modalActive in the template.\n- I am removing the modal functionality for now to check if it still has the issue. I will keep you posted but looks like it's related to the state data as you mentioned. One more thing I have noticed is that it works fine when I run it locally and the issue is only when it gets generated\n- @Lohith it didn't fix it unfortunately..so strange that this happens only on one single page..I am trying to debug removing one component at a time\n- Just for my clarification, for you everything works, if you run in develop mode >npm run dev. you are facing this issue with static page after running this-> npm run generate? am i correct.\n- yes it works fine in develop mode (npm run dev) and the issue is only on the static page generated\n- I had similar issue with breadcrumbs in static mode, which i tried to handle with vuex state, i still use state functionality but to handle it i added multiple if else conditions. In your case if you are facing the issue even after removing the modal means, then it might be from some other components which i cant figure out, as the code seems too abstract to guess.\n- hey @Lohith confirming that was a vuex issue. I've spotted the component and wrapped it with a client-only tag and it fixed the issue. thx for your help","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":111,"estimatedTokens":889}}455{"id":"stack-48253562","source":"stackoverflow","questionId":48253562,"title":"How to Add Client-side Scripts to Nuxt.js?","tags":["javascript","vuejs2","nuxt.js"],"text":"Title: How to Add Client-side Scripts to Nuxt.js?\nTags: javascript, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI've been reading Nuxt.js's documentation on Plugins and the config nuxt file for adding scripts. I tried both, but no luck.\n\nI'm trying to add the following code (located in `/static/js/scripts.js`):\n\n```\n$(window).scroll(function(){\n if ($(window).scrollTop() >= 200) {\n $('nav').addClass('fixed-header');\n }\n else {\n $('nav').removeClass('fixed-header');\n }\n });\n```\n\nCan someone help me please?\n\nIn regular HTML usage, I just do the script tags before the closing body tag (for the sake of user experience). I was able to get the `scripts.js` to load in a Vue.js 2.0 framework, but once I moved everything to Nuxt.js, and tried to adapt it to Nuxt.js, everything else worked, except the `scripts.js` file.\n\n========================================\n\nTop Answer:\nThe official guide in Nuxt v1.4.0 document is here: https://nuxtjs.org/faq/window-document-undefined#window-or-document-undefined-\n\n If you need to specify that\n you want to import a resource only on the client-side, you need to use\n the process.browser variable.\n\n \n For example, in your .vue file:\n\n```\nif (process.browser) {\n require('external_library')\n}\n```\n\n \n If you are using this library within multiple files, we recommend that\n you add it into your vendor bundle via nuxt.config.js:\n\n```\nbuild: {\n vendor: ['external_library']\n}\n```\n\n========================================\n\nCode:\n```text\n$(window).scroll(function(){\n if ($(window).scrollTop() >= 200) {\n $('nav').addClass('fixed-header');\n }\n else {\n $('nav').removeClass('fixed-header');\n }\n });\n```\n\n```text\n/static/js/scripts.js\n```\n\n```text\nscripts.js\n```\n\n```text\nscripts.js\n```\n\n```text\n<script>\nexport default {\n name: 'MainNav',\n data: function () {\n return {\n fixedOnScroll: false\n }\n },\n methods: {\n handleScroll () {\n if (window.scrollY >= 200) {\n this.fixedOnScroll = true\n } else {\n this.fixedOnScroll = false\n }\n }\n },\n created () {\n if (process.browser) {\n window.addEventListener('scroll', this.handleScroll)\n }\n },\n beforeUpdate () {\n if (process.browser) {\n window.addEventListener('scroll', this.handleScroll)\n }\n }\n}\n</script>\n```\n\n```text\n<nav class = \"navbar-expand-lg text-center\" v-bind:class=\"{ 'fixed-header': fixedOnScroll }\">\n```\n\n```text\nif (process.browser) {\n require('external_library')\n}\n```\n\n```text\nbuild: {\n vendor: ['external_library']\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.868Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":125,"estimatedTokens":634}}456{"id":"stack-69488000","source":"stackoverflow","questionId":69488000,"title":"How to get the current nuxt layout from within a component/template?","tags":["vue.js","nuxt.js"],"text":"Title: How to get the current nuxt layout from within a component/template?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nNuxt provides a way to dynamically set a `layout` within a component, but is there a way to determine which layout is in use from within the `` e.g. `v-if=\"layout === 'me'\"`? For example, I want to use a single route `/c/dream` and provide one layout for a user who is authenticated and another layout for a user who is not authenticated. If I can determine the layout in use from within the template, then I can structure the HTML according to the layout. I've inspected the `this` object in a component and do not see a way to determine which layout is in use.\n\n========================================\n\nCode:\n```text\nlayout\n```\n\n```text\n<template>\n```\n\n```text\nv-if=\"layout === 'me'\"\n```\n\n```text\n/c/dream\n```\n\n```text\nthis\n```\n\n```js\n// layouts/authenticated.vue\nexport default {\n provide() {\n return { layout: \"authenticated\" };\n },\n};\n```\n\n```html\n<template>\n <div>\n <div v-if=\"layout == 'authenticated'\">\n <!-- custom UI for authenticated users -->\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n // Determines which layout is currently in use\n inject: [\"layout\"],\n\n // Decide which layout to use\n // based on Nuxt context as an example\n layout(context) {\n return context.user ? \"authenticated\" : \"default\";\n },\n};\n</script>\n```\n\n```text\nlayout\n```\n\n```text\npages/c/dream.vue\n```\n\n```text\nlayout(context)\n```\n\n```text\nlayout\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":77,"estimatedTokens":376}}457{"id":"stack-72848505","source":"stackoverflow","questionId":72848505,"title":"What is the difference between useRoute and useRouter in Nuxt3-Vue","tags":["vue.js","nuxt.js","vue-router","nuxt3.js"],"text":"Title: What is the difference between useRoute and useRouter in Nuxt3-Vue\nTags: vue.js, nuxt.js, vue-router, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI want to understand, what is the difference between\n\n```\nconst Route = useRoute()\n```\n\nand\n\n```\nconst Router = useRouter()\n```\n\nin Nuxt3/Vue.\n\nAlso, I am not able to use router properly.\n\non submit, I want to push to another page with query strings using.\n\n```\n\n \n\nimport { ref } from 'vue'\nconst router = useRouter()\nconst pickuppoint = ref('')\nconst dropoffpoint = ref('')\n\nconst SearchTaxi = () => {\nrouter.push({\n path: `/airport-transfers/results?pickuppoint=${pickuppoint.value}&dropoffpoint=${dropoffpoint.value}`})\n}\n\n```\n\nI expect route to change to\n\n```\n\"url/airport-transfers/results?pickuppoint=XXXX&dropoffpoint=XXXX\"\n```\n\nbut i am getting\n\n```\n\"url/airport-transfers/results\"\n```\n\n========================================\n\nCode:\n```js\nconst Route = useRoute()\n```\n\n```js\nconst Router = useRouter()\n```\n\n```html\n<template>\n <button @click=\"SearchTaxi\"></button>\n</template>\n\n<script setup>\nimport { ref } from 'vue'\nconst router = useRouter()\nconst pickuppoint = ref('')\nconst dropoffpoint = ref('')\n\nconst SearchTaxi = () => {\nrouter.push({\n path: `/airport-transfers/results?pickuppoint=${pickuppoint.value}&dropoffpoint=${dropoffpoint.value}`})\n}\n</script>\n```\n\n```text\n\"url/airport-transfers/results?pickuppoint=XXXX&dropoffpoint=XXXX\"\n```\n\n```text\n\"url/airport-transfers/results\"\n```\n\n```js\nrouter.push({\n path: '/airport-transfers/results',\n query: { \n pickuppoint: pickuppoint.value,\n dropoffpoint: dropoffpoint.value\n }\n})\n```\n\n```text\npush\n```\n\n```text\nreplace\n```\n\n```text\nn-1\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":109,"estimatedTokens":417}}458{"id":"stack-61943647","source":"stackoverflow","questionId":61943647,"title":"How do I get Nuxt.js to pre-render the full HTML for pages?","tags":["html","vue.js","single-page-application","nuxt.js","prerender"],"text":"Title: How do I get Nuxt.js to pre-render the full HTML for pages?\nTags: html, vue.js, single-page-application, nuxt.js, prerender\nSource: Stack Overflow\n\nQuestion:\nI have a basic app (nuxt version 2.12.2) that I made by running `npx create-nuxt-app`, and setting mode to \"SPA\". When I use `npm run build` or `npm run generate`, it creates an HTML file for each page, but it does not pre-render any of the actual HTML in the page. It only has the JavaScript that loads the single-page application. I want each page to have pre-rendered HTML for SEO reasons. What is the best way to do that?\n\nI'm really surprised I haven't found anything in the Nuxt.js documentation that addresses this.\n\n========================================\n\nCode:\n```text\nnpx create-nuxt-app\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run generate\n```\n\n```text\nnuxt generate\n```\n\n========================================\n\nComments:\n- Thank you for this, I thought I was going crazy. I'm deploying a website on netlify and I noticed we have consistently better scores on lighthouse with ssr: true even though there's technically no node behind it. When I mean consistently better I mean like 40 points in score difference from ssr:false to ssr:true. I really couldn't wrap my head around why this was happening! Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":32,"estimatedTokens":324}}459{"id":"stack-72307365","source":"stackoverflow","questionId":72307365,"title":"Nuxt 3 ignore filepath for naming components?","tags":["vue.js","nuxt.js","nuxt3.js"],"text":"Title: Nuxt 3 ignore filepath for naming components?\nTags: vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm migrating over to NuxtJS 3, but my project has several levels of `component` folders:\n\n```\n/components \n /foo\n file.vue\n file2.vue\n /fooTwo\n anotherfile.vue\n /bar\n file1.vue\n file10.vue\n etc...\n```\n\nBecause of Nuxt's naming convention, if I try to import the `anotherfile` component I'd have to rename every place it's used inside my codebase to this: ``\n\nBecause their documentation states:\n\nthe component's name will be based on its own path directory and filename\n\nI really don't want to go through and rename every place that the component is being used. And I also would prefer to not flatten my directory structure either. So, is there some config option in Nuxt 3 that overrides this and lets me just globally call the components by their original name?\n\n========================================\n\nTop Answer:\nAs @kissu suggested this is the answer:\n\n`nuxt.config.ts`\n\n```\ncomponents: [\n {\n path: '~/components', // will get any components nested in let's say /components/test too\n pathPrefix: false, //<------------------- here\n },\n]\n```\n\n========================================\n\nCode:\n```text\n/components \n /foo\n file.vue\n file2.vue\n /fooTwo\n anotherfile.vue\n /bar\n file1.vue\n file10.vue\n etc...\n```\n\n```text\ncomponent\n```\n\n```text\nanotherfile\n```\n\n```text\n<FooFooTwoanotherfile/>\n```\n\n```js\nimport { defineNuxtConfig } from 'nuxt'\n\nexport default defineNuxtConfig({\n components: [\n {\n path: '~/components', // will get any components nested in let's say /components/nested\n pathPrefix: false,\n },\n ]\n})\n```\n\n```html\n<template>\n <div>\n <yolo-swag /> <!-- no need for <nested-yolo-swag /> here -->\n </div>\n</template>\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n/pages/index.vue\n```\n\n```js\ncomponents: [\n {\n path: '~/components', // will get any components nested in let's say /components/test too\n pathPrefix: false, //<------------------- here\n },\n]\n```\n\n```text\nnuxt.config.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":113,"estimatedTokens":530}}460{"id":"stack-64685095","source":"stackoverflow","questionId":64685095,"title":"Problem with placing v-app-bar content in container?","tags":["vue.js","nuxt.js","vuetify.js"],"text":"Title: Problem with placing v-app-bar content in container?\nTags: vue.js, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nI need to place content inside v-app-bar inside container, so It goes in one line with other page content. All content inside app should have max width for each breakpoint instead of full page width. Placing all content iside container don't solve problem.\n\nI marked with red box on screenshot where content should be.\nhttps://i.sstatic.net/nGzAB.png\n\n========================================\n\nTop Answer:\nI got mine to work and also keep the navbar background extended to the edge of the screen. You can put a container inside the app-bar but it messes with the flexbox of the items so you just have to put a v-row inside for them to align properly.\n\n```\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n.v-container {\n max-width: 60% !important;\n}\n\n```\n\n========================================\n\nCode:\n```html\n<template>\n <v-sheet color=\"red\">\n <v-container class=\"pa-0\">\n <v-app-bar\n dense\n flat\n color=\"blue accent-4\"\n >\n <v-btn icon>\n <v-icon>mdi-home-outline</v-icon>\n </v-btn>\n <v-divider inset vertical></v-divider>\n\n <v-btn text :key=\"item.id\" v-for=\"item in quickLinks\" v-text=\"item.text\"></v-btn>\n <v-spacer></v-spacer>\n <v-btn text v-text=\"'Sign In'\"></v-btn>\n <v-btn text v-text=\"'Register'\"></v-btn>\n </v-app-bar>\n </v-container>\n </v-sheet>\n</template>\n```\n\n```html\n<template>\n <v-app-bar app>\n <v-container class=\"pa-0 fill-height\">\n <!-- [...] -->\n </v-container>\n </v-app-bar>\n</template>\n```\n\n```text\nv-app-bar\n```\n\n```html\n<template>\n <nav class=\"toolbar\" align=\"center\">\n <v-app-bar app>\n <v-container>\n <v-row align=\"center\">\n <v-app-bar-title>\n <!-- Title-->\n </v-app-bar-title>\n <div>\n <!-- Left side content -->\n </div>\n <v-spacer />\n <div>\n <!-- Right side content -->\n </div>\n </v-row>\n </v-container>\n </v-app-bar>\n </nav>\n</template>\n\n<style scoped>\n.v-container {\n max-width: 60% !important;\n}\n</style>\n```\n\n========================================\n\nComments:\n- Provide a code related with a specified area. Provide also an code attempts which you have tried but failed. Do you want to move a logo from left navbar and a menu from the right navbar to this red area in navbar?\n- Vuetify has some examples where they constrain the app bar vuetifyjs.com/en/getting-started/wireframes/#examples\n- Thank you, this works well. There was a weird issue with the app-bar where whenever a container is used inside of the app-bar itself (Vuetify 3) all the contents is forced to a small space in the left. Your approach was the only one that worked.","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":118,"estimatedTokens":741}}461{"id":"stack-64304556","source":"stackoverflow","questionId":64304556,"title":"Is there a way to fix this error in prettier, in nuxt / vue environment","tags":["vue.js","nuxt.js","eslint","prettier"],"text":"Title: Is there a way to fix this error in prettier, in nuxt / vue environment\nTags: vue.js, nuxt.js, eslint, prettier\nSource: Stack Overflow\n\nQuestion:\nI just ran NPM update on a project that was working fine. Now, I am getting a Prettier \"Friendly Error\". I'm wondering if ESLint and Prettier are not playing well together in my config.\n\n```\nerror Replace `⏎··················Coming·Soon!⏎················` with `Coming·Soon!`\n```\n\nI'm not really sure what is going on here, but it looks like it's a formatting issue telling me to add backticks. The errors are on HTML markup that does not even have qoutes on it. It's literally `Coming Soon`.\n\n*.eslintrc.js:*\n\n```\nmodule.exports = {\n root: true,\n env: {\n browser: true,\n node: true,\n },\n parserOptions: {\n parser: 'babel-eslint',\n },\n extends: [\n '@nuxtjs',\n 'prettier',\n 'prettier/vue',\n 'plugin:prettier/recommended',\n 'plugin:nuxt/recommended',\n ],\n plugins: ['prettier'],\n rules: {},\n}\n```\n\n*.prettierrc:*\n\n```\n{\n \"semi\": false,\n \"singleQuote\": true,\n \"htmlWhitespaceSensitivity\": \"ignore\"\n}\n```\n\n========================================\n\nCode:\n```text\nerror Replace `⏎··················Coming·Soon!⏎················` with `Coming·Soon!`\n```\n\n```js\nmodule.exports = {\n root: true,\n env: {\n browser: true,\n node: true,\n },\n parserOptions: {\n parser: 'babel-eslint',\n },\n extends: [\n '@nuxtjs',\n 'prettier',\n 'prettier/vue',\n 'plugin:prettier/recommended',\n 'plugin:nuxt/recommended',\n ],\n plugins: ['prettier'],\n rules: {},\n}\n```\n\n```json\n{\n \"semi\": false,\n \"singleQuote\": true,\n \"htmlWhitespaceSensitivity\": \"ignore\"\n}\n```\n\n```text\n<span>Coming Soon</span>\n```\n\n```js\n// .eslintrc.js\nmodule.exports = {\n rules: {\n 'prettier/prettier': {\n htmlWhitespaceSensitivity: 'strict',\n },\n },\n}\n```\n\n```text\nComing Soon!\n```\n\n```text\nhtmlWhitespaceSensitivity\n```\n\n```text\nignore\n```\n\n```text\nstrict\n```\n\n```text\nstrict\n```\n\n```text\nhtmlWhitespaceSensitivity\n```\n\n```text\n.prettierrc\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":126,"estimatedTokens":497}}462{"id":"stack-74274448","source":"stackoverflow","questionId":74274448,"title":"Nuxt3 Robots.txt - @nuxtjs/robots not generating robots.txt file","tags":["javascript","nuxt.js","robots.txt","nuxt3.js"],"text":"Title: Nuxt3 Robots.txt - @nuxtjs/robots not generating robots.txt file\nTags: javascript, nuxt.js, robots.txt, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a Nuxt 3 project. I need my build to generate a robots.txt file, just like this package states it does -> https://github.com/nuxt-community/robots-module\n\nAfter running \"nuxt build\" and/or \"nuxt generate\", the robots.txt does not appear in the output or public folders as I'd expect.\n\nI'm definitely missing something and likely being an idiot here.. Does anyone know what I'm missing? Here's my code:\n\n**package.json**\n\n```\n\"dependencies\": {\n ...\n \"@nuxtjs/robots\": \"^2.5.0\", \n }\n```\n\n**nuxt.config.ts**\n\n```\ntarget: \"static\",\n runtimeConfig: {\n NUXT_STORYBLOK_PRODUCTION_KEY: process.env.NUXT_STORYBLOK_PRODUCTION_KEY,\n public: {\n CDN: process.env.CDN,\n NUXT_STORYBLOK_PREVIEW_KEY: process.env.NUXT_STORYBLOK_PREVIEW_KEY,\n NUXT_DOMAIN_NAME: process.env.NUXT_DOMAIN_NAME,\n },\n },\n modules: [\n ...\n \"@nuxtjs/robots\",\n ],\n robots: {\n UserAgent: \"*\",\n Disallow: \"\",\n },\n}\n```\n\n========================================\n\nTop Answer:\nI just successfully installed this module on Nuxt 3, and I think there are a couple of things to note here.\n\nThe first is that I've never managed to get the module options for any module to work in Nuxt 3 the way you have shown (top-level options, according to the module docs):\n\n```\nmodules: [\n ...\n \"@nuxtjs/robots\",\n ],\n robots: {\n UserAgent: \"*\",\n Disallow: \"\",\n }\n```\n\nHave you tried the other options? You can also try using the Robots Config file, or pass the options when declaring the module (from the README.md for the repo):\n\n```\nexport default {\n modules: [\n // Simple usage\n '@nuxtjs/robots',\n\n // With options\n ['@nuxtjs/robots', { /* module options */ }]\n ]\n}\n```\n\nThe other thing is that I also do not see a generated robots.txt file anywhere after running the build or dev, but if I go to '/robots.txt' in the dev or build preview, I can see the output working as intended. Have you tried visiting the path?\n\nIt looks like something the server generates when the route is visited rather than a static file generated on build by default. I think you can change that in the options, but it's not something I need so I haven't dug into it.\n\nHopefully, that helps somewhat!\n\n========================================\n\nCode:\n```text\n\"dependencies\": {\n ...\n \"@nuxtjs/robots\": \"^2.5.0\", \n }\n```\n\n```text\ntarget: \"static\",\n runtimeConfig: {\n NUXT_STORYBLOK_PRODUCTION_KEY: process.env.NUXT_STORYBLOK_PRODUCTION_KEY,\n public: {\n CDN: process.env.CDN,\n NUXT_STORYBLOK_PREVIEW_KEY: process.env.NUXT_STORYBLOK_PREVIEW_KEY,\n NUXT_DOMAIN_NAME: process.env.NUXT_DOMAIN_NAME,\n },\n },\n modules: [\n ...\n \"@nuxtjs/robots\",\n ],\n robots: {\n UserAgent: \"*\",\n Disallow: \"\",\n },\n}\n```\n\n```text\nnpm install @nuxtjs/robots@3.0.0\n```\n\n```text\nexport default {\n modules: [\n ['@nuxtjs/robots', { configPath: \"~/config/robots.config\" }]\n ]\n}\n```\n\n```text\nmodules: [\n ...\n \"@nuxtjs/robots\",\n ],\n robots: {\n UserAgent: \"*\",\n Disallow: \"\",\n }\n```\n\n```text\nexport default {\n modules: [\n // Simple usage\n '@nuxtjs/robots',\n\n // With options\n ['@nuxtjs/robots', { /* module options */ }]\n ]\n}\n```\n\n```text\nnpm install @nuxtjs/robots\n```\n\n```text\nnpm install @nuxtjs/robots@3.0.0\n```\n\n```text\nrobots.config\n```\n\n```text\nrobots.txt\n```\n\n```text\nnuxt-simple-robots\n```\n\n```text\nyarn add -D nuxt-simple-robots\n```\n\n```text\n/public/robots.txt\n```\n\n```text\n/public/_robots.txt\n```\n\n```text\nnpm install @nuxtjs/robots@3.0.0\n```\n\n```text\nmodules: [\n[ '@nuxtjs/robots',\n {\n rules :{\n UserAgent: '*',\n Disallow: '/'\n }\n }\n] ]\n```\n\n```text\nrobots.mjs\n```\n\n```text\nrobots.txt\n```\n\n```text\nhttps://<your domain>/robots.txt\n```\n\n```text\nhttp://localhost:3000/robots.txt\n```\n\n========================================\n\nComments:\n- It should be `generate` and available in `dist` if I'm not mistaken. Otherwise you can always run `preview` and inspect the generated payload to double check.\n- Nvm, it's the `.output` directory rather.\n- It doesn't appear for me in `output`. If it should appear there and I get no other responses on this question, it's likely I have a dependency conflict with another package and it may be a case of stripping down the project until I find the problem.\n- Tried to preview it? I doubt there is a conflict tbh.\n- Yep. Stil nothing. `Build` / `Generate` && `Preview`, tried it all. No Robots file gets generated in that `output` folder or any of it's subfolders.\n- Got a repro like a public Github?\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":221,"estimatedTokens":1216}}463{"id":"stack-62640237","source":"stackoverflow","questionId":62640237,"title":"v-if breaks nuxt ssr","tags":["vue.js","nuxt.js","apollo"],"text":"Title: v-if breaks nuxt ssr\nTags: vue.js, nuxt.js, apollo\nSource: Stack Overflow\n\nQuestion:\nIf I use fetched data (fetchPolicy: `'cache-and-network'`) from apollo in v-if, it will throw\n`vue.runtime.esm.js:619 [Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside , or missing . Bailing hydration and performing full client-side render.`\n\n```\n\n \n {{ test }}\n \n \n\n```\n\nbut if I use it just as variable to render it works fine.\n\n```\n\n \n {{ test }}\n \n\n```\n\nThe data in real usage is object, that I need to conditionaly render and pass to another components with v-if.\n\nI have tried geting the data trough get, doing watch over the data and seting them manually, but eventually everything broke.\n\nregarding comment:\nif I console the `test` data it will go -> `true` on server -> `false` on client and then `true` on the client again, if I remove the `test` from `v-if` it goes: `true` on server and `true` on client\n\nthis has nothing to do with structure, in real project it has bunch of components and it works just fine if the data isnt used in condition\n\n========================================\n\nTop Answer:\nYou are trying to make the root element of a component conditionnally disappear, which creates an inconsistency in the virtual DOM.\n\nCan you try:\n\n```\n\n \n \n {{ test }}\n \n \n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div\n <div v-if=\"test\">\n {{ test }}\n </div>\n </div>\n</template>\n```\n\n```text\n<template>\n <div>\n {{ test }}\n </div>\n</template>\n```\n\n```text\n'cache-and-network'\n```\n\n```text\nvue.runtime.esm.js:619 [Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.\n```\n\n```text\ntest\n```\n\n```text\ntrue\n```\n\n```text\nfalse\n```\n\n```text\ntrue\n```\n\n```text\ntest\n```\n\n```text\nv-if\n```\n\n```text\ntrue\n```\n\n```text\ntrue\n```\n\n```text\nmounted() {\n this.$apollo.queries.getCampaign.setOptions({\n fetchPolicy: 'cache-and-network',\n })\n}\n```\n\n```text\ncache-and-network\n```\n\n```text\n<template>\n <div>\n <template v-if=\"test\">\n {{ test }}\n </template>\n </div>\n</template>\n```\n\n```text\n<no-ssr>\n```\n\n```text\n<no-ssr>\n```\n\n```text\n<no-ssr>\n```\n\n```text\n<client-only>\n```\n\n========================================\n\nComments:\n- What is the server-side content like?\n- It's been a long time I haven't worked with Nuxt but I see that this question has still no relevant answer. Any update on your side @Lukáš Gibo Vaic\n- Instead of using arbitrary ``, use `` instead.\n- Even if I do that, it doesnt work, in real exmaple there is bunch of components, and all are in wrapper component, this is all cause by the one tick when apollo returns no data.\n- no-ssr is not an option, its all custom components, its all about usage the data from query in `if` statement, once again as I wrote in question if I set apollo to cache-and-network for one tick the cache is empty\n- Do you have an idea, why this helped?\n- no I dont, and Iam long gone from this, so cant really help you sorry\n- really need it to work on server, so this kinda makes no sense for me","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":163,"estimatedTokens":840}}464{"id":"stack-74466869","source":"stackoverflow","questionId":74466869,"title":"Nuxt build error: TypeError: Cannot destructure property 'nuxt' of 'this' as it is undefined","tags":["vue.js","npm","nuxt.js","tailwind-css"],"text":"Title: Nuxt build error: TypeError: Cannot destructure property 'nuxt' of 'this' as it is undefined\nTags: vue.js, npm, nuxt.js, tailwind-css\nSource: Stack Overflow\n\nQuestion:\nI want to create a new Nuxt project and followed their instructions here: https://nuxtjs.org/docs/get-started/installation. Basically just running `npm init nuxt-app@latest `.\n\nAfter going through the setup (in which I choose Tailwind as my UI of choice), I run `npm run dev` and it crashes while trying to build saying \"Cannot destructure property 'nuxt' of 'this' as it is undefined.\"\n\nHere is the full stack:\n\n```\nFATAL Cannot destructure property 'nuxt' of 'this' as it is undefined. 15:22:52 \n\n at postcss8Module (node_modules\\@nuxt\\postcss8\\dist\\index.js:15:10)\n at installModule (/C:/Users/conmi/Documents/Personal/Katie's%20Website/katierose-photos/node_modules/@nuxt/kit/dist/index.mjs:416:9)\n at async setup (/C:/Users/conmi/Documents/Personal/Katie's%20Website/katierose-photos/node_modules/@nuxtjs/tailwindcss/dist/module.mjs:186:7)\n at async ModuleContainer.normalizedModule (/C:/Users/conmi/Documents/Personal/Katie's%20Website/katierose-photos/node_modules/@nuxt/kit/dist/index.mjs:167:5)\n at async ModuleContainer.addModule (node_modules\\@nuxt\\core\\dist\\core.js:239:20)\n at async ModuleContainer.ready (node_modules\\@nuxt\\core\\dist\\core.js:51:7)\n at async Nuxt._init (node_modules\\@nuxt\\core\\dist\\core.js:478:5)\n```\n\nI found not including `'@nuxtjs/tailwindcss'` in the buildModules in nuxt.config.js removes the error, but it does not create the tailwind config files I need. Also, the line causing the error in postcss8Module's index.js is `const { nuxt } = this`. For some reason `this` is undefined.\n\n========================================\n\nTop Answer:\nThe error comes from the recent Nuxt 3 Release and is being tracked on the create-nuxt-app Github.\n\nCreate-nuxt-app is not compatible with Nuxt 3 yet. Therefore, for now, you have to install Nuxt 3 and Tailwind CSS manually:\n\n```\nnpx nuxi init \ncd \nnpm install\nnpm install @nuxtjs/tailwindcss --save-dev\n```\n\nNow you should be able to run your app as expected:\n\n```\nnpm run dev\n```\n\n========================================\n\nCode:\n```text\nFATAL Cannot destructure property 'nuxt' of 'this' as it is undefined. 15:22:52 \n\n at postcss8Module (node_modules\\@nuxt\\postcss8\\dist\\index.js:15:10)\n at installModule (/C:/Users/conmi/Documents/Personal/Katie's%20Website/katierose-photos/node_modules/@nuxt/kit/dist/index.mjs:416:9)\n at async setup (/C:/Users/conmi/Documents/Personal/Katie's%20Website/katierose-photos/node_modules/@nuxtjs/tailwindcss/dist/module.mjs:186:7)\n at async ModuleContainer.normalizedModule (/C:/Users/conmi/Documents/Personal/Katie's%20Website/katierose-photos/node_modules/@nuxt/kit/dist/index.mjs:167:5)\n at async ModuleContainer.addModule (node_modules\\@nuxt\\core\\dist\\core.js:239:20)\n at async ModuleContainer.ready (node_modules\\@nuxt\\core\\dist\\core.js:51:7)\n at async Nuxt._init (node_modules\\@nuxt\\core\\dist\\core.js:478:5)\n```\n\n```text\nnpm init nuxt-app@latest <project-name>\n```\n\n```text\nnpm run dev\n```\n\n```text\n'@nuxtjs/tailwindcss'\n```\n\n```text\nconst { nuxt } = this\n```\n\n```text\nthis\n```\n\n```bash\nnpx nuxi init <project-name>\ncd <project-name>\nnpm install\nnpm install @nuxtjs/tailwindcss --save-dev\n```\n\n```text\nnpm run dev\n```\n\n```json\n\"resolutions\": {\n \"@nuxt/kit\": \"3.0.0-rc.13\"\n }\n```\n\n```text\nnpm install nuxt@latest vue-router@latest vue@latest --save-dev\n```\n\n```text\n<script lang=\"ts\">\nimport { defineComponent } from 'vue';\n\nexport default defineComponent({\n name: 'IndexPage'\n})\n</script>\n```\n\n========================================\n\nComments:\n- Use node v16 and try `npx create-nuxt-app my-new-project`, see if works better anyhow.\n- @kissu I am still getting the same error.\n- Something is wrong with your system then because that one should work flawlessly.\n- I succeeded to use Tailwind as advised by its documentation: tailwindcss.com/docs/guides/nuxtjs\n- OP didn't say that he wanted to use Nuxt3.\n- This should be the accepted answer (for the moment)\n- Same comment as of here: stackoverflow.com/questions/74936551/…","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":121,"estimatedTokens":1072}}465{"id":"stack-55404970","source":"stackoverflow","questionId":55404970,"title":"Nuxtjs - What files /folders do you need to deploy production version on host","tags":["vue.js","nuxt.js"],"text":"Title: Nuxtjs - What files /folders do you need to deploy production version on host\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nhttps://nuxtjs.org/guide/commands#development-environment\n\nThere is no mention of the files required by Nuxt when deploying it to live hosting.\n\nUsing Nuxt CLI, creates several empty folders such as\n\nassets\ncomponents\nlayouts\npages\nserver\n\nUsing npm build .nuxt folder is created - do i simply upload the content of the full folder or are the dist folder….????\n\nI have tried several combinations of uploading the full contents of .nuxt vs only parts. I havent had any luck.\n\n========================================\n\nComments:\n- universal mode?\n- correct- i am using universal mode\n- Thanks! if my website root is /public/ would i upload the files like /public/.nuxt/.. /public/static/.. /public/node_modules/... /public/static etc or would i treat the contents within the .nuxt folder as the root and upload it directly to /public/.. so i would have for example /public/server.js and then have the folder structure maintained within .nuxt just on /public/whatever ??\n- @Jujubes your question kind of assumes that u want static files. But universal mode mean that you have to run node server on your server which will serve request, so it dont matter where to place...\n- I dont want static files. I am running node. I just have no clue what to upload and there doesnt seem to be a clear answer on the docs.\n- when i run npm builld the .nuxt folder is created and it contains a bunch of files and folders. i have no clue what to put onto my website root on the server(hosting)\n- @Jujubes, what hosting are you using?\n- linux centos 7 with plesk\n- Oh wow that is an eye opener which definately leads to more questions regarding babel/ webpack\n- Should I reconfigure babel/ webpack\n- @Jujubes what for ?\n- Mainly to eliminate any unsupported API functions such as import instead of require\n- Nuxt do all transpiring by default\n- Cool cool. So in assuming this is done at runtime. Isn't that kinda slow\n- To clarify, i basically upload my existing files as is to plesk(thats what you github page suggests). The build process using the prescribed scripts in package.json is not done. So i have uploaded uncompiled docs that will be converted once i tell plesk to start node which will spin up the site?\n- It all stated in that link. You either build it on start or you use run script to build it once\n- Read and now in running into a problem with babel-loader it indicates that .nuxt/client.js does not exist and after running the build script on plesk it's definitely there\n- @Aldarund i am getting the following error from your gitpage tutorial postimg.cc/w1vQqymS and the file does exist\n- @Jujubes you can go to nuxt discord where you should get better help than here in comments. Its hard to say what u are doing wrong, but if u tutorial it should work\n- @Aldarund instead of uploading the docs i pulled from a git and it works now - no clue why","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":44,"estimatedTokens":747}}466{"id":"stack-51572594","source":"stackoverflow","questionId":51572594,"title":"How can I stop showing build logs from webpack?","tags":["webpack","nuxt.js"],"text":"Title: How can I stop showing build logs from webpack?\nTags: webpack, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want is to stop displaying build logs like this:\n\n```\nHash: 5a2a3d23f88174970ed8\nVersion: webpack 3.12.0\nTime: 22209ms\n Asset Size Chunks Chunk Names\n pages/widgets/index.51838abe9967a9e0b5ff.js 1.17 kB 10 [emitted] pages/widgets/index\n img/icomoon.7f1da5a.svg 5.38 kB [emitted] \n fonts/icomoon.2d429d6.ttf 2.41 kB [emitted] \n img/fontawesome-webfont.912ec66.svg 444 kB [emitted] [big] \n fonts/fontawesome-webfont.b06871f.ttf 166 kB [emitted] \n img/mobile.8891a7c.png 39.6 kB [emitted] \n img/play_button.6b15900.png 14.8 kB [emitted] \n img/keyword-back.f95e10a.jpg 43.4 kB [emitted] \n fonts/icomoon.16db67c.woff 2.49 kB [emitted] \n fonts/icomoon.2fcbf50.eot 2.58 kB [emitted] \n fonts/fontawesome-webfont.674f50d.eot 166 kB [emitted] \n fonts/fontawesome-webfont.fee66e7.woff 98 kB [emitted] \n\n.\n.\n.\n```\n\nI was using `ava` to run tests. But these logs are annoying me. I tried to set webpack `stats` config in `nuxt.config.js`, but it is not working. Can someone provide any help?\n\n```\n// Does not work\n{\n ...\n build: {\n ...\n extend (config, { isClient }) {\n ...\n if (process.env.NODE_ENV === 'test') {\n config.stats = 'errors-only'\n }\n }\n }\n ...\n}\n```\n\n**Update:** The following can hide assets logs, but it still shows warnings:\n\n```\n// Works, but does not hide warnings\n{\n ...\n build: {\n stats: process.env.NODE_ENV === 'test' ? 'errors-only' {\n chunks: false,\n children: false,\n modules: false,\n colors: true,\n assets: true,\n warnings: true,\n errors: true,\n excludeAssets: [\n /.map$/,\n /index\\..+\\.html$/,\n /vue-ssr-client-manifest.json/\n ]\n },\n ...\n }\n ...\n}\n```\n\nBut this does not hide the warnings:\n\n```\nWARNING Compiled with 2 warnings\n\n warning \n\nasset size limit: The following asset(s) exceed the recommended size limit (300 kB).\nThis can impact web performance.\nAssets: \n img/fontawesome-webfont.912ec66.svg (444 kB)\n vendor.4db9bb219a2a9c02d939.js (726 kB)\n app.f14777ec0017fec245a3.js (546 kB)\n\n warning \n\nentrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (1 MB). This can impact web performance.\nEntrypoints:\n app (1.27 MB)\n manifest.4eb49c6cde9aa836f4d4.js\n vendor.4db9bb219a2a9c02d939.js\n app.f14777ec0017fec245a3.js\n```\n\n========================================\n\nTop Answer:\nHere's a suggestion for your **webpack** config:\n\n```\nmodule.exports = {\n devServer: {\n stats: {\n colors: true,\n hash: false,\n version: false,\n timings: false,\n assets: false,\n chunks: false,\n modules: false,\n reasons: false,\n children: false,\n source: false,\n errors: false,\n errorDetails: false,\n warnings: false,\n publicPath: false\n }\n }\n}\n```\n\nThe key ones to disable are `hash`, `version`, `timings`, `assets`, `chunks`.\n\nThis should reduce build times and suppress logging.\n\nNote: this suggestion comes from Webpack: silence output. I couldn't flag this question as a duplicate though, as it has a bounty. :)\n\n========================================\n\nCode:\n```text\nHash: 5a2a3d23f88174970ed8\nVersion: webpack 3.12.0\nTime: 22209ms\n Asset Size Chunks Chunk Names\n pages/widgets/index.51838abe9967a9e0b5ff.js 1.17 kB 10 [emitted] pages/widgets/index\n img/icomoon.7f1da5a.svg 5.38 kB [emitted] \n fonts/icomoon.2d429d6.ttf 2.41 kB [emitted] \n img/fontawesome-webfont.912ec66.svg 444 kB [emitted] [big] \n fonts/fontawesome-webfont.b06871f.ttf 166 kB [emitted] \n img/mobile.8891a7c.png 39.6 kB [emitted] \n img/play_button.6b15900.png 14.8 kB [emitted] \n img/keyword-back.f95e10a.jpg 43.4 kB [emitted] \n fonts/icomoon.16db67c.woff 2.49 kB [emitted] \n fonts/icomoon.2fcbf50.eot 2.58 kB [emitted] \n fonts/fontawesome-webfont.674f50d.eot 166 kB [emitted] \n fonts/fontawesome-webfont.fee66e7.woff 98 kB [emitted] \n\n.\n.\n.\n```\n\n```text\n// Does not work\n{\n ...\n build: {\n ...\n extend (config, { isClient }) {\n ...\n if (process.env.NODE_ENV === 'test') {\n config.stats = 'errors-only'\n }\n }\n }\n ...\n}\n```\n\n```text\n// Works, but does not hide warnings\n{\n ...\n build: {\n stats: process.env.NODE_ENV === 'test' ? 'errors-only' {\n chunks: false,\n children: false,\n modules: false,\n colors: true,\n assets: true,\n warnings: true,\n errors: true,\n excludeAssets: [\n /.map$/,\n /index\\..+\\.html$/,\n /vue-ssr-client-manifest.json/\n ]\n },\n ...\n }\n ...\n}\n```\n\n```text\nWARNING Compiled with 2 warnings\n\n warning \n\nasset size limit: The following asset(s) exceed the recommended size limit (300 kB).\nThis can impact web performance.\nAssets: \n img/fontawesome-webfont.912ec66.svg (444 kB)\n vendor.4db9bb219a2a9c02d939.js (726 kB)\n app.f14777ec0017fec245a3.js (546 kB)\n\n warning \n\nentrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (1 MB). This can impact web performance.\nEntrypoints:\n app (1.27 MB)\n manifest.4eb49c6cde9aa836f4d4.js\n vendor.4db9bb219a2a9c02d939.js\n app.f14777ec0017fec245a3.js\n```\n\n```text\nava\n```\n\n```text\nstats\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nbuild: {\n\n stats: process.env.NODE_ENV === 'test' ? 'errors-only' : { // default config here for non test build. Nuxt default could be seen here\n https://github.com/nuxt/nuxt.js/blob/567dc860c1393ccf0e849b032b69edddd5b6b7bb/lib/common/nuxt.config.js#L93\n }\n\n ...\n }\n```\n\n```text\nmodule.exports = {\n devServer: {\n stats: {\n colors: true,\n hash: false,\n version: false,\n timings: false,\n assets: false,\n chunks: false,\n modules: false,\n reasons: false,\n children: false,\n source: false,\n errors: false,\n errorDetails: false,\n warnings: false,\n publicPath: false\n }\n }\n}\n```\n\n```text\nhash\n```\n\n```text\nversion\n```\n\n```text\ntimings\n```\n\n```text\nassets\n```\n\n```text\nchunks\n```\n\n========================================\n\nComments:\n- It's not about webpack. It's about nuxt. Nuxt have a custom.erbpack builder and apply webpack config itself\n- Oh, I thought Nuxt could inherit a base webpack config. My mistake.\n- it works! except the `exceed the recommended size limit` warnings, it does hide all printed assets. they should have mentioned these configs in their documentation.\n- do you know how to hide the warnings? it would make your answer complete\n- @Dipu you could provide full config instead of errors-only, where you could set it individually e.g. warnings: false . Or you could just set it to false\n- I tested with full-configs, it does not work. warnings are there no matter what\n- @Dipu well, false will disable whole stat module.\n- I have done that. but the warnings will not stop. what is actually going on here! is nuxt modifying the stats property elsewhere?\n- @Dipu I tried with nuxt-edge and I don't see anything from stats module with false.\n- I was using `nuxt 1.4.1`. they had some bug I guess\n- @Dipu might be, you can try use edge, it will be released soon and stable already","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":304,"estimatedTokens":1856}}467{"id":"stack-59504190","source":"stackoverflow","questionId":59504190,"title":"Why do images that refer to static nuxt assets that don't exist not trigger @error?","tags":["vue.js","nuxt.js"],"text":"Title: Why do images that refer to static nuxt assets that don't exist not trigger @error?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a nuxt application, and in it, I have an image tag where the source attribute refers to a nuxt static asset. \n\n```\n\n```\n\nIf the image exists, it works as expected. If the image does not exist, I get a 404, which should trigger my @error handler, but it doesn't. It seems the problem is the fact that it's pointing to a nuxt static asset, because if I change the src to be `:src=\"'foo'\"`, it triggers the error handler as expected.\n\n========================================\n\nTop Answer:\nWhen you use dynamic images like in your case with `:src=\"`/players/face/${player.name}.png`\"` you have to store them in `assets` so that webpack can process them, not in the static folder.\n\nMove them to the assets folder and update your links to:\n`:src=\"`~/assets/players/face/${player.name}.png`\"`\n\n========================================\n\nCode:\n```text\n<img\n class=\"player-face\"\n :src=\"`/players/face/${player.name}.png`\"\n @error=\"myFunction\"\n />\n```\n\n```text\n:src=\"'foo'\"\n```\n\n```text\nrender: { fallback: false }\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n:src=\"`/players/face/${player.name}.png`\"\n```\n\n```text\nassets\n```\n\n```text\n:src=\"`~/assets/players/face/${player.name}.png`\"\n```\n\n========================================\n\nComments:\n- This didn't work for me, do you have any other suggestions? Nuxt v2.14.1","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":60,"estimatedTokens":368}}468{"id":"stack-50215163","source":"stackoverflow","questionId":50215163,"title":"VueJS - VueX and flash messages","tags":["vue.js","vuex","nuxt.js"],"text":"Title: VueJS - VueX and flash messages\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI use **VueJS 2**, **VueX**, **NuxtJS** and **Vue-Snotify** (artemsky/vue-snotify) for flash notifications.\n\nIt may not be the correct use of VueX, but I'd like to **dispatch** the errors caught in a try/catch.\n\n```\ntry {\n throw new Error('test')\n} catch (error) {\n this.$store.dispatch('errorHandler', error)\n}\n```\n\nThen the dispatch, with VueX should display the notifications with Snotify-View with a loop if there are several errors.\n\n```\nactions: {\n async errorHandler (error) {\n this.$snotify.error(error)\n // and if multiple errors, then while on error\n }\n}\n```\n\nWhat do you think and how to recover the instance of $snotify in VueX?\n\n========================================\n\nCode:\n```text\ntry {\n throw new Error('test')\n} catch (error) {\n this.$store.dispatch('errorHandler', error)\n}\n```\n\n```text\nactions: {\n async errorHandler (error) {\n this.$snotify.error(error)\n // and if multiple errors, then while on error\n }\n}\n```\n\n```text\nactions: {\n nuxtServerInit ({ state }, { app }) {\n // Workaround\n state.Snotify = app.$snotify // inject the context in the store\n },\n // Then, you can called as you want\n // There is not necessity to prefix the method with async keyword\n errorHandler ({ state }, message) {\n state.Snotify.error(message)\n }\n}\n```\n\n```text\nstate: {\n flash: null\n}\nmutations: {\n // Just extract message from the context that you are set before\n SET_ERROR (state, { message, title = 'Something happens!' }) {\n state.flash = { \n type: 'error',\n title, \n message\n }\n },\n FLUSH_FLASH (state) {\n state.flash = null\n }\n}\n```\n\n```text\n<template>\n <vue-snotify />\n ...\n</template>\n\n<script>\n export default {\n // I use fetch because this is the lifecycle hook that executes \n // immediately before page render is sure. And its purpose is to fill\n // the store before page render. But, to the best of my knowledge, \n // this is the only place that you could use to trigger an immediately\n // executed function at the beginning of page render. However, also\n // you could use a middleware instead or \"preferably use a wrapper \n // component and get leverage of component lifecycle and use `mounted`\" [4]\n fetch({ app, store }) {\n if (store.state.flash) {\n const { type, title, message: body } = store.state.flash\n const toast = app.$snotify[type](body, title)\n\n toast.on('destroyed', (t) => { store.commit('FLUSH_FLASH') })\n }\n },\n data: () => ({\n ...\n })\n</script>\n```\n\n```text\n<template>\n <vue-snotify />\n ...\n</template>\n\n<script>\n export default {\n data: () => ({\n ...\n }),\n // Show the flash at the beginning when it's necessary\n mounted: {\n if (this.notification) {\n const { type, title, message: body } = this.notification\n const toast = this.$snotify[type](body, title)\n\n toast.on('destroyed', (t) => { this.$store.commit('FLUSH_FLASH') })\n }\n },\n computed: {\n notification () {\n return this.$store.state.flush\n }\n }\n</script>\n```\n\n```text\nthis.app.$snotify\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nmounted\n```\n\n========================================\n\nComments:\n- I wouldn't use a vuex action if the code isn't going to affect the vuex state.\n- Ok, I see... But how I can make a component to trait all errors?\n- Add errors to an error stack (in Vuex), have a component on the page that interacts with the error stack and displays them using $snotify. Also thanks for the snort this morning with the name of that library :)\n- Thanks @Bert, but how I can get error stack from VueX? With setTimeout()? :)\n- You could get it from Vuex the same way you get anything from Vuex; using a getter. Your component would probably watch to call snotify when the stack changes.","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":160,"estimatedTokens":1032}}469{"id":"stack-52124828","source":"stackoverflow","questionId":52124828,"title":"Cross-Origin Read Blocking (CORB) when get data from Directions API using axios with Nuxt js","tags":["ajax","cors","axios","nuxt.js","vue2-google-maps"],"text":"Title: Cross-Origin Read Blocking (CORB) when get data from Directions API using axios with Nuxt js\nTags: ajax, cors, axios, nuxt.js, vue2-google-maps\nSource: Stack Overflow\n\nQuestion:\nIn my Nuxt project, I use vue2-google-maps library to create map and axios to get data from Map API.\nI want to get distance between 2 location in google map, so i use Directions API: https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood&key=API_KEY. \nWhen I use it with Insomnia, I retrieved data normally, like below picture:\n\nhttps://i.sstatic.net/LMeDk.png\n\nBut when i use it with nuxt using axios, I get some error like:\n\nhttps://i.sstatic.net/5WW8p.jpg\n\n No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.\n\n \n Cross-Origin Read Blocking (CORB) blocked cross-origin response https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood&key=API_KEY with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.\n\nBut if i use Geocoding API with nuxt, it work normally\nI tried adding header Access-Control-Allow-Origin=* but still get errors.\nI don’t know why i get these errors.\nMy code:\n\n\r\n\r\n\n```\naxios\r\n .get('https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood&key=API_KEY')\r\n .then(res => {\r\n console.log(\"Res: \");\r\n console.log(res)\r\n })\r\n .catch(err => console.log(err));\n```\n\n\r\n\r\n\r\n\nPlease help me.\nThank you!!!\n\n========================================\n\nCode:\n```js\naxios\n .get('https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood&key=API_KEY')\n .then(res => {\n console.log(\"Res: \");\n console.log(res)\n })\n .catch(err => console.log(err));\n```\n\n```text\naxios: {\n baseURL: 'https://maps.googleapis.com/maps/api',\n proxyHeaders: false,\n credentials: false\n}\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- I tried your guide like: in my nuxt.config.js: modules: [ '@nuxtjs/axios', ], axios: { baseURL: ' maps.googleapis.com/maps/api ', proxyHeaders: false, credentials: false }, But i still got these errors\n- @NguyễnVănĐại See google maps API you are using is a Server side API. That's why `Access-Control-Allow-Origin` header is not present.You need to make use of client-side JS library\n- Do mark the answer verified if this solves your problem. Cheers\n- But why i use Geocoding API with axios in Nuxt, it work normally @Bharathvaj Ganesan\n- It looks like this API is been hit only on the client side i.e browser. It should have been hit on the server side before serving to the browser.\n- Thank you. I use DirectionsService, and that fixed my problem. This is the link for my question: github.com/xkjyeah/vue-google-maps/issues/174","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":79,"estimatedTokens":738}}470{"id":"stack-74898508","source":"stackoverflow","questionId":74898508,"title":"is it possible to use nuxt3 with quasar framework","tags":["vue.js","nuxt.js","nuxt3.js","quasar"],"text":"Title: is it possible to use nuxt3 with quasar framework\nTags: vue.js, nuxt.js, nuxt3.js, quasar\nSource: Stack Overflow\n\nQuestion:\nI'm very new to nuxt3 and want to know if i't possible to use it with quasar. specially that quasar has his own ssr system .\ndoes anyone successfully created a project with these two frameworks ?\n\ni tried to look if there is any open source projects with these two frameworks but i couldn't find anything useful\n\n========================================\n\nTop Answer:\nThere is a module available that let's you use Quasar UI with Nuxt 3.\n\nI'm using it and it works great.\n\n========================================\n\nComments:\n- i want to use quasar only for the ui ( components ) i don't see why it's not wise the use them both\n- @CSharp-n it's like mixing PHP and Ruby on Rails. You can add material UI components to Nuxt without the need to use Quasar.\n- @CSharp-n Vuetify is great for Nuxt. Since the rest of Quasar (but the components) will not be used. No point into bringing the whole framework to Nuxt. Here you go: next.vuetifyjs.com/en/getting-started/installation/#ssr\n- It's unofficial.\n- Yea your'e right, my bad! Corrected my answer, thank you :)\n- I can testify that Nuxt-Quasar works perfectly! I'm migrating from Vuetify to Quasar and this plugin provides everything I could want\n- If its unofficial is there concern that it wont be updated and break as nuxt or quasar update not in sync?\n- Yep that risk always exists in the world of open source, however I believe that if it happens someone will fork it and make the necassary changes to make it work(maybe it could even be me or you, who knows!)","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":28,"estimatedTokens":411}}471{"id":"stack-72514851","source":"stackoverflow","questionId":72514851,"title":"Does Nuxtjs3 support NuxtServerInit","tags":["nuxt.js","vuejs3","server-side-rendering","nuxt3.js","pinia"],"text":"Title: Does Nuxtjs3 support NuxtServerInit\nTags: nuxt.js, vuejs3, server-side-rendering, nuxt3.js, pinia\nSource: Stack Overflow\n\nQuestion:\nI used Pinia for creating a data in Nuxtjs 3. It works correctly, But I'd like to check that the data is rendered through the server not just client.\nHow can I be sure about that? and Does nuxtServerInit is supported in new version of Nuxtjs 3?\n\n========================================\n\nCode:\n```js\nexport default defineNuxtPlugin((nuxtApp) => {\n if (process.server) {\n // ...\n }\n})\n```\n\n========================================\n\nComments:\n- I think it can be improved by omitting the import (Nuxt 3 does this automatically) and removing the `if (process.server)` by naming the file like this: `{plugin-name}.server.js`. Whit this name the plugin will execute only on server side\n- Yes, You're right, they have changed it into auto-import also inside plugins etc, thanks for pointing, going to edit post","metadata":{"transformedAt":"2026-08-18T18:33:07.869Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":24,"estimatedTokens":237}}472{"id":"stack-54341251","source":"stackoverflow","questionId":54341251,"title":"render function or template not defined in component: anonymous","tags":["vue.js","socket.io","nuxt.js"],"text":"Title: render function or template not defined in component: anonymous\nTags: vue.js, socket.io, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have such a problem, after reloading the page an error occurs.\"render function or template not defined in component: anonymous\". I think the error is due to socket.io. \nWhat does this error do not occur on the local machine, but on the production. dev версия error\n\nserver.js\n\n\r\n\r\n\n```\nconst APP_ENV = require('./.env.js')\r\nconst { Nuxt, Builder } = require('nuxt')\r\nconst app = require('express')()\r\nlet server = require('http').Server(app)\r\n\r\nif(APP_ENV.ssl) {\r\n const fs = require('fs')\r\n const options = {\r\n key: fs.readFileSync(APP_ENV.ssl_key),\r\n cert: fs.readFileSync(APP_ENV.ssl_cert)\r\n }\r\n server = require('https').Server(options, app)\r\n}\r\n\r\nconst port = process.env.PORT || APP_ENV.ws_port\r\nconst isProd = process.env.NODE_ENV === 'production'\r\n\r\n// We instantiate Nuxt.js with the options\r\nlet config = require('./nuxt.config.js')\r\nconfig.dev = !isProd\r\n\r\nconst nuxt = new Nuxt(config)\r\n// Start build process in dev mode\r\nif (config.dev) {\r\n const builder = new Builder(nuxt)\r\n builder.build()\r\n}\r\napp.use(nuxt.render)\r\nif (APP_ENV.socket) {\r\n const io = require('socket.io')(server)\r\n const Redis = require('ioredis')\r\n const redis = new Redis(APP_ENV.redis.port, APP_ENV.redis.host)\r\n redis.psubscribe(['*'])\r\n redis.on('pmessage', function (subscribe, channel, message) {\r\n message = JSON.parse(message)\r\n console.log('Server: ', subscribe, channel, message.data.message)\r\n io.emit(channel + ':' + message.event, message.data)\r\n })\r\n\r\n // io.on('connection', function (socket) {\r\n // })\r\n}\r\n\r\nserver.listen(port, function () {\r\n console.log('Listening on Port ' + port)\r\n})\n```\n\n\r\n\n```\n\n```\n\n\r\n\r\n\r\n\nplugins/socket.io.js\n\r\n\r\n\n```\n``\r\n\r\nimport io from 'socket.io-client'\r\n\r\nconst socket = io(process.env.WS_URL)\r\n\r\nexport default socket\n```\n\n\r\n\n```\n\n```\n\n\r\n\r\n\r\n\nio/index.js\n\n\r\n\r\n\n```\nmodule.exports = function () {\r\n const APP_ENV = require('../.env.js')\r\n const server = require('http').createServer(this.nuxt.renderer.app)\r\n\r\n // overwrite nuxt.listen()\r\n this.nuxt.listen = (port, host) => new Promise((resolve) => server.listen(port || 3000, host || 'localhost', resolve))\r\n // close this server on 'close' event\r\n this.nuxt.hook('close', () => new Promise((resolve) => server.close(resolve)))\r\n\r\n // Add `socket.io-client` in vendor\r\n this.addVendor('socket.io-client')\r\n\r\n if (APP_ENV.socket) {\r\n const io = require('socket.io')(server)\r\n const Redis = require('ioredis')\r\n const redis = new Redis(APP_ENV.redis.port, APP_ENV.redis.host)\r\n redis.psubscribe(['*'])\r\n redis.on('pmessage', function (subscribe, channel, message) {\r\n message = JSON.parse(message)\r\n console.log('Server: ', subscribe, channel, message.data.message)\r\n io.emit(channel + ':' + message.event, message.data)\r\n })\r\n\r\n // io.on('connection', function (socket) {\r\n // })\r\n }\r\n}\n```\n\n\r\n\n```\n\n```\n\n\r\n\r\n\r\n\nmessage/index.vue\n\n\r\n\r\n\n```\n\r\n \r\n \r\n \r\n \r\n \n\n### Мои сообщения\n\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n Входящие 0\">{{ userMessage.count }}-->\r\n Системные-->\r\n \r\n {{tab.title}}\r\n \r\n 1 -->\r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n \r\n {{ user.name[0] | uppercase }}{{ user.name[1] | uppercase }}\r\n 0\" class=\"chat-item__new-messages\">{{ user.unread }}\r\n \r\n \r\n {{ user.name }}\r\n \r\n -->\r\n -->\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n {{ chatUser.name }}\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n Отключить уведомения\r\n \r\n \r\n Очистить историю\r\n \r\n \r\n Заблокировать контакт\r\n \r\n \r\n \r\n -->\r\n \r\n \r\n \r\n {{\r\n chatMessage\r\n }}\r\n -->\r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n \r\n {{ userByIdMessage(message.sender_id).name[0] | uppercase }}{{ userByIdMessage(message.sender_id).name[1] | uppercase }}\r\n \r\n \r\n \r\n \r\n \r\n {{ userCurrent.user_name[0] | uppercase }}{{ userCurrent.user_name[1] | uppercase }}\r\n \r\n \r\n \r\n \r\n \r\n {{message.created_at}}\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n {{ chatUser.name }}\r\n \r\n -->\r\n -->\r\n -->\r\n -->\r\n -->\r\n \r\n \r\n -->\r\n -->\r\n -->\r\n \r\n \r\n \r\n -->\r\n \r\n -->\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n -->\r\n -->\r\n -->\r\n \r\n -->\r\n -->\r\n -->\r\n \r\n\r\n\r\n const DOMAIN = process.env.API_DOMAIN\r\n\r\n import socket from '@/plugins/socket.io'\r\n import { mapActions, mapGetters } from 'vuex'\r\n import api from '@/api'\r\n\r\n export default {\r\n middleware: 'authenticated',\r\n data () {\r\n return {\r\n chat_mob: false,\r\n contacts: true,\r\n tabs: {\r\n incoming: {\r\n active: true,\r\n title: 'Входящие'\r\n },\r\n systemic: {\r\n active: false,\r\n title: 'Системные'\r\n }\r\n },\r\n virtualUser: false,\r\n baseUrl: DOMAIN,\r\n show: false,\r\n tabUsers: [],\r\n chatUser: null,\r\n message: '',\r\n userId: null,\r\n test: null,\r\n img: '',\r\n check: false\r\n }\r\n },\r\n beforeMount () {\r\n this.getUserMessage()\r\n if (socket) {\r\n let base = this\r\n socket.on(this.userCurrent.id +':new-user-message', (message) => {\r\n base.setSocketMessage({\r\n sender_id: message.message.from_id,\r\n message: message.message.message\r\n })\r\n base.setMessageCount({\r\n user_id: message.message.from_id\r\n }\r\n )\r\n base.setUserUnreadMessage({\r\n count: this.userCurrent.unread_messages + 1\r\n }\r\n )\r\n this.scrollToBottom()\r\n })\r\n }\r\n },\r\n computed: {\r\n ...mapGetters({\r\n getContact: 'message/getContact',\r\n idUserMessage: 'message/id',\r\n userMessage: 'message/userMessage',\r\n chatMessage: 'message/chatMessage',\r\n userByIdMessage: 'message/userByIdMessage',\r\n userCurrent: 'user/user'\r\n }),\r\n activeTab () {\r\n let index = null\r\n if (this.idUserMessage !== null && this.userMessage !== [] && this.userMessage.users !== undefined) {\r\n const user = this.userMessage.users.find(users => users.id === this.idUserMessage)\r\n index = this.userMessage.users.indexOf(user)\r\n }\r\n return index\r\n }\r\n },\r\n methods: {\r\n ...mapActions({\r\n setUserUnreadMessage: 'user/setUserUnreadMessage',\r\n setUsers: 'message/setUsers',\r\n addUser: 'message/addUser',\r\n setMessageCount: 'message/setMessageCount',\r\n setUnread: 'message/setUnread',\r\n getUserMessage: 'message/getUserMessage',\r\n getChatMessage: 'message/getChatMessage',\r\n createMessage: 'message/createMessage',\r\n setStoreId: 'message/setStoreId',\r\n setSocketMessage: 'message/setSocketMessage'\r\n }),\r\n checkMessage (id) {\r\n if (this.idUserMessage !== null && this.userMessage !== [] && this.userMessage.users !== undefined){\r\n const user = this.userMessage.users.find(users => users.id === id)\r\n let index = this.userMessage.users.indexOf(user)\r\n if(index === this.activeTab || id === this.userCurrent.id)\r\n return true\r\n else\r\n return false\r\n }\r\n\r\n },\r\n chatBack () {\r\n this.chat_mob = true\r\n this.contacts = true\r\n console.log(123)\r\n },\r\n changeTab (index) {\r\n console.log(index)\r\n for (let key in this.tabs) {\r\n this.tabs[key].active = false\r\n }\r\n this.tabs[index].active = true\r\n },\r\n readMessage(id) {\r\n this.check = true\r\n const payload = {\r\n user_id: id\r\n }\r\n api.readMessage(payload)\r\n .then(() => {\r\n this.setUnread(payload)\r\n\r\n })\r\n },\r\n chengeTab(index, id) {\r\n if(window.innerWidth '+ link[0] + '')\r\n }\r\n return myMessage\r\n },\r\n async onSendMessage() {\r\n if (this.message !== '' && this.userId > 0 || this.img !=='') {\r\n this.message = this.linkMessage(this.message)\r\n this.message = this.message + this.img\r\n const payload = {\r\n message: this.message,\r\n id: this.userId\r\n }\r\n console.log(payload)\r\n this.scrollToBottom()\r\n this.setSocketMessage({\r\n sender_id: this.userCurrent.id,\r\n message: payload.message\r\n })\r\n await this.createMessage(payload)\r\n this.message = ''\r\n this.img = ''\r\n }\r\n },\r\n scrollToBottom() {\r\n this.$nextTick(() => {\r\n let base = this\r\n setTimeout(() => {\r\n base.$refs.chatBody.getElementsByClassName('simplebar-scroll-content')[0].scrollTop = document.getElementById('message-container').scrollHeight\r\n }, 500)\r\n // console.log(document.getElementById('message-container').scrollHeight)\r\n })\r\n },\r\n uploadImg (e) {\r\n var file = e.target.files[0]\r\n const formData = new FormData()\r\n formData.append('image', file)\r\n api.loadImageChat(formData)\r\n .then(res => {\r\n //this.img = '\n' +'' + DOMAIN + 'message-files/' + res.body.data +''\r\n this.img = '\n' +''\r\n })\r\n },\r\n },\r\n watch: {\r\n userMessage: {\r\n handler (val) {\r\n if(!this.check) {\r\n this.tabUsers = []\r\n if (val !== [] && this.userMessage) {\r\n if (this.activeTab !== null && this.idUserMessage !== null) {\r\n this.chengeTab(this.activeTab, this.idUserMessage)\r\n } else if (this.userMessage.count !== undefined) {\r\n this.chengeTab(0, this.userMessage.users[0].id)\r\n }\r\n\r\n if (val.users !== undefined) {\r\n this.virtualUser = true\r\n if(this.getContact){\r\n if(!(val.users.find(user => user.id === this.getContact.id))){\r\n const payload = this.getContact\r\n this.addUser(payload)\r\n // this.userIndex = this.userMessage.users.length - 1\r\n this.chengeTab(this.userMessage.users.length - 1, this.getContact.id)\r\n }\r\n else{\r\n let user = val.users.find(user => user.id === this.getContact.id)\r\n this.userIndex = val.users.indexOf(user)\r\n this.chengeTab(this.userIndex, this.userMessage.users[this.userIndex].id)\r\n }\r\n }\r\n for (let key in val.users) {\r\n let b = parseInt(key) === 0 ? true : false\r\n this.tabUsers.push(b)\r\n }\r\n if(!this.getContact || !this.virtualUser) {\r\n console.log(123)\r\n this.chatUser = val.users[0]\r\n }\r\n else {\r\n this.virtualUser = false\r\n }\r\n }\r\n }\r\n }\r\n },\r\n deep: true\r\n }\r\n }\r\n }\r\n\n```\n\n\r\n\n```\n\n```\n\n========================================\n\nTop Answer:\nI had this problem using nuxt, my components were like:\n\n```\nexport default {\n name: \"blog-post-header\",\n components: {\n NewsletterInput\n },\n ...\n```\n\nTo me, the problem was solved by removing the `components` object from all the components of my project:\n\n```\nexport default {\n name: \"blog-post-header\",\n ...\n```\n\n========================================\n\nCode:\n```js\nconst APP_ENV = require('./.env.js')\nconst { Nuxt, Builder } = require('nuxt')\nconst app = require('express')()\nlet server = require('http').Server(app)\n\nif(APP_ENV.ssl) {\n const fs = require('fs')\n const options = {\n key: fs.readFileSync(APP_ENV.ssl_key),\n cert: fs.readFileSync(APP_ENV.ssl_cert)\n }\n server = require('https').Server(options, app)\n}\n\nconst port = process.env.PORT || APP_ENV.ws_port\nconst isProd = process.env.NODE_ENV === 'production'\n\n// We instantiate Nuxt.js with the options\nlet config = require('./nuxt.config.js')\nconfig.dev = !isProd\n\nconst nuxt = new Nuxt(config)\n// Start build process in dev mode\nif (config.dev) {\n const builder = new Builder(nuxt)\n builder.build()\n}\napp.use(nuxt.render)\nif (APP_ENV.socket) {\n const io = require('socket.io')(server)\n const Redis = require('ioredis')\n const redis = new Redis(APP_ENV.redis.port, APP_ENV.redis.host)\n redis.psubscribe(['*'])\n redis.on('pmessage', function (subscribe, channel, message) {\n message = JSON.parse(message)\n console.log('Server: ', subscribe, channel, message.data.message)\n io.emit(channel + ':' + message.event, message.data)\n })\n\n // io.on('connection', function (socket) {\n // })\n}\n\nserver.listen(port, function () {\n console.log('Listening on Port ' + port)\n})\n```\n\n```html\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"></script>\n```\n\n```js\n``\n\nimport io from 'socket.io-client'\n\nconst socket = io(process.env.WS_URL)\n\nexport default socket\n```\n\n```html\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"></script>\n```\n\n```js\nmodule.exports = function () {\n const APP_ENV = require('../.env.js')\n const server = require('http').createServer(this.nuxt.renderer.app)\n\n // overwrite nuxt.listen()\n this.nuxt.listen = (port, host) => new Promise((resolve) => server.listen(port || 3000, host || 'localhost', resolve))\n // close this server on 'close' event\n this.nuxt.hook('close', () => new Promise((resolve) => server.close(resolve)))\n\n // Add `socket.io-client` in vendor\n this.addVendor('socket.io-client')\n\n if (APP_ENV.socket) {\n const io = require('socket.io')(server)\n const Redis = require('ioredis')\n const redis = new Redis(APP_ENV.redis.port, APP_ENV.redis.host)\n redis.psubscribe(['*'])\n redis.on('pmessage', function (subscribe, channel, message) {\n message = JSON.parse(message)\n console.log('Server: ', subscribe, channel, message.data.message)\n io.emit(channel + ':' + message.event, message.data)\n })\n\n // io.on('connection', function (socket) {\n // })\n }\n}\n```\n\n```html\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"></script>\n```\n\n```js\n<template>\n <div class=\"my-messages\">\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col\">\n <h3>Мои сообщения</h3>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col\">\n <div class=\"chat-wrap\">\n <div class=\"chat-tabs__content active\">\n <div class=\"chat-tabs\">\n <!--<div class=\"chat-tabs__item active\">Входящие <span v-if=\"userMessage.count > 0\">{{ userMessage.count }}</span></div>-->\n <!--<div class=\"chat-tabs__item\">Системные-->\n <div v-for=\"(tab,index) in tabs\" :key=\"index\">\n <div class=\"chat-tabs__item\" @click=\"changeTab(index)\" :class=\"{'chat-tabs__item active': tab.active}\">{{tab.title}}\n </div>\n <!-- <span>1</span> -->\n </div>\n </div>\n <div class=\"chats-list\">\n <div class=\"chats-list__body\" data-simplebar >\n <div class=\"\">\n\n <div class=\"chat-item\" v-if=\"user.name != 'Системные' && tabs.incoming.active\" @click.stop=\"chengeTab(index, user.id)\" :class=\"{ active: tabUsers[index] }\" v-for=\"(user, index) in userMessage.users\" :key=\"index\">\n <div class=\"chat-item__ava\">\n <img v-if=\"user.user_avatar_path\" :src=\"baseUrl + 'items-original/' + user.user_avatar_path\" :alt=\"user.name\">\n <span v-else>{{ user.name[0] | uppercase }}{{ user.name[1] | uppercase }}</span>\n <div v-if=\"user.unread > 0\" class=\"chat-item__new-messages\">{{ user.unread }}</div>\n </div>\n <div class=\"chat-item__interlocutor\">\n {{ user.name }}\n </div>\n <!--<div class=\"chat-item__last-messages\" v-html=\"user.message\">-->\n <!--</div>-->\n <div class=\"chat-item__data\">\n <!-- 13:25 -->\n </div>\n </div>\n </div>\n </div>\n </div>\n <div v-if=\"!chat_mob\" class=\"chats\">\n <div class=\"chat-body active\">\n <div class=\"chat\">\n <div class=\"chat__header\">\n <div class=\"chat__interlocutor\">\n <div class=\"chat-back\" @click=\"chatBack\">\n <svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\n width=\"14.617px\" height=\"8px\" viewBox=\"0 0 14.617 8\" style=\"enable-background:new 0 0 14.617 8;\" xml:space=\"preserve\">\n <path style=\"fill:#DDE1E6;\" d=\"M10.585,5.447c-0.85,0-1.7,0.013-2.549-0.003C6.603,5.418,6.419,5.531,6.489,6.973\n c0.008,0.158-0.011,0.312-0.052,0.468C6.303,7.95,5.766,8.159,5.32,7.867C4.009,7.009,2.699,6.15,1.388,5.291\n c-0.321-0.21-0.65-0.41-0.966-0.628C-0.131,4.282-0.146,3.7,0.41,3.332C2.011,2.271,3.626,1.23,5.23,0.171\n C5.909-0.278,6.516,0.224,6.49,0.896C6.48,1.153,6.489,1.41,6.489,1.667c0,0.58,0.288,0.871,0.864,0.871c2.135,0,4.269,0,6.404,0\n c0.573,0,0.859,0.291,0.86,0.876c0,0.415,0.003,0.83-0.001,1.245c-0.004,0.475-0.322,0.787-0.798,0.788\n C12.74,5.447,11.663,5.447,10.585,5.447z\"/>\n </svg>\n </div>\n <div v-if=\"chatUser && (chatUser.name != 'Системные' && tabs.incoming.active )\">{{ chatUser.name }}</div>\n </div>\n <!-- <div class=\"chat__actions\">\n <div class=\"chat-menu\">\n <div class=\"chat-menu__icon\" @click.prevent=\"show = !show\">\n <svg class=\"icon-svg icon-svg-header-chat-menu\"><use xlink:href=\"/img/sprite.svg#header-chat-menu\"></use></svg>\n </div>\n <ul class=\"chat-menu__dropdown\" :class=\"{ show: show }\">\n <li>\n Отключить уведомения\n </li>\n <li>\n Очистить историю\n </li>\n <li>\n Заблокировать контакт\n </li>\n </ul>\n </div>\n </div> -->\n </div>\n <div class=\"chat__body\" data-simplebar ref=\"chatBody\">\n <!-- <pre>\n {{\n chatMessage\n }}\n </pre> -->\n <div id=\"message-container\" v-if=\"chatMessage !== []\">\n <div class=\"message_wrapper\" v-if=\"checkMessage(message.sender_id) && (message.sender_id != null && tabs.incoming.active)\" v-for=\"(message, index) in chatMessage\" :key=\"index\">\n <div class=\"message\" :class=\"{ 'message--to': userCurrent.id === message.sender_id, 'message--from': userCurrent.id !== message.sender_id }\">\n <div class=\"message__post-data\"></div>\n\n <div class=\"chat-item__ava message__ava\" v-if=\"userByIdMessage(message.sender_id)\" >\n <img v-if=\"userByIdMessage(message.sender_id).user_avatar_path !== null\" :src=\"baseUrl + 'items-original/' + userByIdMessage(message.sender_id).user_avatar_path\" alt=\"\" class=\"\">\n <div v-else >\n <span>{{ userByIdMessage(message.sender_id).name[0] | uppercase }}{{ userByIdMessage(message.sender_id).name[1] | uppercase }}</span>\n </div>\n </div>\n <div class=\"chat-item__ava message__ava\" v-else>\n <img v-if=\"userCurrent.user_avatar_path !== null\" :src=\"baseUrl + 'items-original/' + userCurrent.user_avatar_path\" alt=\"\" class=\"\">\n <div v-else>\n <span>{{ userCurrent.user_name[0] | uppercase }}{{ userCurrent.user_name[1] | uppercase }}</span>\n </div>\n </div>\n <div class=\"message__text\" v-html=\"message.message\" >\n </div>\n </div>\n <div class=\"chat-item__last-messages\" :class=\"{ 'created_time_to': userCurrent.id === message.sender_id, 'created_time_from': userCurrent.id !== message.sender_id }\">{{message.created_at}}</div>\n </div>\n </div>\n </div>\n <form class=\"chat__form\">\n <textarea placeholder=\"Введите сообщение...\" @keyup.ctrl.enter=\"onSendMessage\" v-model=\"message\"></textarea>\n <div v-html=\"img\"></div>\n <div class=\"chat__form-controls\">\n <div class=\"add-additions\">\n <label class=\"message_img\" for=\"image\"><img src=\"/img/affix.svg\" alt=\"\"></label>\n <input class=\"img_input\" id=\"image\" type=\"file\" accept=\"image/png, image/jpeg, image/gif, image/jpg\" @change=\"uploadImg($event)\">\n </div>\n <button @click.prevent=\"onSendMessage\" >\n <img src=\"/img/telega.svg\" alt=\"\">\n </button>\n </div>\n </form>\n </div>\n <div class=\"interlocutor\" v-if=\"chatUser\">\n <img\n v-if=\"chatUser.user_avatar_path\"\n :src=\"baseUrl + 'items-original/' + chatUser.user_avatar_path\"\n :alt=\"chatUser.name\"\n class=\"interlocutor__img\">\n <img v-else\n src=\"/img/avatar.svg\"\n :alt=\"chatUser.name\"\n class=\"interlocutor__img default_ava\">\n\n <div class=\"interlocutor__title\">\n {{ chatUser.name }}\n </div>\n <!--<ul class=\"interlocutor__info\">-->\n <!--<li>-->\n <!--<span>-->\n <!--<img src=\"/img/marker-icon.svg\" alt=\"\">-->\n <!--</span>-->\n <!--115280, Москва,-->\n <!--ул. Ленинская слобода, д. 19-->\n <!--</li>-->\n <!--</ul>-->\n <!--<p class=\"interlocutor__text\">-->\n <!--На сайте 5 мин., выставленно-->\n <!--10 товаров. Время с момента регистрации 3 месяца.-->\n <!--</p>-->\n <!--<a href=\"#\" class=\"btn btn--xl btn--border\">-->\n <!--Перейти к заказу-->\n <!--</a>-->\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n <!--<div class=\"container\" v-else>-->\n <!--<div class=\"row\">-->\n <!--<div class=\"col\">-->\n <!--<h3>Сообщений нет</h3>-->\n <!--</div>-->\n <!--</div>-->\n <!--</div>-->\n </div>\n</template>\n<script>\n const DOMAIN = process.env.API_DOMAIN\n\n import socket from '@/plugins/socket.io'\n import { mapActions, mapGetters } from 'vuex'\n import api from '@/api'\n\n export default {\n middleware: 'authenticated',\n data () {\n return {\n chat_mob: false,\n contacts: true,\n tabs: {\n incoming: {\n active: true,\n title: 'Входящие'\n },\n systemic: {\n active: false,\n title: 'Системные'\n }\n },\n virtualUser: false,\n baseUrl: DOMAIN,\n show: false,\n tabUsers: [],\n chatUser: null,\n message: '',\n userId: null,\n test: null,\n img: '',\n check: false\n }\n },\n beforeMount () {\n this.getUserMessage()\n if (socket) {\n let base = this\n socket.on(this.userCurrent.id +':new-user-message', (message) => {\n base.setSocketMessage({\n sender_id: message.message.from_id,\n message: message.message.message\n })\n base.setMessageCount({\n user_id: message.message.from_id\n }\n )\n base.setUserUnreadMessage({\n count: this.userCurrent.unread_messages + 1\n }\n )\n this.scrollToBottom()\n })\n }\n },\n computed: {\n ...mapGetters({\n getContact: 'message/getContact',\n idUserMessage: 'message/id',\n userMessage: 'message/userMessage',\n chatMessage: 'message/chatMessage',\n userByIdMessage: 'message/userByIdMessage',\n userCurrent: 'user/user'\n }),\n activeTab () {\n let index = null\n if (this.idUserMessage !== null && this.userMessage !== [] && this.userMessage.users !== undefined) {\n const user = this.userMessage.users.find(users => users.id === this.idUserMessage)\n index = this.userMessage.users.indexOf(user)\n }\n return index\n }\n },\n methods: {\n ...mapActions({\n setUserUnreadMessage: 'user/setUserUnreadMessage',\n setUsers: 'message/setUsers',\n addUser: 'message/addUser',\n setMessageCount: 'message/setMessageCount',\n setUnread: 'message/setUnread',\n getUserMessage: 'message/getUserMessage',\n getChatMessage: 'message/getChatMessage',\n createMessage: 'message/createMessage',\n setStoreId: 'message/setStoreId',\n setSocketMessage: 'message/setSocketMessage'\n }),\n checkMessage (id) {\n if (this.idUserMessage !== null && this.userMessage !== [] && this.userMessage.users !== undefined){\n const user = this.userMessage.users.find(users => users.id === id)\n let index = this.userMessage.users.indexOf(user)\n if(index === this.activeTab || id === this.userCurrent.id)\n return true\n else\n return false\n }\n\n },\n chatBack () {\n this.chat_mob = true\n this.contacts = true\n console.log(123)\n },\n changeTab (index) {\n console.log(index)\n for (let key in this.tabs) {\n this.tabs[key].active = false\n }\n this.tabs[index].active = true\n },\n readMessage(id) {\n this.check = true\n const payload = {\n user_id: id\n }\n api.readMessage(payload)\n .then(() => {\n this.setUnread(payload)\n\n })\n },\n chengeTab(index, id) {\n if(window.innerWidth < 768) {\n this.chat_mob = false\n }\n console.log(index, id)\n this.readMessage(id)\n for (let key in this.userMessage.users) {\n this.tabUsers[key] = false\n }\n this.chatUser = this.userMessage.users[index]\n this.tabUsers[index] = true\n this.tabUsers.push()\n this.getChatMessage({\n user_id: id\n })\n this.setStoreId(id)\n this.userId = id\n this.scrollToBottom()\n },\n linkMessage (message) {\n let reg = /(https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\s]{2,}|www\\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\s]{2,}|https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9]\\.[^\\s]{2,}|www\\.[a-zA-Z0-9]\\.[^\\s]{2,})/\n let link = message.match(reg)\n let myMessage = message\n if(link){\n myMessage = message.replace(link[0], '<a href =\"'+link[0]+ '\">'+ link[0] + '</a>')\n }\n return myMessage\n },\n async onSendMessage() {\n if (this.message !== '' && this.userId > 0 || this.img !=='') {\n this.message = this.linkMessage(this.message)\n this.message = this.message + this.img\n const payload = {\n message: this.message,\n id: this.userId\n }\n console.log(payload)\n this.scrollToBottom()\n this.setSocketMessage({\n sender_id: this.userCurrent.id,\n message: payload.message\n })\n await this.createMessage(payload)\n this.message = ''\n this.img = ''\n }\n },\n scrollToBottom() {\n this.$nextTick(() => {\n let base = this\n setTimeout(() => {\n base.$refs.chatBody.getElementsByClassName('simplebar-scroll-content')[0].scrollTop = document.getElementById('message-container').scrollHeight\n }, 500)\n // console.log(document.getElementById('message-container').scrollHeight)\n })\n },\n uploadImg (e) {\n var file = e.target.files[0]\n const formData = new FormData()\n formData.append('image', file)\n api.loadImageChat(formData)\n .then(res => {\n //this.img = '<br>' +'<a href=\"' + DOMAIN + 'message-files/' + res.body.data +'\" target=\"_blank\"><img class=\"load_img\" src=\"'+ DOMAIN + 'message-files/' + res.body.data +'\"></a>'\n this.img = '<br>' +'<div class=\"load_img_wrapper\"><img class=\"load_img\" src=\"'+ DOMAIN + 'message-files/' + res.body.data +'\"></div>'\n })\n },\n },\n watch: {\n userMessage: {\n handler (val) {\n if(!this.check) {\n this.tabUsers = []\n if (val !== [] && this.userMessage) {\n if (this.activeTab !== null && this.idUserMessage !== null) {\n this.chengeTab(this.activeTab, this.idUserMessage)\n } else if (this.userMessage.count !== undefined) {\n this.chengeTab(0, this.userMessage.users[0].id)\n }\n\n if (val.users !== undefined) {\n this.virtualUser = true\n if(this.getContact){\n if(!(val.users.find(user => user.id === this.getContact.id))){\n const payload = this.getContact\n this.addUser(payload)\n // this.userIndex = this.userMessage.users.length - 1\n this.chengeTab(this.userMessage.users.length - 1, this.getContact.id)\n }\n else{\n let user = val.users.find(user => user.id === this.getContact.id)\n this.userIndex = val.users.indexOf(user)\n this.chengeTab(this.userIndex, this.userMessage.users[this.userIndex].id)\n }\n }\n for (let key in val.users) {\n let b = parseInt(key) === 0 ? true : false\n this.tabUsers.push(b)\n }\n if(!this.getContact || !this.virtualUser) {\n console.log(123)\n this.chatUser = val.users[0]\n }\n else {\n this.virtualUser = false\n }\n }\n }\n }\n },\n deep: true\n }\n }\n }\n</script>\n```\n\n```html\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"></script>\n```\n\n```text\n<no-ssr>\n```\n\n```text\nssr: false\n```\n\n```text\n<no-ssr>\n```\n\n```text\nexport default {\n name: \"blog-post-header\",\n components: {\n NewsletterInput\n },\n ...\n```\n\n```text\nexport default {\n name: \"blog-post-header\",\n ...\n```\n\n```text\ncomponents\n```\n\n========================================\n\nComments:\n- Same error here, in my case I had added a `v-if` in the `` tag, so instead I wrapped with a `` containing the `v-if`.\n- Instead of ``, use `` See: nuxtjs.org/docs/features/nuxt-components/…\n- What if we need SSR?","metadata":{"transformedAt":"2026-08-18T18:33:07.870Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":1107,"estimatedTokens":7580}}473{"id":"stack-63870348","source":"stackoverflow","questionId":63870348,"title":"Nuxt/content - How to display a list of articles on the article page (_slug)","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Nuxt/content - How to display a list of articles on the article page (_slug)\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using the nuxt/content module to create a documentation site.\n\nOn the Nuxt blog they have one post displaying the content on a separated index.vue page and the post details on the _slug.vue page.\n\nWhat I'm trying to do is show the list of articles/posts on the same page using a different layout.\n\nHere is the folder structure I'm using:\n\n```\ncontent (folder)\n articles (folder)\n article1.md\n article2.md\n article3.md\npages (folder)\n blog (folder)\n _slug.vue\n index.vue\n```\n\nAnd that's my_slug.vue file:\n\n```\n\n \n \n \n \n \n \n \n\n### {{ article.title }}\n\n \n \n \n \n \n \n \n\n### {{ article.title }}\n\n Article last updated: {{ formatDate(article.updatedAt) }}\n\n \n\n \n \n \n \n\n### On this page\n\n \n \n \n {{ link.text }}\n \n \n \n \n \n\n export default {\n\n async asyncData({ $content, params }) {\n const articles = await $content('articles', params.slug)\n .only(['title', 'slug'])\n .sortBy('createdAt', 'asc')\n .fetch()\n\n const article = await $content('articles', params.slug).fetch()\n\n const [prev, next] = await $content('articles')\n .only(['title', 'slug'])\n .sortBy('createdAt', 'asc')\n .surround(params.slug)\n .fetch()\n\n return {\n articles,\n article,\n prev,\n next\n }\n },\n methods: {\n formatDate(date) {\n const options = { year: 'numeric', month: 'long', day: 'numeric' }\n return new Date(date).toLocaleDateString('en', options)\n }\n }\n }\n\n```\n\nIf I use the \"Display all articles\" piece of code on the index.vue page it works but together on the _slug.vue the list is now empty.\n\nHere is the index where the posts are showing up correctly:\n\n```\n\n \n \n\n### Blog Posts\n\n \n \n \n \n \n\n### {{ article.title }}\n\n \n \n \n \n \n\n export default {\n async asyncData({ $content, params }) {\n const articles = await $content('articles', params.slug)\n .only(['title', 'slug'])\n .sortBy('createdAt', 'asc')\n .fetch()\n\n return {\n articles\n }\n }\n }\n\n```\n\nAm I'm missing something?\n\n========================================\n\nCode:\n```text\ncontent (folder)\n articles (folder)\n article1.md\n article2.md\n article3.md\npages (folder)\n blog (folder)\n _slug.vue\n index.vue\n```\n\n```text\n<template>\n <div class=\"flex\">\n <aside class=\"w-1/3\">\n <ul>\n <li v-for=\"article in articles\" :key=\"article.slug\">\n <NuxtLink :to=\"{ name: 'blog-slug', params: { slug: article.slug } }\">\n <div>\n <h2>{{ article.title }}</h2>\n </div>\n </NuxtLink>\n </li>\n </ul>\n </aside>\n <main class=\"w-full\">\n <h1>{{ article.title }}</h1>\n\n <p>Article last updated: {{ formatDate(article.updatedAt) }}</p>\n\n <nuxt-content :document=\"article\" />\n\n <prev-next :prev=\"prev\" :next=\"next\" />\n </main>\n <aside class=\"w-1/3\">\n <h4>On this page</h4>\n <nav>\n <ul>\n <li v-for=\"link of article.toc\" :key=\"link.id\">\n <NuxtLink :to=\"`#${link.id}`\" :class=\"{ 'py-2': link.depth === 2, 'ml-2 pb-2': link.depth === 3 }\">{{ link.text }}</NuxtLink>\n </li>\n </ul>\n </nav>\n </aside>\n </div>\n</template>\n\n<script>\n export default {\n\n async asyncData({ $content, params }) {\n const articles = await $content('articles', params.slug)\n .only(['title', 'slug'])\n .sortBy('createdAt', 'asc')\n .fetch()\n\n const article = await $content('articles', params.slug).fetch()\n\n const [prev, next] = await $content('articles')\n .only(['title', 'slug'])\n .sortBy('createdAt', 'asc')\n .surround(params.slug)\n .fetch()\n\n return {\n articles,\n article,\n prev,\n next\n }\n },\n methods: {\n formatDate(date) {\n const options = { year: 'numeric', month: 'long', day: 'numeric' }\n return new Date(date).toLocaleDateString('en', options)\n }\n }\n }\n</script>\n```\n\n```text\n<template>\n <div>\n <h1>Blog Posts</h1>\n <ul>\n <li v-for=\"article of articles\" :key=\"article.slug\">\n <NuxtLink :to=\"{ name: 'blog-slug', params: { slug: article.slug } }\">\n <div>\n <h2>{{ article.title }}</h2>\n </div>\n </NuxtLink>\n </li>\n </ul>\n </div>\n</template>\n\n<script>\n export default {\n async asyncData({ $content, params }) {\n const articles = await $content('articles', params.slug)\n .only(['title', 'slug'])\n .sortBy('createdAt', 'asc')\n .fetch()\n\n return {\n articles\n }\n }\n }\n</script>\n\n<style>\n\n</style>\n```\n\n```js\nconst articles = await $content('articles') // instead of $content('articles', params.slug)\n .only(['title', 'slug'])\n .sortBy('createdAt', 'asc')\n .fetch()\n```\n\n```text\narticles\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.870Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":276,"estimatedTokens":1204}}474{"id":"stack-60436593","source":"stackoverflow","questionId":60436593,"title":"How to use markdown-it plugins options in nuxt.js","tags":["javascript","nuxt.js","markdown-it"],"text":"Title: How to use markdown-it plugins options in nuxt.js\nTags: javascript, nuxt.js, markdown-it\nSource: Stack Overflow\n\nQuestion:\nI'm using `@nuxtjs/markdownit` to parse markdown files, I want to enable creating permanent links feature in `'markdown-it-anchor'` plugin, I used following code in `nuxt.config.js` but not working:\n\n```\nmodules: [\n // Doc: https://axios.nuxtjs.org/usage\n '@nuxtjs/axios',\n '@nuxtjs/markdownit'\n ],\n markdownit: {\n preset: 'default',\n linkify: true,\n breaks: true,\n typographer: true,\n html: false,\n use: [\n 'markdown-it-anchor',\n 'markdown-it-attrs',\n 'markdown-it-div',\n 'markdown-it-toc-done-right',\n 'markdown-it-emoji'\n ]\n },\n 'markdown-it-anchor': {\n level: 1,\n // slugify: string => string,\n permalink: true,\n // renderPermalink: (slug, opts, state, permalink) => {},\n permalinkClass: 'header-anchor',\n permalinkSymbol: '¶',\n permalinkBefore: true\n },\n```\n\n========================================\n\nCode:\n```text\nmodules: [\n // Doc: https://axios.nuxtjs.org/usage\n '@nuxtjs/axios',\n '@nuxtjs/markdownit'\n ],\n markdownit: {\n preset: 'default',\n linkify: true,\n breaks: true,\n typographer: true,\n html: false,\n use: [\n 'markdown-it-anchor',\n 'markdown-it-attrs',\n 'markdown-it-div',\n 'markdown-it-toc-done-right',\n 'markdown-it-emoji'\n ]\n },\n 'markdown-it-anchor': {\n level: 1,\n // slugify: string => string,\n permalink: true,\n // renderPermalink: (slug, opts, state, permalink) => {},\n permalinkClass: 'header-anchor',\n permalinkSymbol: '¶',\n permalinkBefore: true\n },\n```\n\n```text\n@nuxtjs/markdownit\n```\n\n```text\n'markdown-it-anchor'\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nmarkdownit: {\n preset: 'default',\n linkify: true,\n breaks: true,\n typographer: true,\n html: false,\n use: [\n [\n 'markdown-it-anchor',\n {\n level: 1,\n // slugify: string => string,\n permalink: true,\n // renderPermalink: (slug, opts, state, permalink) => {},\n permalinkClass: 'header-anchor',\n permalinkSymbol: '¶',\n permalinkBefore: true\n }\n ],\n 'markdown-it-attrs',\n 'markdown-it-div',\n 'markdown-it-toc-done-right',\n 'markdown-it-emoji'\n ]\n },\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.870Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":111,"estimatedTokens":569}}475{"id":"stack-66505198","source":"stackoverflow","questionId":66505198,"title":"SVG doesn't render using @nuxtjs/svg","tags":["svg","nuxt.js"],"text":"Title: SVG doesn't render using @nuxtjs/svg\nTags: svg, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nUsing \"vue-svg-loader\" method to the letter in the module's docs, I get this error:\n\n[Vue warn]: Invalid Component definition:\ndata:image/svg+xml;base64,PHN2ZyB3aWR0...\n\nMy code is identical to the example.\n\nAny idea why I'm getting such error?\n\n(note that previously I tried to use the code from this answer and didn't get error, however a string \"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTMiIGhl...\" was rendered on the page instead of the actual SVG image)\n\nEDIT: below is my template's code, in `/components/global/SvgIcon.vue`.\n\n```\n\n \n\nimport ArrowRight from '~/assets/img/arrow-right.svg?inline'\n\nexport default {\n components: {\n ArrowRight\n }\n}\n\n```\n\nAnd my SVG icon is in `/assets/img/`.\n\nSVG file content:\n\n```\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <ArrowRight />\n</template>\n\n<script>\nimport ArrowRight from '~/assets/img/arrow-right.svg?inline'\n\nexport default {\n components: {\n ArrowRight\n }\n}\n</script>\n```\n\n```text\n<svg width=\"13\" height=\"20\" viewBox=\"0 0 13 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M12.3604 9.93625C12.3604 10.2924 12.2231 10.6485 11.9492 10.9201L3.32384 19.4648C2.77517 20.0083 1.88558 20.0083 1.33712 19.4648C0.788667 18.9214 0.788667 18.0403 1.33712 17.4967L8.96929 9.93625L1.33739 2.37573C0.788933 1.83218 0.788933 0.951159 1.33739 0.407866C1.88585 -0.135954 2.77543 -0.135954 3.32411 0.407865L11.9494 8.95245C12.2234 9.22412 12.3604 9.58023 12.3604 9.93625Z\" fill=\"white\"/>\n</svg>\n```\n\n```text\n/components/global/SvgIcon.vue\n```\n\n```text\n/assets/img/\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n@nuxtjs/svg\n```\n\n========================================\n\nComments:\n- Thanks, you're right I had forgotten that! But now instead of seeing the SVG image I see it's file name rendered in the DOM: `/_nuxt/fce91b3f7439fe8fc414930e5cd5b231.svg`. Any idea what's going on?\n- I was unable to reproduce the behaviour that you've described, so I've posted the minimal example on GitHub (link added to answer). See if it helps or otherwise add a Minimal, Reproducible Example.\n- Dunno what I did, but it works now. Thanks a lot :)","metadata":{"transformedAt":"2026-08-18T18:33:07.870Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":87,"estimatedTokens":556}}476{"id":"stack-67502617","source":"stackoverflow","questionId":67502617,"title":"Integrate Stripe Elements in Nuxt Js","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Integrate Stripe Elements in Nuxt Js\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nLast week I successfully integrated stripe in my react + spring boot by following this doc https://stripe.com/docs/stripe-js/react application and using in my react class component,\n\nnow I am migrating to nuxt from react and I want to integrate stripe in nuxt js.\n\nHow I use those components in my nuxt project?\n\n========================================\n\nCode:\n```text\nyarn add @stripe/stripe-js\n```\n\n```js\nexport default {\n publicRuntimeConfig: {\n stripePublishableKey: process.env.STRIPE_PUBLISHABLE_KEY,\n },\n}\n```\n\n```html\n<template>\n <div id=\"iban-element\" class=\"mt-2 stripe-iban-element\"></div>\n</template>\n\n<script>\nimport { loadStripe } from '@stripe/stripe-js/pure'\n\nloadStripe.setLoadParameters({ advancedFraudSignals: false }) // https://github.com/stripe/stripe-js#disabling-advanced-fraud-detection-signals\nlet stripe, elements\n\nexport default {\n methods: {\n async loadStripeWhenModalOpens() {\n if (!stripe) {\n stripe = await loadStripe(this.$config.stripePublishableKey)\n elements = stripe.elements()\n }\n this.$nextTick(async () => {\n const iban = elements.create('iban', {\n supportedCountries: ['SEPA'],\n placeholderCountry: 'FR',\n iconStyle: 'default',\n style: {\n ... // fancy styling\n },\n })\n // eslint-disable-next-line\n await new Promise((r) => setTimeout(r, 100)) // ugly but needed if you hard refresh the exact page where the module is imported\n iban.mount('#iban-element')\n })\n },\n\n destroyStripeIbanElement() {\n const ibanElement = elements?.getElement('iban')\n if (ibanElement) ibanElement.destroy()\n },\n },\n beforeDestroy() {\n this.destroyStripeIbanElement()\n },\n}\n</script>\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nExample.vue\n```\n\n========================================\n\nComments:\n- Currently I am migrating my whole project to nuxt so at the end i will start implementing stripe by following your steps, if i will face any issue then i will add the comment here\n- This solution is missing `` at the end.","metadata":{"transformedAt":"2026-08-18T18:33:07.870Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":84,"estimatedTokens":552}}477{"id":"stack-68565305","source":"stackoverflow","questionId":68565305,"title":"How to use vue-tel-input-vuetify in Nuxt?","tags":["javascript","vue.js","frontend","nuxt.js","vue-tel-input"],"text":"Title: How to use vue-tel-input-vuetify in Nuxt?\nTags: javascript, vue.js, frontend, nuxt.js, vue-tel-input\nSource: Stack Overflow\n\nQuestion:\nI have been trying to use vue-tel-input-vuetify in Nuxt and I have been having the issue as it is in the image below, I have also tried all the solutions in this link Github but I get the same error.\n\nAfter installation, I created a plugin file **plugins/vue-tel-input-vuetify.js** and added the following code to it.\n\n```\nimport Vue from 'vue'\nimport VueTelInputVuetify from 'vue-tel-input-vuetify'\nVue.use(VueTelInputVuetify)\n```\n\nAfter that, I added this to **nuxt.config.js**\n\n```\nplugins: [\n '~/plugins/vue-tel-input-vuetify',\n { src: '~/plugins/vue-google-charts', mode: 'client' }\n ]\n```\n\nBetween my component's script tags, I did this:\n\n```\nimport { VueTelInputVuetify } from 'vue-tel-input-vuetify'\n\nexport default {\n components: {\n VueTelInputVuetify,\n },\n...\n```\n\nAnd between my component's template tags I added this:\n\n```\n\n```\n\nhttps://i.sstatic.net/SGB93.png\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\nimport VueTelInputVuetify from 'vue-tel-input-vuetify'\nVue.use(VueTelInputVuetify)\n```\n\n```text\nplugins: [\n '~/plugins/vue-tel-input-vuetify',\n { src: '~/plugins/vue-google-charts', mode: 'client' }\n ]\n```\n\n```text\nimport { VueTelInputVuetify } from 'vue-tel-input-vuetify'\n\nexport default {\n components: {\n VueTelInputVuetify,\n },\n...\n```\n\n```html\n<VueTelInputVuetify\n ref=\"phoneInput\"\n v-model=\"phoneNumber\"\n hint=\"Enter your phone number...\"\n :rules=\"phoneNumberRules\"\n placeholder=\"\"\n label=\"Phone\"\n :required=\"true\"\n :validate-on-blur=\"true\"\n :input-options=\"{showDialCode: true, tabIndex: 0}\"\n :valid-characters-only=\"true\"\n mode=\"international\"\n/>\n```\n\n```js\nimport Vue from 'vue';\nimport vuetify from \"vuetify\";\nimport VueTelInputVuetify from 'vue-tel-input-vuetify/lib';\n\nVue.use(VueTelInputVuetify, {\n vuetify,\n});\n```\n\n```js\nplugins: ['@/plugins/phone-input'],\n```\n\n```html\n<template>\n <vue-tel-input-vuetify v-model=\"phone\"></vue-tel-input-vuetify>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n phone: ''\n }\n },\n}\n</script>\n```\n\n```js\nbuild: {\n transpile: [\n 'vue-tel-input-vuetify',\n // 'vuetify' // this one may also be needed, try with and without\n ],\n}\n```\n\n```text\n2.15.7\n```\n\n```text\n@nuxtjs/vuetify\n```\n\n```text\n1.12.1\n```\n\n```text\nvuetify\n```\n\n```text\n2.5.7\n```\n\n```text\nvue-tel-input-vuetify\n```\n\n```text\n1.3.0\n```\n\n```text\nphone-input\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- Can you show us some code please? Hard to debug with just this.\n- What's around the `` component?\n- I wrrapped it around `` tag but, still the same error\n- And what about `{ '~/plugins/vue-tel-input-vuetify', mode: 'client' }`?\n- Yes, I have tried that too, it didn't work `{ src: '~/plugins/vue-tel-input-vuetify', mode: 'client' }`\n- @KoikiDamilare updated with a more in-depth solution, no `transpile` needed.\n- Above works for me as long as plugin set to client only... plugins: [{ src: '@/plugins/phone-input', mode: 'client' }],\n- just curious, why that does not work using camel case ? VueTelInputVuetify\n- @NelsonLaRocca should be. Check in your vue devtools how this is interpreted. Also, how do you write it exactly? Check the style guide for it: vuejs.org/v2/style-guide/…","metadata":{"transformedAt":"2026-08-18T18:33:07.870Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":177,"estimatedTokens":858}}478{"id":"stack-70237844","source":"stackoverflow","questionId":70237844,"title":"How to create a build for multiple environments in Nuxt?","tags":["javascript","vue.js","nuxt.js","dotenv"],"text":"Title: How to create a build for multiple environments in Nuxt?\nTags: javascript, vue.js, nuxt.js, dotenv\nSource: Stack Overflow\n\nQuestion:\nI am building a Nuxt application where I will have two environments **staging and production**, the local should also be considered as staging, now I need to create some commands and generate builds for production and staging, which will be deployed on two separate servers.\n\nI have two questions\n\n- The command\n\n```\nnpm run generate\n```\n\nalways generate a production build, I checked it using\n\n```\nconsole.log(process.env.NODE_ENV)\n```\n\nHow can I generate a new build where the env should be something like staging?\n\n- I want to create some `.env` files for holding some env related variables, but I am confused about how can I create multiple env files for multiple envs (staging and production).\n\nI understand my question is a bit of research orientation, I spent days researching on the internet, but either the blogs are unrelated or confusing. I never really got what I was looking for, can someone point me into the right direction?\n\n========================================\n\nTop Answer:\nuse `nuxt --dotenv` and pass the path to your env file like .env.production\nExample package.json:\n\n```\n{\n \"scripts\":{\n \"prod\":\"NODE_ENV=production && nuxt --dotenv .env.production\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\nnpm run generate\n```\n\n```js\nconsole.log(process.env.NODE_ENV)\n```\n\n```text\n.env\n```\n\n```text\nNODE_ENV=\"staging\" npm run generate\n```\n\n```text\nENV\n```\n\n```text\n{\n \"scripts\":{\n \"prod\":\"NODE_ENV=production && nuxt --dotenv .env.production\"\n }\n}\n```\n\n```text\nnuxt --dotenv\n```\n\n========================================\n\nComments:\n- `NODE_env` needs to be defined on the staging platform, same goes for the env files. Meaning that if you want some variable locally, set it in `.env`, if you want a specific variable for staging/production on Heroku, AWS or alike, set the env variable there (not in an `.env` but on some dashboard/settings tab).\n- If I'm not mistaken, `generate` uses the default `production` if nothing is passed. If you give it a specific value, either in `.env` or by prefixing `npm run generate`, it should be good!\n- @kissu I generated a build by defining NODE_ENV=staging in .env nothing changed still shows production when i create a build\n- It's because the build will overwrite the env variable at build time.","metadata":{"transformedAt":"2026-08-18T18:33:07.870Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":83,"estimatedTokens":605}}479{"id":"stack-59478989","source":"stackoverflow","questionId":59478989,"title":"vue + nuxt.js - How to read POST request parameters received from an external request","tags":["javascript","node.js","vue.js","post","nuxt.js"],"text":"Title: vue + nuxt.js - How to read POST request parameters received from an external request\nTags: javascript, node.js, vue.js, post, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a an external form which submits a post request to my nuxt app. I am struggling currently to find out how I can access these POST request parameters in my nuxt page?\n\nI found so far the \"asyncData\" method, but when I try to access the submitted parameter through the \"params\" object it is always \"undefined\". What do I wrong here?\n\n- \"asyncData\" nuxt reference\n\nexample code in my nuxt page, assuming \"email\" is the request parameter submitted from outside\n\n```\nexport default {\n asyncData({ params }) {\n console.log('asyncData called...' + params.email);\n return {email: params.email};\n},\n```\n\nexternal html form\n\n```\n\n \n \n \n \n\n```\n\n========================================\n\nTop Answer:\nNuxt.js cannot handle such things by itself.\nhttps://nuxtjs.org/api/configuration-servermiddleware \n\nYou should implement your own middleware for such cases.\n\nAnd `asyncData` has nothing to do with handling inbound POST data.\n\n========================================\n\nCode:\n```text\nexport default {\n asyncData({ params }) {\n console.log('asyncData called...' + params.email);\n return {email: params.email};\n},\n```\n\n```text\n<body>\n <form action=\"https://...\" target=\"_blank\" method=\"post\">\n <input name=\"email\" class=\"input\" type=\"text\" placeholder=\"Email\" maxlength=\"255\"></input>\n <input name=\"submit\" class=\"btn\" type=\"submit\" value=\"Ok\"></input>\n </form>\n</bod>\n```\n\n```text\n<script>\nexport default {\n asyncData({ req, res }) {\n if (process.server) {\n const qs = require('querystring');\n var body = '';\n var temp = '';\n while(temp = req.read()) {\n body += temp;\n } \n var post = qs.parse(body);\n return {data: post};\n }\n },\n data() {\n return {\n data: '',\n }\n },\n mounted() {\n console.log(this.data['email']);\n },\n</script>\n```\n\n```text\nasyncData\n```\n\n========================================\n\nComments:\n- `asyncData({req})` have you tried that way?\n- yes but it was a little bit difficult to access the request body and its encoded parameters, see the answer below\n- This is not fully correct, see the asyncData() description which allows you to pass request and response object into the method call link","metadata":{"transformedAt":"2026-08-18T18:33:07.870Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":98,"estimatedTokens":600}}480{"id":"stack-65784983","source":"stackoverflow","questionId":65784983,"title":"Add .env Secrets to Nuxt App Deploying on Firebase Hosting with Github Actions","tags":["firebase","vue.js","nuxt.js","github-actions","firebase-hosting"],"text":"Title: Add .env Secrets to Nuxt App Deploying on Firebase Hosting with Github Actions\nTags: firebase, vue.js, nuxt.js, github-actions, firebase-hosting\nSource: Stack Overflow\n\nQuestion:\nI'm trying to deploy a Nuxt app to firebase hosting using github actions...\n\nThe deploy worked fine until I added my firebase config to .env - it runs fine on localhost but when deployed the api key and other config doesn't seem to be registering.\n\n.env\n\n```\nFIREBASE_APIKEY=mykey\nFIREBASE_AUTHDOMAIN=mydomain\nFIREBASE_DATABASEURL=mydburl\nFIREBASE_PROJECTID=projectid\nFIREBASE_STORAGEBUCKET=bucket\nFIREBASE_MESSAGINGSENDERID=senderid\nFIREBASE_APPID=appid\nFIREBASE_MEASUREMENTID=measurementid\n```\n\nnuxt.config.js\n\n```\n// Nuxt-Fire Module Options\n firebase: {\n config: {\n apiKey: process.env.FIREBASE_APIKEY,\n authDomain: process.env.FIREBASE_AUTHDOMAIN,\n databaseURL: process.env.FIREBASE_DATABASEURL,\n projectId: process.env.FIREBASE_PROJECTID,\n storageBucket: process.env.FIREBASE_STORAGEBUCKET,\n messagingSenderId: process.env.FIREBASE_MESSAGINGSENDERID,\n appId: process.env.FIREBASE_APPID,\n measurementId: process.env.FIREBASE_MEASUREMENTID\n },\n onFirebaseHosting: true,\n services: {\n auth: {\n persistence: 'local', // default\n initialize: {\n // onAuthStateChangedMutation: 'ON_AUTH_STATE_CHANGED_MUTATION',\n onAuthStateChangedAction: 'onAuthStateChanged'\n },\n ssr: true\n },\n firestore: true,\n storage: true,\n performance: true\n // analytics: true,\n }\n },\n```\n\ndeploy.yml\n\n```\nname: Firebase Continuous Deployment\n\non:\n push:\n branches: [master]\n\njobs:\n firebase-deploy:\n runs-on: ubuntu-latest\n\n steps:\n - uses: actions/checkout@master\n - uses: actions/setup-node@master\n with:\n node-version: '12'\n - run: yarn install\n env:\n FIREBASE_APIKEY: ${{ secrets.FIREBASE_APIKEY }}\n FIREBASE_AUTHDOMAIN: ${{ secrets.FIREBASE_AUTHDOMAIN }}\n FIREBASE_DATABASEURL: ${{ secrets.FIREBASE_DATABASEURL }}\n FIREBASE_PROJECTID: ${{ secrets.FIREBASE_PROJECTID }}\n FIREBASE_STORAGEBUCKET: ${{ secrets.FIREBASE_STORAGEBUCKET }}\n FIREBASE_MESSAGINGSENDERID: ${{ secrets.FIREBASE_MESSAGINGSENDERID }}\n FIREBASE_APPID: ${{ secrets.FIREBASE_APPID }}\n FIREBASE_MEASUREMENTID: ${{ secrets.FIREBASE_MEASUREMENTID }}\n - run: yarn generate\n - uses: w9jds/firebase-action@master\n with:\n args: deploy --only hosting\n env:\n FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}\n```\n\nhttps://i.sstatic.net/cOUSE.png\n\n========================================\n\nTop Answer:\nI add the same issue, it is the name of your env variable.\n\nIf you wannt Nuxt to inject your env variable, they must start with `NUXT_ENV_` (`NUXT_ENV_FIREBASE_APIKEY=mykey` for instance) in your .env file.\n\nSee : Automatic injection of environment variables from Nuxt documentation form more details\n\nAnd then in your code you use the variable like `process.env.NUXT_ENV_FIREBASE_APIKEY`\n\n========================================\n\nCode:\n```text\nFIREBASE_APIKEY=mykey\nFIREBASE_AUTHDOMAIN=mydomain\nFIREBASE_DATABASEURL=mydburl\nFIREBASE_PROJECTID=projectid\nFIREBASE_STORAGEBUCKET=bucket\nFIREBASE_MESSAGINGSENDERID=senderid\nFIREBASE_APPID=appid\nFIREBASE_MEASUREMENTID=measurementid\n```\n\n```text\n// Nuxt-Fire Module Options\n firebase: {\n config: {\n apiKey: process.env.FIREBASE_APIKEY,\n authDomain: process.env.FIREBASE_AUTHDOMAIN,\n databaseURL: process.env.FIREBASE_DATABASEURL,\n projectId: process.env.FIREBASE_PROJECTID,\n storageBucket: process.env.FIREBASE_STORAGEBUCKET,\n messagingSenderId: process.env.FIREBASE_MESSAGINGSENDERID,\n appId: process.env.FIREBASE_APPID,\n measurementId: process.env.FIREBASE_MEASUREMENTID\n },\n onFirebaseHosting: true,\n services: {\n auth: {\n persistence: 'local', // default\n initialize: {\n // onAuthStateChangedMutation: 'ON_AUTH_STATE_CHANGED_MUTATION',\n onAuthStateChangedAction: 'onAuthStateChanged'\n },\n ssr: true\n },\n firestore: true,\n storage: true,\n performance: true\n // analytics: true,\n }\n },\n```\n\n```text\nname: Firebase Continuous Deployment\n\non:\n push:\n branches: [master]\n\njobs:\n firebase-deploy:\n runs-on: ubuntu-latest\n\n steps:\n - uses: actions/checkout@master\n - uses: actions/setup-node@master\n with:\n node-version: '12'\n - run: yarn install\n env:\n FIREBASE_APIKEY: ${{ secrets.FIREBASE_APIKEY }}\n FIREBASE_AUTHDOMAIN: ${{ secrets.FIREBASE_AUTHDOMAIN }}\n FIREBASE_DATABASEURL: ${{ secrets.FIREBASE_DATABASEURL }}\n FIREBASE_PROJECTID: ${{ secrets.FIREBASE_PROJECTID }}\n FIREBASE_STORAGEBUCKET: ${{ secrets.FIREBASE_STORAGEBUCKET }}\n FIREBASE_MESSAGINGSENDERID: ${{ secrets.FIREBASE_MESSAGINGSENDERID }}\n FIREBASE_APPID: ${{ secrets.FIREBASE_APPID }}\n FIREBASE_MEASUREMENTID: ${{ secrets.FIREBASE_MEASUREMENTID }}\n - run: yarn generate\n - uses: w9jds/firebase-action@master\n with:\n args: deploy --only hosting\n env:\n FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}\n```\n\n```text\nname: Firebase Continuous Deployment\n\non:\n push:\n branches: [master]\n\njobs:\n firebase-deploy:\n runs-on: ubuntu-latest\n\n steps:\n - uses: actions/checkout@master\n - uses: actions/setup-node@master\n with:\n node-version: '12'\n - run: yarn install\n - run: yarn generate\n env:\n FIREBASE_APIKEY: ${{ secrets.FIREBASE_APIKEY }}\n FIREBASE_AUTHDOMAIN: ${{ secrets.FIREBASE_AUTHDOMAIN }}\n FIREBASE_DATABASEURL: ${{ secrets.FIREBASE_DATABASEURL }}\n FIREBASE_PROJECTID: ${{ secrets.FIREBASE_PROJECTID }}\n FIREBASE_STORAGEBUCKET: ${{ secrets.FIREBASE_STORAGEBUCKET }}\n FIREBASE_MESSAGINGSENDERID: ${{ secrets.FIREBASE_MESSAGINGSENDERID }}\n FIREBASE_APPID: ${{ secrets.FIREBASE_APPID }}\n FIREBASE_MEASUREMENTID: ${{ secrets.FIREBASE_MEASUREMENTID }}\n - uses: w9jds/firebase-action@master\n with:\n args: deploy --only hosting\n env:\n FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}\n```\n\n```text\nNUXT_ENV_\n```\n\n```text\nNUXT_ENV_FIREBASE_APIKEY=mykey\n```\n\n```text\nprocess.env.NUXT_ENV_FIREBASE_APIKEY\n```\n\n========================================\n\nComments:\n- Looks like you're setting your `env` variables on the `yarn install` step. Shouldn't they be on the `yarn generate` step below?\n- Yep that was it - thanks for saving my morning @Phil ;)\n- Pretty much a lucky guess on my part, I'm hopeless when it comes to Nuxt. Glad you got it working 🙂\n- Hmm looks correct although I was generating a static site so I didn’t need the nuxt_env prefix just needed to be before generate\n- I wish I saw this answer 2 hours ago","metadata":{"transformedAt":"2026-08-18T18:33:07.870Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":237,"estimatedTokens":1794}}481{"id":"stack-67808532","source":"stackoverflow","questionId":67808532,"title":"Vuetify + Nuxt + locally add md icons","tags":["vue.js","nuxt.js","vuetify.js"],"text":"Title: Vuetify + Nuxt + locally add md icons\nTags: vue.js, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nHow would one import the 'md' icons locally, similar to how they import the mdi ones in this post:\nHow to import the mdi icons module inside nuxt.config.js in Nuxt\n\nEither the standard package or the custom repo\nhttps://github.com/jossef/material-design-icons-iconfont\nI'm using the nuxt-vuetify plugin.\nAll my attempts have failed, e.g adding this:\n\nnuxt.config.js\n\n```\ncss: ['~/assets/main.css', './node_modules/material-design-icons-iconfont/dist/material-design-icons.css'],\n\nvuetify: {\n customVariables: ['~/assets/variables.scss'],\n treeShake: true,\n defaultAssets: {\n font: false,\n icons: 'md',// this just fetches it from the repo\n// icons: {iconfont: 'md'} // this doesn't seem to work for me\n enter code here\n },\n theme: {\n dark: false,\n themes: {\n light: {\n primary: '#fec655',\n },\n }\n }\n },\n```\n\n========================================\n\nCode:\n```text\ncss: ['~/assets/main.css', './node_modules/material-design-icons-iconfont/dist/material-design-icons.css'],\n\nvuetify: {\n customVariables: ['~/assets/variables.scss'],\n treeShake: true,\n defaultAssets: {\n font: false,\n icons: 'md',// this just fetches it from the repo\n// icons: {iconfont: 'md'} // this doesn't seem to work for me\n enter code here\n },\n theme: {\n dark: false,\n themes: {\n light: {\n primary: '#fec655',\n },\n }\n }\n },\n```\n\n========================================\n\nComments:\n- Vuetify has material icons integrated. I am also developing in vuejs, nuxtjs. I just installed font using this command `npm install @mdi/font -D` and i can use any material icon `mdi-iconname` inside `v-icon`. check this vuetifyjs.com/en/features/icon-fonts\n- Yes, but this is about the 'md' library and not the mdi one :). Adding md vs. mdi locally ended up just being about switching out the global css import.","metadata":{"transformedAt":"2026-08-18T18:33:07.870Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":69,"estimatedTokens":486}}482{"id":"stack-79807587","source":"stackoverflow","questionId":79807587,"title":"Is it possible to customize the speed of the Nuxt UI Marquee component?","tags":["nuxt.js","tailwind-css","nuxtui"],"text":"Title: Is it possible to customize the speed of the Nuxt UI Marquee component?\nTags: nuxt.js, tailwind-css, nuxtui\nSource: Stack Overflow\n\nQuestion:\nGiven the Nuxt UI marquee component\n\n```\n\n \n \n```\n\nis it possible to control its speed? I wasn't able to find a prop for that. Maybe this can be achieved with a Tailwind class inside the `ui` prop?\n\n========================================\n\nCode:\n```html\n<UMarquee>\n <!-- ... -->\n </UMarquee>\n```\n\n```text\nui\n```\n\n```html\n<UMarquee\n :ui=\"{\n root: '[--duration:40s]'\n }\"\n>\n ...\n</UMarquee>\n```\n\n```text\n--duration\n```\n\n========================================\n\nComments:\n- By reviewing the default class names in the Theme section, you can find out which other variables the component uses.","metadata":{"transformedAt":"2026-08-18T18:33:07.870Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":46,"estimatedTokens":187}}483{"id":"stack-73046743","source":"stackoverflow","questionId":73046743,"title":"ReferenceError: computed is not defined on Vitest test suite","tags":["vue.js","nuxt.js","vitest"],"text":"Title: ReferenceError: computed is not defined on Vitest test suite\nTags: vue.js, nuxt.js, vitest\nSource: Stack Overflow\n\nQuestion:\n### Description\n\nI'm migrating test suites from Jest to Vitest.\nBut i've a problem when i run test suites, an error occurs when a component has a computed property.\n\nThe common error is :\n\n```\nReferenceError: computed is not defined\n\n - /components/Ui/Avatar.vue:13:30\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:157:22\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7084:29\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7039:11\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5401:13\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5376:17\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4978:21\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5515:21\n - /node_modules/@vue/reactivity/dist/reactivity.cjs.js:189:25\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5622:56\n```\n\n### Versions\n\n- \"vitest\": \"^0.18.1\"\n\n- \"jsdom\": \"^20.0.0\"\n\n- \"@vue/test-utils\": \"^2.0.2\"\n\n### Exemple\n\nHere is my component code :\n\n```\n\n \n\nconst props = withDefaults(defineProps(), {\n src: '',\n big: false,\n errorImage: '/no-avatar.png',\n})\n\nconst onErrorLoadImage = computed(() => `this.src='${props.errorImage}';this.onerror='';`)\n\n```\n\nAnd my test\n\n```\nimport { describe, it, expect } from 'vitest'\nimport { mount } from '@vue/test-utils'\nimport UiAvatar from './Avatar.vue'\n\nconst componentName = 'img'\nconst src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII='\nconst big = true\nconst errorImage = '/no-avatar.png'\n\ndescribe('UiAvatar', () => {\n it('should be render the component', () => {\n const wrapper = mount(UiAvatar, {\n propsData: {\n src,\n big,\n errorImage\n }\n })\n expect(wrapper.element.tagName).toBe(componentName)\n })\n})\n```\n\nThanks :)\n\n========================================\n\nCode:\n```text\nReferenceError: computed is not defined\n\n - /components/Ui/Avatar.vue:13:30\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:157:22\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7084:29\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7039:11\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5401:13\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5376:17\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4978:21\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5515:21\n - /node_modules/@vue/reactivity/dist/reactivity.cjs.js:189:25\n - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5622:56\n```\n\n```js\n<template>\n <image\n :src=\"src\"\n :onerror=\"onErrorLoadImage\"\n :class=\"['avatar', { big }]\"\n />\n</template>\n\n<script setup lang=\"ts\">\nconst props = withDefaults(defineProps<{\n src?: string\n big?: boolean\n errorImage?: string\n}>(), {\n src: '',\n big: false,\n errorImage: '/no-avatar.png',\n})\n\nconst onErrorLoadImage = computed(() => `this.src='${props.errorImage}';this.onerror='';`)\n</script>\n```\n\n```js\nimport { describe, it, expect } from 'vitest'\nimport { mount } from '@vue/test-utils'\nimport UiAvatar from './Avatar.vue'\n\nconst componentName = 'img'\nconst src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII='\nconst big = true\nconst errorImage = '/no-avatar.png'\n\ndescribe('UiAvatar', () => {\n it('should be render the component', () => {\n const wrapper = mount(UiAvatar, {\n propsData: {\n src,\n big,\n errorImage\n }\n })\n expect(wrapper.element.tagName).toBe(componentName)\n })\n})\n```\n\n========================================\n\nComments:\n- same issue, have you solved it yet?\n- @weiL. not solved, but my temporary fix is to import required modules on the component. Like for exemple when i have the error \"computed is not defined\" when i run test suites, i've added the module in the component file :)","metadata":{"transformedAt":"2026-08-18T18:33:07.870Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":152,"estimatedTokens":1003}}484{"id":"stack-54317639","source":"stackoverflow","questionId":54317639,"title":"Is there a created() for vuex actions to auto dispatch","tags":["javascript","vue.js","vuex","nuxt.js"],"text":"Title: Is there a created() for vuex actions to auto dispatch\nTags: javascript, vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have an action within vuex that I would like to auto dispatch within vuex itself rather than a component.\n\nI have created a notification bar that changes through different notifications which is on multiple pages. Rather than the notifications start from the beginning when I switch page I have created a store to set which notification to show.\n\nI would like to dispatch the rotate function in the vuex store from within vuex rather than from within a component\n\n*Please note: I'm using Nuxt*\n\n**VUEX State: store/notifications.js**\n\n\r\n\r\n\n```\nexport const state = () => ({\r\n section: 0,\r\n notifications: [\r\n 'notification 1',\r\n 'notification 2',\r\n 'notification 3'\r\n ]\r\n})\r\n\r\nexport const mutations = {\r\n INC_SECTION(state) {\r\n state.section ++\r\n },\r\n RESET_SECTION(state) {\r\n state.section = 0\r\n }\r\n}\r\n\r\nexport const actions = {\r\n rotate({commit, dispatch, state}) {\r\n setTimeout(() => {\r\n \r\n let total = state.notifications.length -1\r\n \r\n if (state.section === total) {\r\n commit('RESET_SECTION')\r\n }\r\n else {\r\n commit('INC_SECTION')\r\n }\r\n dispatch('rotate')\r\n \r\n }, 3500)\r\n }\r\n}\r\n\r\nexport default {\r\n state,\r\n mutations,\r\n actions\r\n}\n```\n\n\r\n\r\n\r\n\n**VUE JS Component:**\n\n\r\n\r\n\n```\n\r\n \r\n \r\n {{notification}}\n\n\r\n \r\n \r\n\r\n\r\n\r\nexport default {\r\n data() {\r\n return { notifications: [] }\r\n },\r\n computed: {\r\n setData() {\r\n this.notifications = this.$store.state.notifications.notifications\r\n }\r\n },\r\n created() {\r\n this.setData\r\n }\r\n}\r\n\r\n\n```\n\n========================================\n\nCode:\n```js\nexport const state = () => ({\n section: 0,\n notifications: [\n 'notification 1',\n 'notification 2',\n 'notification 3'\n ]\n})\n\nexport const mutations = {\n INC_SECTION(state) {\n state.section ++\n },\n RESET_SECTION(state) {\n state.section = 0\n }\n}\n\nexport const actions = {\n rotate({commit, dispatch, state}) {\n setTimeout(() => {\n \n let total = state.notifications.length -1\n \n if (state.section === total) {\n commit('RESET_SECTION')\n }\n else {\n commit('INC_SECTION')\n }\n dispatch('rotate')\n \n }, 3500)\n }\n}\n\nexport default {\n state,\n mutations,\n actions\n}\n```\n\n```html\n<template>\n <section class=\"notifications\">\n <template v-for=\"(notification, i) in notifications\" >\n <p v-if=\"$store.state.notifications.section === i\" :key=\"i\">{{notification}}</p>\n </template>\n </section>\n</template>\n\n<script>\nexport default {\n data() {\n return { notifications: [] }\n },\n computed: {\n setData() {\n this.notifications = this.$store.state.notifications.notifications\n }\n },\n created() {\n this.setData\n }\n}\n\n</script>\n```\n\n```text\nexport const state = () => ({\n section: 0,\n notifications: [\"notification 1\", \"notification 2\", \"notification 3\"]\n});\n\nexport const mutations = {\n INC_SECTION(state) {\n state.section++;\n },\n RESET_SECTION(state) {\n state.section = 0;\n }\n};\n\nexport const actions = {\n rotate({ commit, dispatch, state }) {\n setTimeout(() => {\n let total = state.notifications.length - 1;\n if (state.section === total) {\n commit(\"RESET_SECTION\");\n } else {\n commit(\"INC_SECTION\");\n }\n dispatch(\"rotate\");\n }, 3500);\n }\n};\n\nexport const getters = {\n notifications(state) {\n return state.notifications;\n },\n section(state) {\n return state.section;\n }\n};\n\nexport default {\n state,\n mutations,\n actions,\n getters\n};\n```\n\n```text\n<template>\n <section class=\"notifications\">\n <template v-for=\"(notification, i) in notifications\">\n <p v-if=\"section === i\" :key=\"i\">{{ notification }}</p>\n </template>\n </section>\n</template>\n\n<script>\nimport { mapGetters } from \"vuex\";\nexport default {\n data() {\n return {};\n },\n computed: {\n ...mapGetters([\"notifications\", \"section\"])\n }\n};\n</script>\n```\n\n```text\nexport default function({ store }) {\n store.dispatch(\"rotate\");\n}\n```\n\n```text\nmapGetters\n```\n\n========================================\n\nComments:\n- Thanks for taking the time out to help. This only works when I change route, and it triggers it each time I change route so I have the same issue as before. Is there any way to trigger the middleware on initial site load only?\n- To solve this I have created a plugin instead of the middleware called onload.js: `export default function ({ app, store }) { app.router.onReady(() => store.dispatch(\"rotate\")) }` and updated nuxt.config.js `plugins: [ {src: '~/plugins/onLoad.js', ssr: false} ]`","metadata":{"transformedAt":"2026-08-18T18:33:07.871Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":257,"estimatedTokens":1185}}485{"id":"stack-57316551","source":"stackoverflow","questionId":57316551,"title":"Best method to integrate Nuxt frontend with Flask backend","tags":["javascript","flask","integration","nuxt.js","flask-security"],"text":"Title: Best method to integrate Nuxt frontend with Flask backend\nTags: javascript, flask, integration, nuxt.js, flask-security\nSource: Stack Overflow\n\nQuestion:\nI am trying to integrate a front-end dashboard built with nuxt with an API back-end built with Flask. Both the front and the back must run on the same local server on the client's closed network. The client wishes to use Flask-Security in order to authenticate users, but this is where the problems start. \nOriginally, the client wanted to serve static pages in the flask-security templates folder. \n\nHowever, because the pages themselves need data from the API in order to load (using nuxt's asyncData), I ran into problems when trying to deploy the front-end files using \"npm run generate\"/\"npm run build\" and the only way I could get the front to work together with the back was by deploying the front-end in server-side rendering and running it locally (npm run start) on a different localhost port than the one the API is running on. \nSo far its been working, but the problem is that now the client wishes to add login to the system, using Flask-Security, but I am running into a brick wall trying to do that...\n\nSo, I have a few questions - \n\n1 - What do you think about would be the ideal way of going about this? can it be done? \n\n2 - Could you suggest a different method/setting to integrate the front and the back? What would be the best practices in this situation ? Should the login be done using Flask or using something else? at the front-end or at the back? \n\n3 - Would you recommend a different login method? (just as a note, the front-end hasn't been run with a vue store so far, and I think that is required for authentication through nuxt...)\n\n========================================\n\nComments:\n- Just to make sure - I am using nuxt served in SSR, and so I'm not sure I understood exactly, how would you use Flask-Security for the login and then transfer the user to the nuxt frontend ?\n- Presumably your Vue components are using axios or some other package to make API calls to your flask backend. Flask-Security has support JSON request/response for a while. So your Vue Login component would make a POST /login with body {\"email\": \"xx\", \"password\": \"password\"} with Content-Type = \"application/json\". You will get a 200 response (no redirects).\n- Fantastic. Thanks a lot!","metadata":{"transformedAt":"2026-08-18T18:33:07.871Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":25,"estimatedTokens":589}}486{"id":"stack-57368613","source":"stackoverflow","questionId":57368613,"title":"Odd behavior with axios, nuxt, and docker","tags":["vue.js","docker-compose","axios","nuxt.js"],"text":"Title: Odd behavior with axios, nuxt, and docker\nTags: vue.js, docker-compose, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am setting up a full-stack application with nuxt js running my client-side code, express js running my api, and mysql as my database. To run all of these processes I have been using docker, more specifically docker-compose. After much configuration, I have gotten all three images to run together. There is one problem though, I cannot figure out how to make calls to my api with nuxt/axios.\n\nI have tried many different tactics. My express api is available to the \"outside-world\" at `http://localhost:8080`, so I set up my axios `baseURL` to reflect that. I ran some test axios gets in some nuxt js middleware, and kept getting a connection refusal error. I finally figured out that I could use docker-compose networks to connect my frontend and backend, so I remapped my axios `baseURL` to `http://api:8080` (api is the name of my docker-compose image), and in the axios request in the nuxt js middleware, it worked like a charm. Later, I was writing some code, and I wanted to send an axios request in a vue method. Even though the axios requests in the middleware were working with this `baseURL`, this new axios request in the method gave the error\n\n commons.app.js:434 OPTIONS http://api:8080/api/v1/get/colors net::ERR_NAME_NOT_RESOLVED\n\nI tried changing my axios baseURL back to localhost, and now the axios request in the methods works, but the axios request in the middleware doesn't work.\n\ndocker-compose.yml\n\n```\nversion: \"3.3\"\n\nservices:\n mysql:\n container_name: mysql\n image: mysql:5.7\n environment:\n MYSQL_USER: ${MYSQL_DEV_USER}\n MYSQL_PASSWORD: ${MYSQL_DEV_PASSWORD}\n MYSQL_DATABASE: ${MYSQL_DEV_DATABASE}\n MYSQL_ROOT_PASSWORD: ${MYSQL_DEV_ROOT_PASSWORD}\n ports:\n - 3306:3306\n restart: always\n volumes:\n - mysql_data:/var/lib/mysql\n - ./database/create_db.sql:/docker-entrypoint-initdb.d/create_db.sql\n - ./database/insert_db.sql:/docker-entrypoint-initdb.d/insert_db.sql\n\n api:\n container_name: api\n depends_on:\n - mysql\n links:\n - mysql\n build:\n context: ./backend\n dockerfile: Dockerfile-dev\n environment:\n NODE_ENV: development\n MYSQL_USER: ${MYSQL_DEV_USER}\n MYSQL_PASSWORD: ${MYSQL_DEV_PASSWORD}\n MYSQL_DATABASE: ${MYSQL_DEV_DATABASE}\n MYSQL_HOST_IP: mysql\n PORT: ${API_PORT}\n HOST: ${API_HOST}\n expose:\n - 8080\n ports:\n - 8080:8080\n volumes:\n - ./backend:/app\n command: npm run dev\n\n frontend:\n container_name: frontend\n depends_on:\n - api\n links:\n - api\n build:\n context: ./frontend\n dockerfile: Dockerfile-dev\n environment:\n NUXT_PORT: 3000\n NUXT_HOST: 0.0.0.0\n NODE_ENV: development\n GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID}\n API_HOST: api\n API_PORT: ${API_PORT}\n API_PREFIX: ${API_PREFIX}\n expose:\n - 3000\n ports:\n - 3000:3000\n volumes:\n - ./frontend:/app\n command: npm run dev\n\nvolumes:\n mysql_data:\n```\n\nnuxt.config.js\n\n```\naxios: {\n baseURL: 'http://api:8080/api/v1'\n },\n```\n\nnuxt middleware\n\n```\nexport default async function({ app, redirect, error }) {\n try {\n const response = await app.$axios.$get('/auth/login')\n if (!response.success) {\n throw new Error(response.message)\n }\n redirect('/admin')\n } catch (err) {\n console.log(err)\n await app.$auth.logout()\n error({ message: err.message, statusCode: 500 })\n }\n}\n```\n\nnuxt method\n\n```\nmethods: {\n async test() {\n const colors = await this.$nuxt.$axios.$get('/get/colors')\n console.log(colors)\n }\n}\n```\n\nThank you all so much!\n\nP.S. This is my first stack overflow question!\n\n========================================\n\nCode:\n```text\nversion: \"3.3\"\n\nservices:\n mysql:\n container_name: mysql\n image: mysql:5.7\n environment:\n MYSQL_USER: ${MYSQL_DEV_USER}\n MYSQL_PASSWORD: ${MYSQL_DEV_PASSWORD}\n MYSQL_DATABASE: ${MYSQL_DEV_DATABASE}\n MYSQL_ROOT_PASSWORD: ${MYSQL_DEV_ROOT_PASSWORD}\n ports:\n - 3306:3306\n restart: always\n volumes:\n - mysql_data:/var/lib/mysql\n - ./database/create_db.sql:/docker-entrypoint-initdb.d/create_db.sql\n - ./database/insert_db.sql:/docker-entrypoint-initdb.d/insert_db.sql\n\n api:\n container_name: api\n depends_on:\n - mysql\n links:\n - mysql\n build:\n context: ./backend\n dockerfile: Dockerfile-dev\n environment:\n NODE_ENV: development\n MYSQL_USER: ${MYSQL_DEV_USER}\n MYSQL_PASSWORD: ${MYSQL_DEV_PASSWORD}\n MYSQL_DATABASE: ${MYSQL_DEV_DATABASE}\n MYSQL_HOST_IP: mysql\n PORT: ${API_PORT}\n HOST: ${API_HOST}\n expose:\n - 8080\n ports:\n - 8080:8080\n volumes:\n - ./backend:/app\n command: npm run dev\n\n frontend:\n container_name: frontend\n depends_on:\n - api\n links:\n - api\n build:\n context: ./frontend\n dockerfile: Dockerfile-dev\n environment:\n NUXT_PORT: 3000\n NUXT_HOST: 0.0.0.0\n NODE_ENV: development\n GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID}\n API_HOST: api\n API_PORT: ${API_PORT}\n API_PREFIX: ${API_PREFIX}\n expose:\n - 3000\n ports:\n - 3000:3000\n volumes:\n - ./frontend:/app\n command: npm run dev\n\nvolumes:\n mysql_data:\n```\n\n```js\naxios: {\n baseURL: 'http://api:8080/api/v1'\n },\n```\n\n```js\nexport default async function({ app, redirect, error }) {\n try {\n const response = await app.$axios.$get('/auth/login')\n if (!response.success) {\n throw new Error(response.message)\n }\n redirect('/admin')\n } catch (err) {\n console.log(err)\n await app.$auth.logout()\n error({ message: err.message, statusCode: 500 })\n }\n}\n```\n\n```js\nmethods: {\n async test() {\n const colors = await this.$nuxt.$axios.$get('/get/colors')\n console.log(colors)\n }\n}\n```\n\n```text\nhttp://localhost:8080\n```\n\n```text\nbaseURL\n```\n\n```text\nbaseURL\n```\n\n```text\nhttp://api:8080\n```\n\n```text\nbaseURL\n```\n\n```js\naxios: {\n baseURL: 'http://api:8080/api/v1',\n browserBaseURL: 'http://localhost/8080/api/v1'\n},\n```\n\n========================================\n\nComments:\n- I don't know Nuxt very well so help me out a bit... how are you running these *\"test\"* requests from the middleware? In what environment are they running?\n- @Phil when I go to the route localhost:3000/verify, nuxt js loads a .vue file that automatically runs that piece of middleware. I learned what I know about the middleware from this bit of documentation nuxtjs.org/guide/routing#middleware. Also, thank you for re-formatting my question a bit! If there is anything else I can clarify please let me know.","metadata":{"transformedAt":"2026-08-18T18:33:07.871Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":270,"estimatedTokens":1617}}487{"id":"stack-58711851","source":"stackoverflow","questionId":58711851,"title":"Why in my nuxt-link doesn't reload page with same url?","tags":["vue.js","nuxt.js"],"text":"Title: Why in my nuxt-link doesn't reload page with same url?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIf I’m on a page with the URL 'http://localhost:8080/item' and I’m clicking on the same link on this page, then the page does not reload.\nI need to make that if I click on the same link, the page will reload.\n\nMy link:\n\n```\n\n```\n\nAny insight will be welcome. Thanks!\n\n========================================\n\nTop Answer:\nI recently tried to solve a similar issue and to overcome this I used `Vuex` with `:key` (ref).\n\nFirstly, in your store you need a `state property` such as:\n\n```\nexport const state = () => ({\n componentUpdates: {\n item: 0,\n //can add more as needed\n }\n})\n```\n\nIn general, you could use only one property across the app if you prefer it that way. Just remember that later on, the `key` value needs to be unique - that is in the case if you used this property for two or more components within one page, for example. In this case, you could do something like this `:key=\"$store.getters.getComponentUpdates.item+'uniqueString'\"`\n\nthen a `getter`:\n\n```\nexport const getters = {\n getComponentUpdates(state) {\n return state.updateComponent;\n }\n}\n```\n\nfinally a `mutatation`:\n\n```\nexport const mutations = {\n updateComponent(state, payload) {\n return state.componentUpdates[payload.update]++\n }\n}\n```\n\nNow we can utilise the reactive `:key` wherever needed.\nBut first in your `nuxt-link` lets add an event to trigger the mutation, note the usage of `@click.native` to trigger the click event:\n\n```\n\n```\n\nNow in the item page, for example. Let's imagine there is a component that needs to be updated. In this case we would add `:key` to it:\n\n```\n\n```\n\nThat is it. As you can see this solution utilises the benefits of `nuxt-link` but also allows us to selectively update only parts of our page that need updates (we could update the entire page this way as well if needed).\n\nIn case if you needed to trigger the logic from `mounted` or initial load in general, then you could use `computed` property and `:key` to your `div` container, right inside the `` of your page.\n\nAdd `:key` to the `div`:\n\n```\n\n \n\n```\n\nCreate `computed` property:\n\n```\ncomputed: {\n updateItemPage() {\n //run your initial instructions here as if you were doing it in mounted then return the getter\n this.initialLoadMethod()\n return this.$store.getters.getComponentUpdates.item\n }\n}\n```\n\nThe final touch, which is not crucial but can be implemented in order to reset the `state property`:\n\n```\nexport const mutations = {\n updateComponent(state, payload) {\n return state.componentUpdates[payload.update] >= 10\n ? state.componentUpdates[payload.update] = 0\n : state.componentUpdates[payload.update]++\n }\n}\n```\n\n========================================\n\nCode:\n```text\n<nuxt-link :to=\"/item\">\n```\n\n```text\n<router-view :key=\"$route.params.yourCustomParam\"/>\n```\n\n```text\n<router-link :to=\"{ params: { yourCustomParam: Data.now } }\" replace>link</router-link>\n```\n\n```text\nto\n```\n\n```text\nrouter.push()\n```\n\n```text\nexport const state = () => ({\n componentUpdates: {\n item: 0,\n //can add more as needed\n }\n})\n```\n\n```text\nexport const getters = {\n getComponentUpdates(state) {\n return state.updateComponent;\n }\n}\n```\n\n```text\nexport const mutations = {\n updateComponent(state, payload) {\n return state.componentUpdates[payload.update]++\n }\n}\n```\n\n```text\n<nuxt-link @click.native=\"$store.commit('updateComponent', { update: 'item'})\" :to=\"/item\">\n```\n\n```text\n<my-item :key=\"$store.getters.getComponentUpdates.item\" />\n```\n\n```text\n<template>\n <div :key=\"$store.getters.getComponentUpdates.item\"></div>\n</template>\n```\n\n```text\ncomputed: {\n updateItemPage() {\n //run your initial instructions here as if you were doing it in mounted then return the getter\n this.initialLoadMethod()\n return this.$store.getters.getComponentUpdates.item\n }\n}\n```\n\n```text\nexport const mutations = {\n updateComponent(state, payload) {\n return state.componentUpdates[payload.update] >= 10\n ? state.componentUpdates[payload.update] = 0\n : state.componentUpdates[payload.update]++\n }\n}\n```\n\n```text\nVuex\n```\n\n```text\n:key\n```\n\n```text\nstate property\n```\n\n```text\nkey\n```\n\n```text\n:key=\"$store.getters.getComponentUpdates.item+'uniqueString'\"\n```\n\n```text\ngetter\n```\n\n```text\nmutatation\n```\n\n```text\n:key\n```\n\n```text\nnuxt-link\n```\n\n```text\n@click.native\n```\n\n```text\n:key\n```\n\n```text\nnuxt-link\n```\n\n```text\nmounted\n```\n\n```text\ncomputed\n```\n\n```text\n:key\n```\n\n```text\ndiv\n```\n\n```text\n<template>\n```\n\n```text\n:key\n```\n\n```text\ndiv\n```\n\n```text\ncomputed\n```\n\n```text\nstate property\n```\n\n========================================\n\nComments:\n- Doesn't work for me. Perhaps you provide a codesandbox link\n- also not working for me. router.push() seems to work. I'm using NuxtJS","metadata":{"transformedAt":"2026-08-18T18:33:07.871Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":274,"estimatedTokens":1201}}488{"id":"stack-68858082","source":"stackoverflow","questionId":68858082,"title":"How to properly setup bootstrap-vue in my Nuxt app?","tags":["css","twitter-bootstrap","vue.js","nuxt.js","bootstrap-vue"],"text":"Title: How to properly setup bootstrap-vue in my Nuxt app?\nTags: css, twitter-bootstrap, vue.js, nuxt.js, bootstrap-vue\nSource: Stack Overflow\n\nQuestion:\nI am very new to `Nuxt.js` application and I am trying to create a web application using the `Nuxt.js and Vue.js`. During the creation of the project using the `Nuxt cli` I have added the `Bootstrap-vue`.\n\nI am facing some problems with `Bootstrap modal` creation hence I want to remove the `Bootstrap vue` completely and add the good old plain `Bootstrap` into my application. I tried adding as per a few of the answers found here but for some reason, it's not working as expected and my `Modal` is not being displayed properly with `drop-downs` etc. So my guess is that I have not properly removed the `Bootstrap vue` from my application and added the `Bootstrap` completely.\n\nCan someone please let me know if I have missed something here:\n\n** Removal of Bootstrap-vue ***\n\n- `npm i bootstrap-vue --save`.\n\n- Remove the `bootstrap-vue.js` file from `plugins` folder.\n\n- Remove `plugin` from `nuxt-config.js`: `plugins: [\"@/plugins/bootstrap-vue\"],`\n\n** Installing plaing old Bootstrap **\nAdded following CDN links to my `nuxt-config.js` file:\n\n```\nscript: [\n {\n src: \"https://code.jquery.com/jquery-3.6.0.min.js\"\n },\n {\n src:\n \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"\n }\n]\n```\n\n```\nlink:[\n {\n rel: \"stylesheet\",\n href:\n \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\"\n },\n {\n rel: \"stylesheet\",\n href:\n \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css\"\n }]\n```\n\nAfter doing these things when I create a simple modal using `Boostrap` and add drop-down to it, it does not display anything on the modal\n\nCan someone please confirm if I am following proper workflow or am I missing something? Any help or recommendation would be really helpful.\n\n*** **UPDATED** ***\n\nFollowing is my `nuxt-config.js` file:\n\n```\nimport colors from \"vuetify/es5/util/colors\";\n\nexport default {\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n titleTemplate: \"%s - openepcis-test-data-generator-ui\",\n title: \"EPCIS | Test Data Generator\",\n htmlAttrs: {\n lang: \"en\"\n },\n meta: [\n { charset: \"utf-8\" },\n { name: \"viewport\", content: \"width=device-width, initial-scale=1\" },\n { hid: \"description\", name: \"description\", content: \"\" },\n { name: \"format-detection\", content: \"telephone=no\" }\n ],\n script: [\n /* {\n src: \"https://code.jquery.com/jquery-3.6.0.min.js\"\n },\n {\n src:\n \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"\n }*/\n ],\n link: [\n { rel: \"icon\", type: \"image/x-icon\", href: \"/Logo.ico\" },\n {\n rel: \"stylesheet\",\n href:\n \"https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css\"\n }\n /* {\n rel: \"stylesheet\",\n href:\n \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\"\n },\n {\n rel: \"stylesheet\",\n href:\n \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css\"\n }*/\n ]\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\"@/assets/css/styles.css\"],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [\"@/plugins/bootstrap-vue\"],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n [\n \"@nuxtjs/eslint-module\",\n {\n fix: true\n }\n ],\n [\"@nuxtjs/vuetify\"],\n [\"@nuxtjs/dotenv\"]\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\"@nuxtjs/axios\"],\n\n // Axios module configuration: https://go.nuxtjs.dev/config-axios\n axios: {\n baseURL: process.env.API_URL,\n headers: {\n \"Content-Type\": \"text/plain\"\n }\n },\n\n // Vuetify module configuration: https://go.nuxtjs.dev/config-vuetify\n vuetify: {},\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {\n babel: {\n plugins: [\n [\"@babel/plugin-proposal-class-properties\", { loose: true }],\n [\"@babel/plugin-proposal-private-methods\", { loose: true }],\n [\"@babel/plugin-proposal-private-property-in-object\", { loose: true }]\n ]\n }\n },\n\n server: {\n port: 5000\n }\n};\n```\n\nI have following things in my `plugins/bootstrap-vue.js`:\n\n```\nimport Vue from 'vue'\nimport BootstrapVue from 'bootstrap-vue'\nimport 'bootstrap/dist/css/bootstrap.css'\nimport 'bootstrap-vue/dist/bootstrap-vue.css'\nVue.use(BootstrapVue)\n```\n\nApart from that following is code for modal:\n\n```\n\n \n \n \n \n \n \n \n \n Add Options\n \n \n ×\n \n \n \n \n Action\n Another action\n Something else here\n \n \n \n \n Close\n \n \n Save changes\n \n \n \n \n \n \n \n \n\nexport default {\n components: {},\n data () {\n return {}\n },\n methods: {\n hideModal () {\n this.$store.commit(\n 'hideModal'\n )\n }\n }\n}\n\n```\n\n========================================\n\nCode:\n```text\nscript: [\n {\n src: \"https://code.jquery.com/jquery-3.6.0.min.js\"\n },\n {\n src:\n \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"\n }\n]\n```\n\n```text\nlink:[\n {\n rel: \"stylesheet\",\n href:\n \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\"\n },\n {\n rel: \"stylesheet\",\n href:\n \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css\"\n }]\n```\n\n```text\nimport colors from \"vuetify/es5/util/colors\";\n\nexport default {\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n titleTemplate: \"%s - openepcis-test-data-generator-ui\",\n title: \"EPCIS | Test Data Generator\",\n htmlAttrs: {\n lang: \"en\"\n },\n meta: [\n { charset: \"utf-8\" },\n { name: \"viewport\", content: \"width=device-width, initial-scale=1\" },\n { hid: \"description\", name: \"description\", content: \"\" },\n { name: \"format-detection\", content: \"telephone=no\" }\n ],\n script: [\n /* {\n src: \"https://code.jquery.com/jquery-3.6.0.min.js\"\n },\n {\n src:\n \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"\n }*/\n ],\n link: [\n { rel: \"icon\", type: \"image/x-icon\", href: \"/Logo.ico\" },\n {\n rel: \"stylesheet\",\n href:\n \"https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css\"\n }\n /* {\n rel: \"stylesheet\",\n href:\n \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\"\n },\n {\n rel: \"stylesheet\",\n href:\n \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css\"\n }*/\n ]\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\"@/assets/css/styles.css\"],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [\"@/plugins/bootstrap-vue\"],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n [\n \"@nuxtjs/eslint-module\",\n {\n fix: true\n }\n ],\n [\"@nuxtjs/vuetify\"],\n [\"@nuxtjs/dotenv\"]\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\"@nuxtjs/axios\"],\n\n // Axios module configuration: https://go.nuxtjs.dev/config-axios\n axios: {\n baseURL: process.env.API_URL,\n headers: {\n \"Content-Type\": \"text/plain\"\n }\n },\n\n // Vuetify module configuration: https://go.nuxtjs.dev/config-vuetify\n vuetify: {},\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {\n babel: {\n plugins: [\n [\"@babel/plugin-proposal-class-properties\", { loose: true }],\n [\"@babel/plugin-proposal-private-methods\", { loose: true }],\n [\"@babel/plugin-proposal-private-property-in-object\", { loose: true }]\n ]\n }\n },\n\n server: {\n port: 5000\n }\n};\n```\n\n```text\nimport Vue from 'vue'\nimport BootstrapVue from 'bootstrap-vue'\nimport 'bootstrap/dist/css/bootstrap.css'\nimport 'bootstrap-vue/dist/bootstrap-vue.css'\nVue.use(BootstrapVue)\n```\n\n```text\n<template>\n <div v-if=\"$store.state.showModal\">\n <transition name=\"modal\">\n <div class=\"modal-mask\">\n <div class=\"modal-wrapper\">\n <div class=\"modal-dialog\" role=\"document\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <h5 class=\"modal-title\">\n Add Options\n </h5>\n <button\n type=\"button\"\n class=\"close\"\n data-dismiss=\"modal\"\n aria-label=\"Close\"\n >\n <span\n aria-hidden=\"true\"\n @click=\"hideModal\"\n >×</span>\n </button>\n </div>\n <div class=\"modal-body\">\n <div class=\"dropdown-menu\" aria-labelledby=\"dropdownMenuButton\">\n <a class=\"dropdown-item\" href=\"#\">Action</a>\n <a class=\"dropdown-item\" href=\"#\">Another action</a>\n <a class=\"dropdown-item\" href=\"#\">Something else here</a>\n </div>\n </div>\n <div class=\"modal-footer\">\n <button\n type=\"button\"\n class=\"btn btn-secondary\"\n @click=\"hideModal\"\n >\n Close\n </button>\n <button type=\"button\" class=\"btn btn-primary\">\n Save changes\n </button>\n </div>\n </div>\n </div>\n </div>\n </div>\n </transition>\n </div>\n</template>\n\n<script>\nexport default {\n components: {},\n data () {\n return {}\n },\n methods: {\n hideModal () {\n this.$store.commit(\n 'hideModal'\n )\n }\n }\n}\n</script>\n\n<style>\n</style>\n```\n\n```text\nNuxt.js\n```\n\n```text\nNuxt.js and Vue.js\n```\n\n```text\nNuxt cli\n```\n\n```text\nBootstrap-vue\n```\n\n```text\nBootstrap modal\n```\n\n```text\nBootstrap vue\n```\n\n```text\nBootstrap\n```\n\n```text\nModal\n```\n\n```text\ndrop-downs\n```\n\n```text\nBootstrap vue\n```\n\n```text\nBootstrap\n```\n\n```text\nnpm i bootstrap-vue --save\n```\n\n```text\nbootstrap-vue.js\n```\n\n```text\nplugins\n```\n\n```text\nplugin\n```\n\n```text\nnuxt-config.js\n```\n\n```text\nplugins: [\"@/plugins/bootstrap-vue\"],\n```\n\n```text\nnuxt-config.js\n```\n\n```text\nBoostrap\n```\n\n```text\nnuxt-config.js\n```\n\n```text\nplugins/bootstrap-vue.js\n```\n\n```js\nexport default {\n modules: [\n 'bootstrap-vue/nuxt',\n ],\n}\n```\n\n```html\n<template>\n <div>\n <b-button v-b-modal.modal-1>Launch demo modal</b-button>\n\n <b-modal id=\"modal-1\" title=\"BootstrapVue\">\n <p class=\"my-4\">Hello from modal!</p>\n\n <b-dropdown id=\"dropdown-1\" text=\"Dropdown Button\" class=\"m-md-2\">\n <b-dropdown-item>First Action</b-dropdown-item>\n <b-dropdown-item>Second Action</b-dropdown-item>\n <b-dropdown-item>Third Action</b-dropdown-item>\n <b-dropdown-divider></b-dropdown-divider>\n <b-dryopdown-item active>Active action</b-dryopdown-item>\n <b-dropdown-item disabled>Disabled action</b-dropdown-item>\n </b-dropdown>\n </b-modal>\n </div>\n</template>\n```\n\n```text\nnpx create-nuxt-app my-awesome-project\n```\n\n```text\nyarn add bootstrap-vue\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- Don't you want to fix Bootstrap Vue? Using Bootstrap-only will make you lose all the components logic that is already done for you. So, it'll become just some styling and nothing dynamic (so no `Datepicker` for example). If you want style only, you should probably consider something else too. What is the issue with Bootstrap modal?\n- On a side note, if you want a guide to properly install and use jquery, here: stackoverflow.com/a/68414170/8816585\n- @kissu Actually I am fine with fixing the `Bootstrap Vue` as well. Since I was not finding any proper example with dropdowns and workflow I thought of switching to `Plain Bootstrap` as I have worked with it briefly before. Please let me know what steps I need to to fix my `Bootstrap vue` and get it working properly with my `Modal`.\n- Show us your `nuxt.config.js` file, any additional configuration related to Boostrap-vue done so far and what is not working (vs what is expected) please.\n- @kissu Thanks for your response. Based on your request I have updated the question with a code sample and more information. Please let me know whats the problem is or if you need any more information.\n- `https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstra‌​p.min.css` Any reason why you're using such an old version of Bootstrap? Specifically if you're using BootstrapVue you should be using version `4.5.3` of Bootstrap.","metadata":{"transformedAt":"2026-08-18T18:33:07.871Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":31,"totalLines":560,"estimatedTokens":3178}}489{"id":"stack-74749448","source":"stackoverflow","questionId":74749448,"title":"Dark mode switcher in Nuxt 3 not working with official @nuxtjs/color-mode","tags":["javascript","nuxt.js","tailwind-css","nuxt3.js","darkmode"],"text":"Title: Dark mode switcher in Nuxt 3 not working with official @nuxtjs/color-mode\nTags: javascript, nuxt.js, tailwind-css, nuxt3.js, darkmode\nSource: Stack Overflow\n\nQuestion:\nI wanted to implement dark mode on my Nuxt app using tailwind and the recommended @nuxtjs/color-mdoe module. Testing tailwind's dark: classes went fine and worked as expected, however I can't make a button switcher work to set the color mode programmatically.\n\nI installed in devDeps the module in version 3.2.0, which should be compatible with Nuxt 3, according to the docs\n\n```\n\"@nuxtjs/tailwindcss\": \"^6.1.3\",\n\"@nuxtjs/color-mode\": \"^3.2.0\"\n```\n\nAnd applied the proper configuration in `nuxt.config.ts`\n\n```\nmodules: [ '@nuxtjs/color-mode' ],\ncolorMode: {\n classSuffix: '',\n preference: 'system',\n fallback: 'dark'\n }\n```\n\nI used tailwind nuxt module\nIn **tailwind.config.js**\n\n```\nmodule.exports= {\n theme: {\n colors: {\n transparent: 'transparent',\n current: 'currentColor',\n dark: '#212129',\n darkPrimary: '#00E1FF',\n darkSecondary: '#00D6D6',\n light: '#E9DAC1',\n lightPrimary: '#1d68f3',\n lightSecondary: '#00b5f0',\n main: '#0073FF',\n white: '#FFFFFF',\n },\n spacing: {\n 'header': '120px',\n },\n darkMode: 'class'\n }\n}\n```\n\nWhile in **./assets/css/main.css** I have no meaningful config about dark mode, just some classes I defined globally\n\n```\nhtml {\n @apply transition-colors ease-in duration-1000;\n @apply bg-gradient-to-b bg-no-repeat w-screen ;\n @apply dark:from-dark/95 dark:via-dark/95 dark:to-dark dark:text-white from-white via-light/50 to-light;\n}\n\n.contain {\n @apply px-[5%] md:px-[25%]; \n}\n```\n\nSince I wanted to place the switch in the header here's what I did in the component:\n\n```\n\n \n \n \n \n \n \n\nfunction toggleDarkMode(theme) {\n useColorMode().preference = theme\n}\n\n```\n\nThe classes are actually toggling when I manually change the color mode from my os (win11) settings, but clicking the button won't replicate the same behavior. The mode seems to be switching since the icon does change accordingly.\n\nLooking at the docs and tutorials I found elsewhere it should just work like that.\n\nDo I need to set the mode as a global state inside the store? Should I call the hook in a root-level component?\n\n========================================\n\nTop Answer:\nFor anybody else wondering,\nthis is a working solution with **`@nuxt/ui` module** but you can use your own element.\n\nThe trick is in changing the **model-value (with Vue)**, otherwise, the toggle will change the value to `true` and `false` and not string values.\n\n```\n\n```\n\n========================================\n\nCode:\n```json\n\"@nuxtjs/tailwindcss\": \"^6.1.3\",\n\"@nuxtjs/color-mode\": \"^3.2.0\"\n```\n\n```js\nmodules: [ '@nuxtjs/color-mode' ],\ncolorMode: {\n classSuffix: '',\n preference: 'system',\n fallback: 'dark'\n }\n```\n\n```js\nmodule.exports= {\n theme: {\n colors: {\n transparent: 'transparent',\n current: 'currentColor',\n dark: '#212129',\n darkPrimary: '#00E1FF',\n darkSecondary: '#00D6D6',\n light: '#E9DAC1',\n lightPrimary: '#1d68f3',\n lightSecondary: '#00b5f0',\n main: '#0073FF',\n white: '#FFFFFF',\n },\n spacing: {\n 'header': '120px',\n },\n darkMode: 'class'\n }\n}\n```\n\n```css\nhtml {\n @apply transition-colors ease-in duration-1000;\n @apply bg-gradient-to-b bg-no-repeat w-screen ;\n @apply dark:from-dark/95 dark:via-dark/95 dark:to-dark dark:text-white from-white via-light/50 to-light;\n}\n\n.contain {\n @apply px-[5%] md:px-[25%]; \n}\n```\n\n```html\n<template>\n <header class=\"contain py-[15px] flex items-center justify-between backdrop-blur-3xl\">\n <button @click=\"toggleDarkMode($colorMode.preference === 'dark' ? 'light' : 'dark')\">\n <nuxt-icon v-if=\"$colorMode.preference === 'dark'\" name=\"sun\"/>\n <nuxt-icon v-else name=\"moon\"/>\n </button>\n </header>\n</template>\n\n<script setup>\nfunction toggleDarkMode(theme) {\n useColorMode().preference = theme\n}\n</script>\n```\n\n```text\nnuxt.config.ts\n```\n\n```json\n\"devDependencies\": {\n \"@nuxtjs/color-mode\": \"^3.2.0\",\n \"autoprefixer\": \"^10.4.13\",\n \"nuxt\": \"3.0.0\",\n \"postcss\": \"^8.4.19\",\n \"tailwindcss\": \"^3.2.4\"\n }\n```\n\n```js\n/** @type {import('tailwindcss').Config} */\nmodule.exports = {\n content: ['./app.vue'], // you forget content\n darkMode: 'class', //you should define darkMode here\n theme: {\n extend: {},\n //darkMode: 'class' >> this is mistake\n },\n plugins: [],\n};\n```\n\n```css\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n@layer base {\n body{\n @apply bg-lightPrimary dark:bg-darkPrimary;\n }\n}\n```\n\n```text\n// https://v3.nuxtjs.org/api/configuration/nuxt.config\nexport default defineNuxtConfig({\n modules: ['@nuxtjs/color-mode'],\n colorMode: {\n classSuffix: '',\n preference: 'system',\n fallback: 'dark',\n },\n css: ['/assets/css/main.css'],\n postcss: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n },\n});\n```\n\n```text\npackage.json\n```\n\n```text\n3.1.6\n```\n\n```text\ntailwind.config.js\n```\n\n```text\ncontent\n```\n\n```text\ndarkMode\n```\n\n```text\ntheme\n```\n\n```text\nmain.css\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\ndarkMode\n```\n\n```text\ndarkMode: 'class'\n```\n\n```text\ncontent\n```\n\n```text\nmain.css\n```\n\n```text\nnuxt.config.ts\n```\n\n```html\n<UToggle\n:model-value=\"colorMode.preference === 'dark'\"\n@update:model-value=\"colorMode.preference = $event ? 'dark' : 'light'\"\n/>\n```\n\n```text\n@nuxt/ui\n```\n\n```text\ntrue\n```\n\n```text\nfalse\n```\n\n========================================\n\nComments:\n- hi, what do you mean when you say, classes toggling and where is your CSS or SCSS file I have exactly the same code and it's working when I press the button the root class changes to dark\n- pls check this link stackblitz.com/edit/github-ac9rz7?file=README.md\n- The demo is working perfectly fine, are you sure you don't have an extension running? .cleanshot.com/ejDEUZ\n- Also, if that Nuxt module doesn't work well, maybe give a try to that VueUse composable used here: github.com/antfu/vitesse/blob/… (`useDark`)\n- @sadeqshahmoradi I mean I wanted to switch mode with a button. I edited my question to post the tailwind and css files too\n- @kissu I have the dark reader extension but I did disabled it on localhost. I tried useDark hook too from vueuse but to no avail\n- I was indeed the 'darkMode' property of tailwind's config in the wrong place (theme). Such a silly mistake, thank you so much ahahah. Anyway all the missing configs you saw in my snippets were due to me using the tailwind's nuxt official module, which should have made it easier actually. Therefore no content property, in fact my custom colors and other tailwind's classes were all working correctly. Thanks a lot <3\n- Happy to help my friend","metadata":{"transformedAt":"2026-08-18T18:33:07.871Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":309,"estimatedTokens":1674}}490{"id":"stack-67767619","source":"stackoverflow","questionId":67767619,"title":"Nuxt-Laravel-Sanctum CSRF token mismatch 419 error","tags":["laravel","nuxt.js","laravel-sanctum"],"text":"Title: Nuxt-Laravel-Sanctum CSRF token mismatch 419 error\nTags: laravel, nuxt.js, laravel-sanctum\nSource: Stack Overflow\n\nQuestion:\nI have a Nuxt-Laravel-Sanctum CSRF token mismatch 419 error while Laravel is hosted on a server and Nuxt is on localhost on a PC. I have uploaded my Laravel project for getting API on api.repairtofix.com.\n\nAnd I am trying to log in from `localhost` in my pc from Nuxt. While clicking on the login button I get the following error.\n\n{message: \"CSRF token mismatch.\", exception:\n\"Symfony\\Component\\HttpKernel\\Exception\\HttpException\",…}\n\n**Login method**\n\n```\nlogin() {\n this.$auth.loginWith('laravelSanctum', { \n data: this.form \n })\n .then(response => console.log(response))\n .catch(error => console.log(response))\n}\n```\n\n**.env**\n\n```\nAPP_URL=http://api.repairtofix.com\nSESSION_DOMAIN=api.repairtofix.com\nSANCTUM_STATEFUL_DOMAINS=.repairtofix.com,localhost:3000\n```\n\n**Kernel.php**\n\n```\n'api' => [\n EnsureFrontendRequestsAreStateful::class,\n 'throttle:api',\n \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\n],\n```\n\n**sanctum.php**\n\n```\n'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', \n 'api.repairtofix.com,localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1'\n)),\n```\n\n**cors.php**\n\n```\n'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'signup', 'getUser'],\n'allowed_methods' => ['*'],\n'allowed_origins' => ['*'],\n'allowed_origins_patterns' => [],\n'allowed_headers' => ['*'],\n'exposed_headers' => [],\n'max_age' => 0,\n'supports_credentials' => true,\n```\n\n**api.php**\n\n```\nRoute::middleware('auth:sanctum')->get('/user', function (Request $request) {\n return $request->user();\n});\n\n// register\nRoute::get('register', function(Request $request){\n $user = User::create([\n 'name' => $request->name,\n 'email' => $request->email,\n 'password' => bcrypt($request->password)\n ]);\n\n return $user;\n});\n\n// login\nRoute::post('login', function(Request $request){\n $credentials = $request->only('email', 'password');\n if(!auth()->attempt($credentials)){\n throw ValidationException::withMessages([\n 'email' => 'Invalid credentials'\n ]);\n }\n\n $request->session()->regenerate();\n return response()->json(null, 201);\n});\n\n// logout\nRoute::post('logout', function(Request $request){\n auth()->guard('web')->logout();\n $request->session()->invalidate();\n $request->session()->regenerateToken();\n return response()->json(null, 201);\n});\n```\n\n**nuxt.config.js**\n\n```\nmodules: [\n '@nuxtjs/axios',\n '@nuxtjs/pwa',\n '@nuxtjs/auth-next',\n '@nuxtjs/toast',\n],\n\nauth:{\n strategies: {\n 'laravelSanctum': {\n provider: 'laravel/sanctum',\n url: 'http://api.repairtofix.com',\n endpoints: {\n login: {\n url: '/api/login'\n },\n logout: {\n url: '/api/logout'\n },\n user: {\n url: '/api/user'\n },\n },\n user: {\n property: false\n }\n },\n },\n redirect: {\n login: \"/login\",\n logout: \"/\",\n home: \"/\"\n }\n},\n```\n\n========================================\n\nTop Answer:\nIn my case, Axios credentials were not set to true in nuxt.config file, also the text is case sensitive\n\n```\naxios: {\n baseUrl: 'http://localhost:8000',\n credentials: true,\n },\n```\n\n========================================\n\nCode:\n```text\nlogin() {\n this.$auth.loginWith('laravelSanctum', { \n data: this.form \n })\n .then(response => console.log(response))\n .catch(error => console.log(response))\n}\n```\n\n```text\nAPP_URL=http://api.repairtofix.com\nSESSION_DOMAIN=api.repairtofix.com\nSANCTUM_STATEFUL_DOMAINS=.repairtofix.com,localhost:3000\n```\n\n```text\n'api' => [\n EnsureFrontendRequestsAreStateful::class,\n 'throttle:api',\n \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\n],\n```\n\n```text\n'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', \n 'api.repairtofix.com,localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1'\n)),\n```\n\n```text\n'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'signup', 'getUser'],\n'allowed_methods' => ['*'],\n'allowed_origins' => ['*'],\n'allowed_origins_patterns' => [],\n'allowed_headers' => ['*'],\n'exposed_headers' => [],\n'max_age' => 0,\n'supports_credentials' => true,\n```\n\n```text\nRoute::middleware('auth:sanctum')->get('/user', function (Request $request) {\n return $request->user();\n});\n\n// register\nRoute::get('register', function(Request $request){\n $user = User::create([\n 'name' => $request->name,\n 'email' => $request->email,\n 'password' => bcrypt($request->password)\n ]);\n\n return $user;\n});\n\n// login\nRoute::post('login', function(Request $request){\n $credentials = $request->only('email', 'password');\n if(!auth()->attempt($credentials)){\n throw ValidationException::withMessages([\n 'email' => 'Invalid credentials'\n ]);\n }\n\n $request->session()->regenerate();\n return response()->json(null, 201);\n});\n\n// logout\nRoute::post('logout', function(Request $request){\n auth()->guard('web')->logout();\n $request->session()->invalidate();\n $request->session()->regenerateToken();\n return response()->json(null, 201);\n});\n```\n\n```text\nmodules: [\n '@nuxtjs/axios',\n '@nuxtjs/pwa',\n '@nuxtjs/auth-next',\n '@nuxtjs/toast',\n],\n\nauth:{\n strategies: {\n 'laravelSanctum': {\n provider: 'laravel/sanctum',\n url: 'http://api.repairtofix.com',\n endpoints: {\n login: {\n url: '/api/login'\n },\n logout: {\n url: '/api/logout'\n },\n user: {\n url: '/api/user'\n },\n },\n user: {\n property: false\n }\n },\n },\n redirect: {\n login: \"/login\",\n logout: \"/\",\n home: \"/\"\n }\n},\n```\n\n```text\nlocalhost\n```\n\n```text\nIn order to authenticate, your SPA and API must share the same top-level domain. However, they may be placed on different subdomains.\n```\n\n```text\naxios: {\n baseUrl: 'http://localhost:8000',\n credentials: true,\n },\n```\n\n```text\nAIRLOCK_STATEFUL_DOMAINS=127.0.0.1\n```\n\n```text\nawait axios.get(\"http://127.0.0.1:8000/sanctum/csrf-cookie\");\n```\n\n```text\nawait axios.get(\"http://127.0.0.1:8000/bah/bah/bal\");\n```\n\n========================================\n\nComments:\n- You need to use token-based authentication in this case. Stateful domains and \"EnsureFrontendRequestsAreStateful\" are using Laravel's session cookie-based authentication, which is only working when both application the same top-level domain.\n- This enlightened me, thanks. I have my backend and frontend on different domains and nothins was working. I didn't notice that they can be on different subdomains but under the same top-level domain. I guess I will have to use token-based authentication now (JWT).\n- UPDATE: I completely forgot that I don't even need to implement JWT because that would be much complicated unnecessary. Instead I added a CNAME to my domain DNS settings so now both of them live under the same domain like this: laravel backend -> api.mydomain.com nextjs frontend -> mydomain.com and it works!\n- Yeah, that is a common approach.","metadata":{"transformedAt":"2026-08-18T18:33:07.871Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":307,"estimatedTokens":1760}}491{"id":"stack-67771384","source":"stackoverflow","questionId":67771384,"title":"Using Capacitor 3 with Nuxtjs SSR","tags":["nuxt.js","capacitor"],"text":"Title: Using Capacitor 3 with Nuxtjs SSR\nTags: nuxt.js, capacitor\nSource: Stack Overflow\n\nQuestion:\nI'm on Nuxtjs 2.15.4 ssr mode and I wanna add Capacitorjs 3 to my project. As I read the doc, I found out for `webDir` we should add `dist` directory that is created by `npm run generate` which is for static mode `target: static` not `npm run build` (for ssr apps).\n\nSo what is the correct way of configurating Capacitor for SSR Nuxt??\n\n========================================\n\nCode:\n```text\nwebDir\n```\n\n```text\ndist\n```\n\n```text\nnpm run generate\n```\n\n```text\ntarget: static\n```\n\n```text\nnpm run build\n```\n\n```text\n{\n \"appId\": \"io.mysillyapp.app\",\n \"appName\": \"My Silly App\",\n \"server\": {\n \"url\": \"https://mysillyapp.myapphosting.io\"\n },\n \"linuxAndroidStudioPath\": \"/snap/bin/android-studio\"\n}\n```\n\n```text\n{\n ...\n server: process.env.HOST ? { url: `${process.env.HOST}:${process.env.PORT ?? 8100 }` : undefined\n ...\n}\n```\n\n```text\nWeb asset directory specified by webDir does not exist. This is not an error because server.url is set in config.\n```\n\n```text\n{\n ...\n \"webDir\": \".nuxt\",\n ...\n}\n```\n\n```text\n/**\n * Load an external URL in the Web View.\n *\n * This is intended for use with live-reload servers.\n *\n * **This is not intended for use in production.**\n *\n * @since 1.0.0\n */\n url?: string;\n```\n\n```text\nwebdir\n```\n\n```text\nserver: {url: }\n```\n\n```text\nnpx cap copy\n```\n\n```text\nwebDir\n```\n\n```text\n.nuxt\n```\n\n```text\nserver url\n```\n\n```text\nserver url\n```\n\n========================================\n\nComments:\n- What did you tried so far? Does this codesandbox help: codesandbox.io/s/79cm0 Looks like it's totally configured already. There is this one also: github.com/MexsonFernandes/nuxt-ionic-capacitor-app\n- Hmmm... , the serverMiddleware ! huh! gonna try that. tanx\n- Yes, this is only related to server and some Node.js.\n- I'm encountering the same issue with my Nuxt SSR - did you figure out what `webDir` needs to be set as? I've tried setting it to `.nuxt` and `dist` (which doesn't exist as it's srr) but no luck\n- @JonathanRobbins you don't ever need to touch to `.nuxt` (cache) nor `dist` (final built directory).\n- It's not the `.nuxt` or `dist` directory that I am touching, its value of `webDir` in `capacitor.config.json` @MojtabaBarari used to solve the original issue I want to know\n- @JonathanRobbins maybe you can get inspired from what Quasar is doing.\n- Additionally Dan Pastori seems to have a ton of knowledge on this topic. Here's a relevant reddit dicussion: reddit.com/r/Nuxt/comments/qo0i19/comment/hjp0fnx/…","metadata":{"transformedAt":"2026-08-18T18:33:07.871Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":115,"estimatedTokens":656}}492{"id":"stack-51892252","source":"stackoverflow","questionId":51892252,"title":"Nuxt - How can I run a code in client-side after server-side-rendering?","tags":["vue.js","nuxt.js","server-side-rendering","noty"],"text":"Title: Nuxt - How can I run a code in client-side after server-side-rendering?\nTags: vue.js, nuxt.js, server-side-rendering, noty\nSource: Stack Overflow\n\nQuestion:\nI created a plugin injecting a noty (https://ned.im/noty/#/) so I can use it globally, it looks like this:\n\n```\nexport default ({ app }, inject) => {\n\n const notify = function (options = {}) {\n if (process.client) {\n new Noty(options).show();\n }\n }\n\n app.$notify = notify;\n inject('notify', notify);\n\n}\n```\n\nThis plugin shows a noty only on the client-side. On the server-side a noty does not appear, cause it can be displayed only in browser.\nI have a page with product details and I am receiving data in asyncData method. When the product was not found I would like to show a noty with proper message and redirect user to a product list page. When I change a route in client-side everything works awesome. However on the first page load (eg. I change an url manually in the browser) which happens on the server-side a noty does not appear, only a redirect works.\nMy question is: how to show a noty in this case? How to create a noty in the browser after SSR or what is the best other solution to my problem?\n\nIs there any way to run some code after client-side is already rendered (after server-side-rendering)?\n\n========================================\n\nTop Answer:\nYou could just disable ssr for that plugin.\n\n```\nplugins: [\n ...,\n { src: '~plugins/yourplugin.js', ssr: false }\n]\n```\n\n========================================\n\nCode:\n```text\nexport default ({ app }, inject) => {\n\n const notify = function (options = {}) {\n if (process.client) {\n new Noty(options).show();\n }\n }\n\n app.$notify = notify;\n inject('notify', notify);\n\n}\n```\n\n```text\nplugins: [\n ...,\n { src: '~plugins/yourplugin.js', ssr: false }\n]\n```\n\n```js\n<script setup>\nconsole.log('run in server-side.');\nonMounted(() => {\n console.log('run in client-side.');\n});\n</script>\n```\n\n========================================\n\nComments:\n- The problem, I am facing, is that you cannot create a reactive property inside onMounted function","metadata":{"transformedAt":"2026-08-18T18:33:07.871Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":78,"estimatedTokens":528}}493{"id":"stack-52624166","source":"stackoverflow","questionId":52624166,"title":"How to access store context within a plugin in nuxt?","tags":["vue.js","nuxt.js"],"text":"Title: How to access store context within a plugin in nuxt?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI try to add third party code and use it in my Nuxt app. Basically I wrote a plugin under `@/plugins/vendorCode/logFn.js` which contains a dumb function :\n\n```\nexport default ({ store }) => {\n console.log('store is', store)\n}\n```\n\nAs you can see I try to access store and perform later some mutation. That's my next step.\nBut for now I'm stuck.\n\nIn my Vue Component, I've a button calling the logFn, here's what I did :\n\n```\n\nimport logFn from '@/plugins/vendorCode/logFn.js'\n\n export default {\n methods: {\n onClick () {\n logFn()\n }\n }\n }\n\n```\n\nSo far so good. Once page reload, I can see the result of my logFn in the console, with the store object.\n\n**First question : why it is print now ? I did not call it at all.**\n\nThen I click the button and got an error : `TypeError: Cannot read property 'store' of undefined`. \n\n**Second question : why this error regarding the log I had previously?**\n\nThank you for your help\n\n========================================\n\nCode:\n```text\nexport default ({ store }) => {\n console.log('store is', store)\n}\n```\n\n```text\n<script>\nimport logFn from '@/plugins/vendorCode/logFn.js'\n\n export default {\n methods: {\n onClick () {\n logFn()\n }\n }\n }\n</script>\n```\n\n```text\n@/plugins/vendorCode/logFn.js\n```\n\n```text\nTypeError: Cannot read property 'store' of undefined\n```\n\n```text\nexport default function (context) {\n console.log('store is', context.store)\n}\n```\n\n```text\nexport default (store) => { // <- not { store }, but store\n console.log('store is', store)\n}\n```\n\n```text\n<script>\nimport logFn from '~/assets/js/logFn.js'\n\n export default {\n methods: {\n onClick () {\n logFn(this.$store)\n }\n }\n }\n</script>\n```\n\n```text\nlogFn.js\n```\n\n```text\n~/assets/js/logFn.js\n```\n\n```text\npage.vue\n```\n\n========================================\n\nComments:\n- it works, I did this at first but thought it was bit odd to pass store like this. Thank you for your help sosmii","metadata":{"transformedAt":"2026-08-18T18:33:07.871Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":115,"estimatedTokens":517}}494{"id":"stack-67879210","source":"stackoverflow","questionId":67879210,"title":"Nuxt static not loading fetched state when pushing new route","tags":["vue.js","nuxt.js","server-side-rendering","static-site-generation"],"text":"Title: Nuxt static not loading fetched state when pushing new route\nTags: vue.js, nuxt.js, server-side-rendering, static-site-generation\nSource: Stack Overflow\n\nQuestion:\nI'm generating full static web app using nuxt as described here https://nuxtjs.org/blog/going-full-static/#crazy-fast-static-applications\n\nI have a small blog to load as static site also, so I'm using the fetch hook to load the data from api.\n\n```\nasync fetch() {\n this.posts = await fetch(`${this.baseApi}/posts`).then(res => res.json())\n},\n```\n\nWhen I generate (`npm run generate`), the fetched state is properly generated inside the `dist/assets/static`, so when directly accessing `/blog`, the state is properly loaded and the data displays correctly.\nHowever, when I'm in the homepage, and access the blog using a\n\n```\nthis.$router.push\n```\n\nor a\n\n```\nBlog\n```\n\nThe fetched state does not get loaded, and I have to call the api again, or call `this.$fetch()` one more time in the `mounted()` hook\n\nI have already added a\n\n```\nwatch: {\n '$route.query': '$fetch'\n}\n```\n\nto the homepage\n\nI need the fetched state to be properly loaded when using navigation What am I still missing ?\n\nClarification\n\nI'm not experiencing any problem with the fetch hook by itself, but rather with the navigation not retrieving the state of the target route.\nEven the HTML is there\nI need the page to get the state of the target route, when the route changes, because the vue template depends on it, so if it's not loaded, the ui won't display anything, and i'm forced to call the fetch hook manually\n\nFor a clearer view, This is a screenshot of my devtools while directly accessing /blog, notice how state.js is properly retrieved (it contains all rendered content)\nhttps://i.sstatic.net/I73Tm.png\n\nAnd the following is a screenshot of my devtools while accessing /, and then going to blog using nuxt-link, or a this.$router.push (same result)\n\nhttps://i.sstatic.net/WfqCe.png\n\nStatic state screenshot:\nhttps://i.sstatic.net/vA7db.jpg\n\n`Blog.vue`\n\n```\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n {{ replaceSlugByString(post.slug) }}\n \n \n \n \n Read more\n \n \n \n \n \n \n\nimport { mapState } from 'vuex'\n\nexport default {\n data() {\n return {\n slug: 'test',\n posts: {},\n currentPage: 1,\n perPage: 12,\n pageIndex: 1,\n totalPages: 1,\n }\n },\n async fetch() {\n const response = await fetch(`${this.baseApi}/StaticPage`)\n const fetchedPosts = await response.json()\n\n this.posts = fetchedPosts\n // this.posts = await fetch(`${this.baseApi}/StaticPage`).then(res =>res.json())\n },\n computed: {\n ...mapState('modules/settings', ['baseApi']),\n },\n beforeMount() {\n this.$fetch() // i want to remove this because the pages are statically generated correctly, I'm only adding it to refresh the state. which can be retrieved as a separate js file when accessing the route directly\n },\n methods: {\n openBlogPost(idx) {\n const pageObject = this.posts.data[idx]\n this.$router.push({\n name: `blog-slug`,\n params: {\n slug: pageObject.slug,\n page: pageObject,\n },\n })\n },\n replaceSlugByString(slug) {\n return slug.replaceAll('-', ' ')\n },\n },\n}\n\n```\n\nAnd here is the pastebin for slug.vue\n\nhttps://pastebin.com/DmJa9Mm1\n\n========================================\n\nTop Answer:\nEDIT:\n\n- `fetch()` hook is working great, even if you come to this specific page for the first time, it will be triggered\n\n- Vue devtools can help you find out if some state is missing or behaving in a weird manner.\n\n- there is no such thing as *state in static folder* since the state is not a static variable or thing at all, it's dynamic and available only at runtime.\n\n- this answer may help you see a working example with JSONplaceholder (with a list + details pages): How to have list + details pages based on API fetched content\n\nTry to not mix `async/await` and `then`.\n\nSo, this syntax should be more suited.\n\n```\nasync fetch() {\n const response = await fetch(`${this.baseApi}/posts`)\n const fetchedPosts = await response.json()\n console.log('posts', fetchedPosts)\n this.posts = fetchedPosts\n},\n```\n\nThen, you could debug with the network tab of the devtools to see if it is triggered. But I think that it should be fine then.\n\nThis answer that I just wrote more in-depth could also help understanding a bit more the `fetch()` hook: https://stackoverflow.com/a/67862314/8816585\n\n========================================\n\nCode:\n```js\nasync fetch() {\n this.posts = await fetch(`${this.baseApi}/posts`).then(res => res.json())\n},\n```\n\n```js\nthis.$router.push\n```\n\n```html\n<nuxt-link to=\"/blog\">Blog</nuxt-link>\n```\n\n```js\nwatch: {\n '$route.query': '$fetch'\n}\n```\n\n```html\n<template>\n <b-container class=\"container blog\">\n <b-row>\n <b-col lg=\"12\" md=\"12\" sm=\"12\" cols=\"12\" class=\"logo-col\">\n <SbLogoSingle />\n </b-col>\n </b-row>\n <b-row v-if=\"$fetchState.pending\" class=\"text-center\">\n <b-spinner style=\"margin: auto\"></b-spinner>\n </b-row>\n <b-row v-else>\n <b-col\n v-for=\"(post, idx) in posts.data\"\n :key=\"idx\"\n lg=\"4\"\n md=\"4\"\n sm=\"6\"\n cols=\"12\"\n class=\"blog-post-col\"\n >\n <b-card\n v-if=\"post !== undefined\"\n no-body\n class=\"shadow-lg blog-post-card\"\n :img-src=\"post.media.url\"\n img-top\n >\n <b-card-body class=\"text-left\">\n <b-card-title>{{ replaceSlugByString(post.slug) }}</b-card-title>\n <b-card-text\n class=\"post-short-description\"\n v-html=\"post.localizations[0].shortDescription\"\n ></b-card-text>\n </b-card-body>\n <template #footer>\n <div class=\"text-left\">\n <b-button class=\"apply-btn read-more-btn\" @click=\"openBlogPost(idx)\">Read more</b-button>\n </div>\n </template>\n </b-card>\n </b-col>\n </b-row>\n </b-container>\n</template>\n\n<script>\nimport { mapState } from 'vuex'\n\nexport default {\n data() {\n return {\n slug: 'test',\n posts: {},\n currentPage: 1,\n perPage: 12,\n pageIndex: 1,\n totalPages: 1,\n }\n },\n async fetch() {\n const response = await fetch(`${this.baseApi}/StaticPage`)\n const fetchedPosts = await response.json()\n\n this.posts = fetchedPosts\n // this.posts = await fetch(`${this.baseApi}/StaticPage`).then(res =>res.json())\n },\n computed: {\n ...mapState('modules/settings', ['baseApi']),\n },\n beforeMount() {\n this.$fetch() // i want to remove this because the pages are statically generated correctly, I'm only adding it to refresh the state. which can be retrieved as a separate js file when accessing the route directly\n },\n methods: {\n openBlogPost(idx) {\n const pageObject = this.posts.data[idx]\n this.$router.push({\n name: `blog-slug`,\n params: {\n slug: pageObject.slug,\n page: pageObject,\n },\n })\n },\n replaceSlugByString(slug) {\n return slug.replaceAll('-', ' ')\n },\n },\n}\n</script>\n```\n\n```text\nnpm run generate\n```\n\n```text\ndist/assets/static\n```\n\n```text\n/blog\n```\n\n```text\nthis.$fetch()\n```\n\n```text\nmounted()\n```\n\n```text\nBlog.vue\n```\n\n```text\nexport const state = () => ({\n posts:[]\n})\nexport const mutations = {\n SET_POSTS(state, posts) {\n state.posts = posts\n }\n}\n```\n\n```text\nasync fetch() {\n const response = await this.$axios.$get(`${this.baseApi}/posts`)\n this.$store.commit(\"modules/blog/SET_POSTS\",response)\n}\n```\n\n```text\nnuxt generate\n```\n\n```text\n$fetch\n```\n\n```text\nstore/modules/blog.js\n```\n\n```text\nnpm run generate\n```\n\n```text\ndist/assets/static/<someid>/state.js\n```\n\n```text\nmodules:{blog:{posts:[]}...\n```\n\n```text\ndist/assets/static/<someid>/blog/state.js\n```\n\n```text\nmodules:{blog:{posts:{success:am,code:an ...\n```\n\n```text\ndist/assets/static/<someid>/blog/payload.js\n```\n\n```text\npayload.js\n```\n\n```text\n<nuxt-link to='/blog'>\n```\n\n```text\n/blog\n```\n\n```text\nstate.js\n```\n\n```text\npayload.js\n```\n\n```js\nasync fetch() {\n const response = await fetch(`${this.baseApi}/posts`)\n const fetchedPosts = await response.json()\n console.log('posts', fetchedPosts)\n this.posts = fetchedPosts\n},\n```\n\n```text\nfetch()\n```\n\n```text\nasync/await\n```\n\n```text\nthen\n```\n\n```text\nfetch()\n```\n\n========================================\n\nComments:\n- Not sure that `'$route.query': '$fetch'` will be useful here. Also, you're using `$fetch` and `fetch`, be careful of not mixing them both.\n- Correct, it's not useful.\n- Pretty difficult to see what is the issue without more of the `Blog.vue` file itself. Also, install the Vue devtools to be able to debug your state more easily.\n- blog.vue: pastebin.com/2tQMq7t7 . I don't think it's useful to include screenshots of the vue dev tools. The problem is clear, the state is only fetched from the static folder if you access the url directly. Is this is the expected behavior?\n- Especially that vue dev tools work in dev mode (server side rendering where the $fetch hook is always called automatically before mounting, and the state.js is never fetched from the static folder) -- completely different story not related to my problem, that's why i didn't post screenshots of the vue dev tools.\n- Do you have another interesting `.vue` file to ? Like a `/blog/:slug` ?\n- I've updated my answer.\n- I have added the slug.vue\n- I tried this and it didn't work. I'm not experiencing problems with the fetch hook by itself, but rather with the navigation not retrieving the updated state of the target route, I have added a clarification and some screenshots to my question. Thanks\n- I do extensive research before asking, YES there is a static state generated for each route (I edited my question and included a screenshot in my question `Static State Screenshot`), because, isn't the point of static generation to no longer call fetch and asyncdata hooks ? (as explained here nuxtjs.org/blog/going-full-static ). I did not want to move the blog data to the store in order to not have them load inside the initial state.js. I will look into your JSONplaceholder suggestion\n- I managed to achieve what I needed which is no longer needed to call the $fetch to update the component's UI, by moving the data to the store, a separate file blog.js, I'm adding my definite answer, Thanks for all the help\n- Your contribution is very appreciated, but unfortunately did not help, since i didnt originally have any problem with the fetch hook. You were semi-right about the state.js though, it gets loaded only once, but there's a payload.js that gets loaded when the nuxt-link becomes visible, this payload.js fills the state with data taken from the store.. I'm adding everything to my answer\n- I answered my question, if you are interested in knowing how i solved it.\n- Hey! I'm facing with a similar problem. When I static generate the site with `asyncData` I can see the payload files generated, but navigating to that page it makes the API calls to the server. Is your `store` version the way to work really statically?\n- I did not get the question, but the solution for me, was to move all needed state data to the store, and let the page read data directly from the stored state\n- @Snsxn could you fix it? I can make it generate content with asyncData, it simply wont work...\n- @DanielVilela no, instead I've refactored everything to work with the new `fetch()`\n- Its important to set a key when using asycnData, otherwise nuxt will not know if to call the same api or not. The problem that i am having is that that the fetch command works when i do npm run generate, but the payload files fail because the pre-rendering crawler is looking for the data almost immediately.","metadata":{"transformedAt":"2026-08-18T18:33:07.872Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":426,"estimatedTokens":2902}}495{"id":"stack-55286011","source":"stackoverflow","questionId":55286011,"title":"Nuxt 2.5.0 + Firebase - dependencies were not found","tags":["firebase","nuxt.js"],"text":"Title: Nuxt 2.5.0 + Firebase - dependencies were not found\nTags: firebase, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI've been using firebase in Nuxt but with the 2.5.0 upgrade I'm getting these errors. Can't seem to figure out what the problem is?\n\n```\nERROR Failed to compile with 7 errors friendly-errors 13:21:54\n\nThese dependencies were not found: friendly-errors 13:21:54\n friendly-errors 13:21:54\n* core-js/fn/array/find in ./node_modules/@firebase/polyfill/dist/index.esm.js friendly-errors 13:21:54\n* core-js/fn/array/find-index in ./node_modules/@firebase/polyfill/dist/index.esm.js friendly-errors 13:21:54\n* core-js/fn/object/assign in ./node_modules/@firebase/polyfill/dist/index.esm.js friendly-errors 13:21:54\n* core-js/fn/string/repeat in ./node_modules/@firebase/polyfill/dist/index.esm.js friendly-errors 13:21:54\n* core-js/fn/string/starts-with in ./node_modules/@firebase/polyfill/dist/index.esm.js friendly-errors 13:21:54\n* core-js/fn/symbol in ./node_modules/@firebase/polyfill/dist/index.esm.js friendly-errors 13:21:54\n* core-js/fn/symbol/iterator in ./node_modules/@firebase/polyfill/dist/index.esm.js friendly-errors 13:21:54\n friendly-errors 13:21:54\nTo install them, you can run: npm install --save core-js/fn/array/find core-js/fn/array/find-index core-js/fn/object/assign core-js/fn/string/repeat core-js/fn/string/starts-with core-js/fn/symbol core-js/fn/symbol/iterator\n```\n\n========================================\n\nTop Answer:\nI have this exact problem. \n\n```\n* core-js/modules/es6.array.find in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.array.iterator in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.date.to-string in ./.nuxt/utils.js, ./.nuxt/components/nuxt.js\n* core-js/modules/es6.function.name in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.object.assign in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.object.keys in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.object.to-string in ./.nuxt/client.js, ./.nuxt/components/nuxt-link.client.js\n* core-js/modules/es6.promise in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.regexp.constructor in ./.nuxt/utils.js friendly-errors 20:39:58\n* core-js/modules/es6.regexp.match in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.regexp.replace in ./.nuxt/utils.js, ./.nuxt/components/nuxt.js\n* core-js/modules/es6.regexp.search in ./.nuxt/utils.js friendly-errors 20:39:58\n* core-js/modules/es6.regexp.split in ./.nuxt/utils.js, ./node_modules/babel-loader/lib??ref--2-0!./node_modules/vue-loader/lib??vue-loader-options!./.nuxt/components/nuxt-build-indicator.vue?vue&type=script&lang=js& and 1 other\n* core-js/modules/es6.regexp.to-string in ./.nuxt/utils.js, ./.nuxt/components/nuxt.js\n* core-js/modules/es6.string.includes in ./.nuxt/client.js, ./.nuxt/components/nuxt-link.client.js\n* core-js/modules/es6.string.iterator in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.string.repeat in ./.nuxt/utils.js friendly-errors 20:39:58\n* core-js/modules/es6.string.starts-with in ./.nuxt/utils.js friendly-errors 20:39:58\n* core-js/modules/es6.symbol in ./.nuxt/client.js, ./.nuxt/components/nuxt-link.client.js\n* core-js/modules/es7.array.includes in ./.nuxt/client.js, ./.nuxt/components/nuxt-link.client.js\n* core-js/modules/es7.object.get-own-property-descriptors in ./.nuxt/index.js\n* core-js/modules/es7.promise.finally in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es7.symbol.async-iterator in ./.nuxt/client.js, ./.nuxt/components/nuxt-link.client.js\n* core-js/modules/web.dom.iterable in ./.nuxt/client.js, ./.nuxt/components/nuxt-link.client.js\n```\n\nThe thing is, I'm running nuxt 2.11.\n\n========================================\n\nCode:\n```text\nERROR Failed to compile with 7 errors friendly-errors 13:21:54\n\nThese dependencies were not found: friendly-errors 13:21:54\n friendly-errors 13:21:54\n* core-js/fn/array/find in ./node_modules/@firebase/polyfill/dist/index.esm.js friendly-errors 13:21:54\n* core-js/fn/array/find-index in ./node_modules/@firebase/polyfill/dist/index.esm.js friendly-errors 13:21:54\n* core-js/fn/object/assign in ./node_modules/@firebase/polyfill/dist/index.esm.js friendly-errors 13:21:54\n* core-js/fn/string/repeat in ./node_modules/@firebase/polyfill/dist/index.esm.js friendly-errors 13:21:54\n* core-js/fn/string/starts-with in ./node_modules/@firebase/polyfill/dist/index.esm.js friendly-errors 13:21:54\n* core-js/fn/symbol in ./node_modules/@firebase/polyfill/dist/index.esm.js friendly-errors 13:21:54\n* core-js/fn/symbol/iterator in ./node_modules/@firebase/polyfill/dist/index.esm.js friendly-errors 13:21:54\n friendly-errors 13:21:54\nTo install them, you can run: npm install --save core-js/fn/array/find core-js/fn/array/find-index core-js/fn/object/assign core-js/fn/string/repeat core-js/fn/string/starts-with core-js/fn/symbol core-js/fn/symbol/iterator\n```\n\n```text\n* core-js/modules/es6.array.find in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.array.iterator in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.date.to-string in ./.nuxt/utils.js, ./.nuxt/components/nuxt.js\n* core-js/modules/es6.function.name in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.object.assign in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.object.keys in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.object.to-string in ./.nuxt/client.js, ./.nuxt/components/nuxt-link.client.js\n* core-js/modules/es6.promise in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.regexp.constructor in ./.nuxt/utils.js friendly-errors 20:39:58\n* core-js/modules/es6.regexp.match in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.regexp.replace in ./.nuxt/utils.js, ./.nuxt/components/nuxt.js\n* core-js/modules/es6.regexp.search in ./.nuxt/utils.js friendly-errors 20:39:58\n* core-js/modules/es6.regexp.split in ./.nuxt/utils.js, ./node_modules/babel-loader/lib??ref--2-0!./node_modules/vue-loader/lib??vue-loader-options!./.nuxt/components/nuxt-build-indicator.vue?vue&type=script&lang=js& and 1 other\n* core-js/modules/es6.regexp.to-string in ./.nuxt/utils.js, ./.nuxt/components/nuxt.js\n* core-js/modules/es6.string.includes in ./.nuxt/client.js, ./.nuxt/components/nuxt-link.client.js\n* core-js/modules/es6.string.iterator in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es6.string.repeat in ./.nuxt/utils.js friendly-errors 20:39:58\n* core-js/modules/es6.string.starts-with in ./.nuxt/utils.js friendly-errors 20:39:58\n* core-js/modules/es6.symbol in ./.nuxt/client.js, ./.nuxt/components/nuxt-link.client.js\n* core-js/modules/es7.array.includes in ./.nuxt/client.js, ./.nuxt/components/nuxt-link.client.js\n* core-js/modules/es7.object.get-own-property-descriptors in ./.nuxt/index.js\n* core-js/modules/es7.promise.finally in ./.nuxt/client.js friendly-errors 20:39:58\n* core-js/modules/es7.symbol.async-iterator in ./.nuxt/client.js, ./.nuxt/components/nuxt-link.client.js\n* core-js/modules/web.dom.iterable in ./.nuxt/client.js, ./.nuxt/components/nuxt-link.client.js\n```\n\n```text\nnpm install core-js@2.6.10\n```\n\n```text\n\"dependencies\": {\n \"@nuxtjs/auth\": \"^4.9.1\",\n \"@nuxtjs/axios\": \"^5.10.3\",\n \"@nuxtjs/firebase\": \"^5.0.7\",\n \"core-js\": \"2.6.10\",\n \"firebase\": \"^7.14.2\",\n \"nuxt\": \"^2.12.2\"\n },\n \"devDependencies\": {\n \"@nuxtjs/vuetify\": \"^1.11.2\"\n }\n```\n\n========================================\n\nComments:\n- wait for a hotfix in nuxt 2.5.1\n- Getting even more dependencies errors now: * core-js/modules/es6.array.find in ./.nuxt/client.js, ./node_modules/babel-loader/lib??ref--2-0!./node_modules/vue‌​-loader/lib??vue-loa‌​der-options!./pages/‌​home/index.vue?vue&t‌​ype=script&lang=js& and 1 other\n- @ChrisF. delete node modules and lock file and reinstall\n- I think it ended up being the package-lock.json file. Make sure you delete it and re-install.\n- firebase appears to use a different core-js version than cordova does by default. Version mismatch occurs and then this mess happens. Since cordova works with a webview, I instead enabled firebase in the webview rather than the native environment. Bummer.","metadata":{"transformedAt":"2026-08-18T18:33:07.872Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":129,"estimatedTokens":2286}}496{"id":"stack-66547299","source":"stackoverflow","questionId":66547299,"title":"Nuxt.js says compiled with some errors","tags":["nuxt.js"],"text":"Title: Nuxt.js says compiled with some errors\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhen running `npm run dev` says server error without exception that's why can't debug what's wrong\n\nhttps://i.sstatic.net/auioO.png\n\n========================================\n\nCode:\n```text\nnpm run dev\n```\n\n```text\nnpm run build\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.872Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":19,"estimatedTokens":82}}497{"id":"stack-51301959","source":"stackoverflow","questionId":51301959,"title":"TypeScript and tsconfig.json file for NuxtJS","tags":["typescript","nuxt.js"],"text":"Title: TypeScript and tsconfig.json file for NuxtJS\nTags: typescript, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a project with **NuxtJS** (*in ./src/client/*) and **NestJS** (*in ./src/server/*).\n\nThe **tsconfig.json** for **NuxtJS** is an extension of **tsconfig.json** for global project.\n\nI don't know how I can do to the project works.\n\nhttps://github.com/pirmax/nuxt-and-nest/tree/develop\n\nI have an error on NuxtJS when I go to root page:\n\n bundle export should be a function when using { runInNewContext: false\n }.\n\nIf I delete all traces of **NestJS** in my project, **NuxtJS** starts well, but when I add my configurations in **tsconfig.json**, the project gives me this error.\n\n### My tsconfig.json in ./src/client/\n\n```\n{\n \"extends\": \"../../tsconfig.json\",\n \"compilerOptions\": {\n \"rootDir\": \".\",\n \"target\": \"es5\",\n \"lib\": [\"dom\", \"es2015\"],\n \"module\": \"es2015\",\n \"moduleResolution\": \"node\",\n \"experimentalDecorators\": true,\n \"noImplicitAny\": false,\n \"noImplicitThis\": false,\n \"strictNullChecks\": true,\n \"removeComments\": true,\n \"suppressImplicitAnyIndexErrors\": true,\n \"allowSyntheticDefaultImports\": true,\n \"allowJs\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"~/*\": [\"./*\"]\n }\n }\n}\n```\n\n### My tsconfig.json in ./ (root)\n\n```\n{\n \"compilerOptions\": {\n \"declaration\": false,\n \"noImplicitAny\": false,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"module\": \"commonjs\",\n \"lib\": [\"es2015\"],\n \"target\": \"es5\",\n \"sourceMap\": true,\n \"allowJs\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \".\",\n \"paths\": {\n \"~/*\": [\n \"./*\"\n ],\n \"@app/*\": [\n \"./src/client/*\"\n ],\n \"@server/*\": [\n \"./src/server/*\"\n ]\n }\n },\n \"include\": [\n \"src/server/**/*\"\n ],\n \"exclude\": [\n \"node_modules\",\n \"**/*.spec.ts\"\n ]\n}\n```\n\n========================================\n\nTop Answer:\nIt is possible to specify custom `tsconfig.json` to `Nuxt App`. There is an option https://typescript.nuxtjs.org/guide/setup/#typecheck in `nuxt.config.json` which allows to point `Nuxt` to your `tsconfig.json` like this:\n\n```\ntypescript: {\n typeCheck: {\n typescript: {\n configFile: './tsconfig.nuxt.json'\n }\n }\n},\n```\n\nOther options https://github.com/TypeStrong/fork-ts-checker-webpack-plugin#typescript-options\n\n========================================\n\nCode:\n```text\n{\n \"extends\": \"../../tsconfig.json\",\n \"compilerOptions\": {\n \"rootDir\": \".\",\n \"target\": \"es5\",\n \"lib\": [\"dom\", \"es2015\"],\n \"module\": \"es2015\",\n \"moduleResolution\": \"node\",\n \"experimentalDecorators\": true,\n \"noImplicitAny\": false,\n \"noImplicitThis\": false,\n \"strictNullChecks\": true,\n \"removeComments\": true,\n \"suppressImplicitAnyIndexErrors\": true,\n \"allowSyntheticDefaultImports\": true,\n \"allowJs\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"~/*\": [\"./*\"]\n }\n }\n}\n```\n\n```text\n{\n \"compilerOptions\": {\n \"declaration\": false,\n \"noImplicitAny\": false,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"module\": \"commonjs\",\n \"lib\": [\"es2015\"],\n \"target\": \"es5\",\n \"sourceMap\": true,\n \"allowJs\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \".\",\n \"paths\": {\n \"~/*\": [\n \"./*\"\n ],\n \"@app/*\": [\n \"./src/client/*\"\n ],\n \"@server/*\": [\n \"./src/server/*\"\n ]\n }\n },\n \"include\": [\n \"src/server/**/*\"\n ],\n \"exclude\": [\n \"node_modules\",\n \"**/*.spec.ts\"\n ]\n}\n```\n\n```text\ntypescript: {\n typeCheck: {\n typescript: {\n configFile: './tsconfig.nuxt.json'\n }\n }\n},\n```\n\n```text\ntsconfig.json\n```\n\n```text\nNuxt App\n```\n\n```text\nnuxt.config.json\n```\n\n```text\nNuxt\n```\n\n```text\ntsconfig.json\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.872Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":197,"estimatedTokens":912}}498{"id":"stack-54789823","source":"stackoverflow","questionId":54789823,"title":"Middleware executing before Vuex Store restore from localstorage","tags":["vue.js","local-storage","persistence","vuex","nuxt.js"],"text":"Title: Middleware executing before Vuex Store restore from localstorage\nTags: vue.js, local-storage, persistence, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn nuxtjs project, I created an auth middleware to protect page.\nand using vuex-persistedstate (also tried vuex-persist and nuxt-vuex-persist) to persist vuex store.\n\nEverything is working fine when navigating from page to page, but when i refresh page or directly land to protected route, it redirect me to login page.\n\nlocalStorage plugin\n\n```\nimport createPersistedState from 'vuex-persistedstate'\n\nexport default ({ store }) => {\n createPersistedState({\n key: 'store-key'\n })(store)\n}\n```\n\nauth middleware\n\n```\nexport default function ({ req, store, redirect, route }) {\n const userIsLoggedIn = !!store.state.auth.user\n if (!userIsLoggedIn) {\n return redirect(`/auth/login?redirect=${route.fullPath}`)\n }\n return Promise.resolve()\n}\n```\n\n========================================\n\nTop Answer:\nI solved this problem by using this plugin vuex-persistedstate instead of the vuex-persist plugin. It seems there's some bug (or probably design architecture) in vuex-persist that's causing it.\n\n========================================\n\nCode:\n```text\nimport createPersistedState from 'vuex-persistedstate'\n\nexport default ({ store }) => {\n createPersistedState({\n key: 'store-key'\n })(store)\n}\n```\n\n```text\nexport default function ({ req, store, redirect, route }) {\n const userIsLoggedIn = !!store.state.auth.user\n if (!userIsLoggedIn) {\n return redirect(`/auth/login?redirect=${route.fullPath}`)\n }\n return Promise.resolve()\n}\n```\n\n```text\nthis.$cookies.set('token', 'Bearer '+response.tokens.access_token, { path: '/', maxAge: 60 * 60 * 12 })\n```\n\n```text\nthis.$cookies.remove('token')\n```\n\n```text\nasync nuxtServerInit ({dispatch, commit}, {app, $http, req}) {\n return new Promise((resolve, reject) => {\n let token = app.$cookies.get('token')\n if(!!token) {\n $http.setToken(token, 'Bearer')\n }\n return resolve(true)\n })\n },\n```\n\n```text\nexport default function ({app, req, store, redirect, route, context }) {\n if(process.server) {\n\n\n let token = app.$cookies.get('token')\n\n if(!token) {\n return redirect({path: '/auth/login', query: {redirect: route.fullPath, message: 'Token Not Provided'}})\n } else if(!isTokenValid(token.slice(7))) { // slice(7) used to trim Bearer(space)\n return redirect({path: '/auth/login', query: {redirect: route.fullPath, message: 'Token Expired'}})\n } \n return Promise.resolve()\n \n }\n else {\n const userIsLoggedIn = !!store.state.auth.user\n if (!userIsLoggedIn) {\n return redirect({path: '/auth/login', query: {redirect: route.fullPath}})\n // return redirect(`/auth/login?redirect=${route.fullPath}`)\n } else if (!isTokenValid(store.state.auth.tokens.access_token)) {\n return redirect({path: '/auth/login', query: {redirect: route.fullPath, message: 'Token Expired'}})\n // return redirect(`/auth/login?redirect=${route.fullPath}&message=Token Expired`)\n } else if (isTokenValid(store.state.auth.tokens.refresh_token)) {\n return redirect(`/auth/refresh`)\n } else if (store.state.auth.user.role !== 'admin')\n return redirect(`/403?message=Not having sufficient permission`)\n return Promise.resolve()\n }\n}\n```\n\n```text\n<no-ssr></no-ssr>\n```\n\n========================================\n\nComments:\n- Also experiencing this. Did you make any progress?\n- @SeanRussell I fail in solving the issue, but found a bypass to this by creating a redirect page. In my case store data was located at localstorage of client side. So whenever we perform refresh, server try to locate the store data on server, thats by it. So i create a redirect page. and change the above function accordingly. Mail me at yashdeep.rajput019@gmail.com for code.\n- @auedbaki Can you post the solution here, please? Thanks\n- This cannot be solve with client side solution. It happen because of absence of Vuex Store values at server side. Which is not possible with these libraries. You will experience when using asyncData Function which runs on server side.\n- Oh. That can be very true. But I experienced this issue using vuex-persist on the client side. On searching google, this page was the best result I could find so perhaps someone else who encounters the problem while using vuex-persist (before the issue is resolved in the plugin) can come across my comment and it will be of help. Besides there's nothing on servers in the question so I didn't know that.\n- I am surprised that there are no more docs or comments on this subject. There is no way to access browser local storage on server side. Meaning, store access will always be undefined. My auth middleware is working with cookies as well. Of course, I am talking ssr mode for nuxt and not spa.","metadata":{"transformedAt":"2026-08-18T18:33:07.872Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":127,"estimatedTokens":1241}}499{"id":"stack-58496743","source":"stackoverflow","questionId":58496743,"title":"In-component Navigation Guard callback not working: Nuxt JS and `beforeRouteEnter`","tags":["javascript","vue.js","vuejs2","vue-router","nuxt.js"],"text":"Title: In-component Navigation Guard callback not working: Nuxt JS and `beforeRouteEnter`\nTags: javascript, vue.js, vuejs2, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a search form and a results page build with Nuxt JS. I am attempting to redirect the results page `pages/results/index.vue` back to the search page `pages/search/index.vue` if the form returns errors.\n\nI am attempting to use In-Component Guards per the Vue documentation\n\nAccording to the docs:\n\n However, you can access the instance by passing a callback to next. The callback will be called when the navigation is confirmed, and the component instance will be passed to the callback as the argument:\n\n```\nbeforeRouteEnter (to, from, next) {\n next(vm => {\n // access to component instance via `vm`\n })\n}\n```\n\n```\n// version info\n\n├─┬ nuxt@2.10.1\n│ ├─┬ @nuxt/builder@2.10.1\n│ │ └─┬ @nuxt/vue-app@2.10.1\n│ │ └── vue@2.6.10 deduped\n│ └─┬ @nuxt/core@2.10.1\n│ └─┬ @nuxt/vue-renderer@2.10.1\n│ └── vue@2.6.10 deduped\n└─┬ vue-glide-js@1.3.12\n └── vue@2.6.10\n```\n\nMy main issue is that the callback in the `next()` function in the navigation guard does not seem to work to re-route the page.\n\n(the *from* page)\n\n```\n// page/search/index.vue\n\n ...\n \n Show Results\n \n ...\n\nexport default {\n ...\n methods: {\n doSearch () {\n ... // validates search fields and adds content to store\n }\n },\n ...\n}\n\n```\n\nThe above works fine, where `doSearch` validates the form and adds the results (along with any errors) to the store.\n\nBut then in the following...\n\n(the *to* page)\n\n```\n// pages/results/index.vue\n\nexport default {\n ...\n beforeRouteEnter (to, from, next) {\n next((vm) => {\n console.log(vm.validateRoute()) // works: '/search'\n vm.validateRoute() // does not work: does nothing\n })\n },\n ...\n computed: {\n errors () {\n return this.$store.state.errors\n }\n },\n ...\n async fetch ({ store, params }) {\n await store.dispatch('searchresults/GET_RESULTS')\n },\n ...\n methods: {\n validateRoute () {\n let route = true\n if (this.errors.length > 0) {\n route = '/search'\n }\n console.log(this.erros.length) // works: 7\n console.log(route) // works: '/search'\n return route\n }\n },\n ...\n}\n\n```\n\nThe callback in `beforeRouteEnter` does not appear to be evaluated and does not cause the route to change. Note the logging shows the callback is firing and returning the proper value(s).\n\nIf I explicitly define the route, without using a callback function, it works:\n\n```\n// pages/results/index.vue\n\nexport default {\n ...\n beforeRouteEnter (to, from, next) {\n next('/search') // works: re-routes to '/search' every time\n },\n ...\n}\n\n```\n\nI tried several iterations of the `next(callback)` with limited success...\n\n```\nnext(() => { return false }) // does not work\n```\n\n```\nnext(function () { return false }) // does not work\n```\n\nBut only explicit declarations work...\n\n```\nnext({ path: false }) // works: prevents route change\n```\n\n```\nnext({ path: '/search' }) // works: changes route to '/search'\n```\n\nI'm at a total loss; is this a bug, or am I missing something?\n\n**Addendum**\n\nI previously tried using middleware as mentioned in the Nuxt documentation here. However this resulted in an endless loop, as discussed in this blog post.\n\n```\n// middleware/validate.js\n\nexport default function ({ store, redirect }) {\n console.log('middleware: validate') // 'middleware: validate'\n if (store.state.errors.length > 0) {\n return redirect('/search') // ...endless loop\n }\n return true // otherwise this works\n}\n\n// nuxt.config.js\n\nexport default {\n ...\n router: {\n middleware: \"validate\"\n },\n ...\n}\n```\n\n**Fixed**\n\nAs pointed out by @ifaruki, placing the middleware call inside the page component fixes the endless loop issue:\n\n Next step is to add your middleware to your page pages/results/index.vue like this:\n\n```\nexport default {\n middleware: 'validate'\n}\n```\n\nI found this at the very end of the docs which appears to be the Nuxt method for Vue JS In-component Guards:\n\n You can add your middleware to a specific layout or page as well:\n\n \n `pages/index.vue` or `layouts/default.vue`\n\n:facepalm:\n\n========================================\n\nCode:\n```text\nbeforeRouteEnter (to, from, next) {\n next(vm => {\n // access to component instance via `vm`\n })\n}\n```\n\n```sh\n// version info\n\n├─┬ nuxt@2.10.1\n│ ├─┬ @nuxt/builder@2.10.1\n│ │ └─┬ @nuxt/vue-app@2.10.1\n│ │ └── vue@2.6.10 deduped\n│ └─┬ @nuxt/core@2.10.1\n│ └─┬ @nuxt/vue-renderer@2.10.1\n│ └── vue@2.6.10 deduped\n└─┬ vue-glide-js@1.3.12\n └── vue@2.6.10\n```\n\n```js\n// page/search/index.vue\n\n<template>\n ...\n <nuxt-link to=\"/results\" @click.native=\"doSearch\">\n Show Results\n </nuxt-link>\n ...\n</template>\n\n<script>\nexport default {\n ...\n methods: {\n doSearch () {\n ... // validates search fields and adds content to store\n }\n },\n ...\n}\n</script>\n```\n\n```js\n// pages/results/index.vue\n\n<script>\nexport default {\n ...\n beforeRouteEnter (to, from, next) {\n next((vm) => {\n console.log(vm.validateRoute()) // works: '/search'\n vm.validateRoute() // does not work: does nothing\n })\n },\n ...\n computed: {\n errors () {\n return this.$store.state.errors\n }\n },\n ...\n async fetch ({ store, params }) {\n await store.dispatch('searchresults/GET_RESULTS')\n },\n ...\n methods: {\n validateRoute () {\n let route = true\n if (this.errors.length > 0) {\n route = '/search'\n }\n console.log(this.erros.length) // works: 7\n console.log(route) // works: '/search'\n return route\n }\n },\n ...\n}\n</script>\n```\n\n```js\n// pages/results/index.vue\n\n<script>\nexport default {\n ...\n beforeRouteEnter (to, from, next) {\n next('/search') // works: re-routes to '/search' every time\n },\n ...\n}\n</script>\n```\n\n```js\nnext(() => { return false }) // does not work\n```\n\n```js\nnext(function () { return false }) // does not work\n```\n\n```js\nnext({ path: false }) // works: prevents route change\n```\n\n```js\nnext({ path: '/search' }) // works: changes route to '/search'\n```\n\n```js\n// middleware/validate.js\n\nexport default function ({ store, redirect }) {\n console.log('middleware: validate') // 'middleware: validate'\n if (store.state.errors.length > 0) {\n return redirect('/search') // ...endless loop\n }\n return true // otherwise this works\n}\n\n// nuxt.config.js\n\nexport default {\n ...\n router: {\n middleware: \"validate\"\n },\n ...\n}\n```\n\n```text\nexport default {\n middleware: 'validate'\n}\n```\n\n```text\npages/results/index.vue\n```\n\n```text\npages/search/index.vue\n```\n\n```text\nnext()\n```\n\n```text\ndoSearch\n```\n\n```text\nbeforeRouteEnter\n```\n\n```text\nnext(callback)\n```\n\n```text\npages/index.vue\n```\n\n```text\nlayouts/default.vue\n```\n\n```text\nexport default function ({ store, redirect }) {\n if (store.state.errors.length > 0) {\n return redirect('/search')\n }\n}\n```\n\n```text\nexport default {\n middleware: 'validate'\n}\n```\n\n```text\nmiddleware\n```\n\n```text\nmiddleware\n```\n\n```text\nvalidate.js\n```\n\n```text\nvalidate.js\n```\n\n```text\npages/results/index.vue\n```\n\n```text\nstore.state.errors\n```\n\n```text\n/search\n```\n\n========================================\n\nComments:\n- Did you tried doing`return vm.validateRoute()` instead of `vm.validateRoute()`? I mean inside the callback `next((vm) => { // Here })`.\n- thanks @ifaruki - I originally missed the part in the Nuxt docs about adding the middleware directly to the page component. Adding globally resulted in an endless redirect loop. I should have mentioned that I already reviewed the Nuxt docs and the endless loop results, and have updated the question accordingly.\n- I also would like to add here that `redirect(false)` does not work but `redirect({ path: false })` does.","metadata":{"transformedAt":"2026-08-18T18:33:07.872Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":28,"totalLines":416,"estimatedTokens":1945}}500{"id":"stack-69300837","source":"stackoverflow","questionId":69300837,"title":"How to make Nuxt.js SSR with partially static pre-rendering pages","tags":["vue.js","nuxt.js"],"text":"Title: How to make Nuxt.js SSR with partially static pre-rendering pages\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nThere are a lot of information either on Nuxt SSR, or going full static, but I can't find any guide how to build a hybrid SSR with static pages together.\n\nI'm building a website with Nuxt SSR, and I want to pre-render all product pages statically from a 10MB JSON file.\n\nI found an archived thread on Reddit, mentioned it's possible to create a middleware with the routes to be statically generated. I don't know how to achieve that, and hope I can get some help.\n\n========================================\n\nCode:\n```text\ntarget: 'server'\n```\n\n```text\nnuxt build\n```\n\n```text\nnuxt generate --no-build\n```\n\n```text\nnuxt start\n```\n\n========================================\n\nComments:\n- Ah, nice... this helps a lot. It's like building 2 separate apps with one code base. When it said \"something better coming out very soon\", what does that mean? Is it Nuxt 3 will have a proper solution without separate build + generate?\n- @samchuang yep, you'll get probably a few new rendering modes!\n- Will this still work for Nuxt 3? I'm facing the same issue. `nuxt build` seems to ignore the `prerender` route rules (contra the docs), while `nuxt generate` gives me ONLY the prerendered routes (as documented).\n- It's been a year, but maybe someone finds this useful: Nuxt 3 introduced the hybrid render mode: nuxt.com/docs/guide/concepts/rendering#hybrid-rendering\n- @madc that answer was for Nuxt2 anyway, Nuxt3 got quite more advanced renderings indeed.","metadata":{"transformedAt":"2026-08-18T18:33:07.872Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":38,"estimatedTokens":393}}501{"id":"stack-56547002","source":"stackoverflow","questionId":56547002,"title":"Nuxtjs handler.call is not a function","tags":["javascript","vue.js","components","nuxt.js"],"text":"Title: Nuxtjs handler.call is not a function\nTags: javascript, vue.js, components, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nbeen banging my head once more.\n\nI'm surprised I haven't seen a similar question here on SOF, but it's really weird.\nThis code WAS working, but I moved into a standalone component to be used on multiple pages.\nThis is the error I'm getting when I go to the page:\n\n`handler.call is not a function`\n\nI know for a fact it is this component because if I remove the component from the page, there is no error and runs fine. The component calls no functions and has no functions in the script. I have no idea what is going on.\n\nand in the console log, there isn't much help either:\n\n```\nTypeError: \"handler.call is not a function\"\n NuxtJS 21\n\n invokeWithErrorHandling\n\n callHook\n\n insert\n\n invokeInsertHook\n\n patch\n\n _update\n\n updateComponent\n\n get\n\n Watcher\n\n mountComponent\n\n $mount\n\n mount\n\n _callee5$\n\n tryCatch\n\n invoke\n\n method\n\n asyncGeneratorStep\n\n _next\n\n run\n\n notify\n\n flush\n```\n\nThis is the very simple component source code:\n\n```\n\n \n Edit \n \n \n\n### {{card.name}}\n\n \n\n### •••• •••• •••• {{card.last4}}\n\n Exp. {{card.expiration}}\n\n \n \n \n Your saved payment methods will display here once you send your first card!\n \n\n \n 0)\" href=\"/add-card\" class='action'> + Add New Card \n \n\nexport default {\n data : function(){\n return {\n cards : [\n {\n id: 1,\n name: \"Lisa Smith\",\n last4: \"4231\",\n expiration: \"12/2022\"\n },\n {\n id: 2,\n name: \"John Smith\",\n last4: \"1234\",\n expiration: \"11/2023\"\n },\n ],\n };\n },\n props : {\n can_add : {\n default : true,\n type: Boolean,\n },\n can_edit : {\n default : true,\n type: Boolean,\n },\n },\n mounted : {\n // fetch cards\n },\n}\n\n```\n\nand this is how I'm importing the component:\n\n```\n\n \n \n\n### My Credit Cards\n\n \n \n\nimport mycards from '~/components/my_cards.vue';\nexport default {\n data : function(){\n return {\n test : 1,\n };\n },\n components : {\n mycards,\n },\n}\n\n```\n\n========================================\n\nCode:\n```text\nTypeError: \"handler.call is not a function\"\n NuxtJS 21\n\n invokeWithErrorHandling\n\n callHook\n\n insert\n\n invokeInsertHook\n\n patch\n\n _update\n\n updateComponent\n\n get\n\n Watcher\n\n mountComponent\n\n $mount\n\n mount\n\n _callee5$\n\n tryCatch\n\n invoke\n\n method\n\n asyncGeneratorStep\n\n _next\n\n run\n\n notify\n\n flush\n```\n\n```html\n<template>\n <div>\n <button v-if=\"can_edit\" class='btn-blue'> Edit </button>\n <div v-for=\"card in cards\" class='my-credit-card' v-bind:key=\"card.id\">\n <h5>{{card.name}}</h5>\n <h5 class='mt-0'>•••• •••• •••• {{card.last4}}</h5>\n <p class='small'>Exp. {{card.expiration}}</p>\n </div>\n <div v-if=\"cards.length == 0\">\n <p class='subtle'>\n Your saved payment methods will display here once you send your first card!\n </p>\n </div>\n <a v-if=\"(can_add && cards.length > 0)\" href=\"/add-card\" class='action'> + Add New Card </a>\n </div>\n</template>\n<script>\nexport default {\n data : function(){\n return {\n cards : [\n {\n id: 1,\n name: \"Lisa Smith\",\n last4: \"4231\",\n expiration: \"12/2022\"\n },\n {\n id: 2,\n name: \"John Smith\",\n last4: \"1234\",\n expiration: \"11/2023\"\n },\n ],\n };\n },\n props : {\n can_add : {\n default : true,\n type: Boolean,\n },\n can_edit : {\n default : true,\n type: Boolean,\n },\n },\n mounted : {\n // fetch cards\n },\n}\n</script>\n```\n\n```html\n<template>\n <section class='container'>\n <h1>My Credit Cards</h1>\n <mycards :can_add=\"true\" :can_edit=\"true\"></mycards>\n </section>\n</template>\n<script>\nimport mycards from '~/components/my_cards.vue';\nexport default {\n data : function(){\n return {\n test : 1,\n };\n },\n components : {\n mycards,\n },\n}\n</script>\n```\n\n```text\nhandler.call is not a function\n```\n\n```js\nmounted : {\n // fetch cards\n},\n```\n\n```js\nmounted () {\n // fetch cards\n},\n```\n\n```text\ncall\n```\n\n========================================\n\nComments:\n- Thank you so much, I can't believe I looked past that, I checked through every line!\n- And quick response!\n- You are a lifesaver. I actually used mounted where am supposed to use methods","metadata":{"transformedAt":"2026-08-18T18:33:07.872Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":305,"estimatedTokens":1132}}502{"id":"stack-73348158","source":"stackoverflow","questionId":73348158,"title":"Nuxt: Is there a way to cache server-side across requests in memory?","tags":["nuxt.js"],"text":"Title: Nuxt: Is there a way to cache server-side across requests in memory?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to make an API request at build-time, and cache that so it's available in-memory for all future SSR requests?\n\nMy use case is that I have data needed to render server-side (for SEO reasons), but it's stored in a database.\n\nI don't want to make this API request for every SSR request.\n\nIdeally:\n\n- Make API request once at build-time\n\n- Access or Commit this data to Vuex\n\n- Not have to request this at each SSR\n\n- Refresh the data once every 24 hours\n\nI've looked into a few SO answers, and all seem to point to Redis-based cache. Is there no way to do this in-memory.\n\nFor example, I use `nuxtServerInit`:\n\n```\nasync nuxtServerInit({ dispatch, commit }, context: Context) {\n // check if already in memory?\n if (somehowInMemory) {\n commit(cache)\n } else {\n const serverDataJson = await dispatch(\"getServerData\");\n // store this json in memory?\n cache = serverDataJson;\n commit(cache);\n }\n}\n```\n\n========================================\n\nTop Answer:\nNuxt2 provides Static Site Generation. Nuxt3 right now has this future experimental.\n\nAll you need to do is to set your nuxt.config.ts file a variable:\n\n```\nexport default {\n target: 'static' // default is 'server'\n}\n```\n\nTo generate all pages you want. You need to make one page/component where you make a request to get all links you need to generate. Create \"for\" loop in template for them with `` tag. Nuxt in build time will know it has a many `NuxtLinks` to generate as static sites.\n\nApplication will keep SPA as soon it hit client browser, so you still need to have database open. To exclude pages from generation, you have `generate.exclude` property.\n\nYou can find more information about this in Nuxt2 documentation\n\nFiles will be saved on server Hard Drive, not a RAM memory. I'm pretty sure you just want to avoid unnecessary API calls to your database, so this detail should not be an issue.\n\nNuxt team not provide any tools to repeat this process every 24h. But I'm pretty sure you can find any solution to this instead of by your self generate static sites every day.\n\n========================================\n\nCode:\n```js\nasync nuxtServerInit({ dispatch, commit }, context: Context) {\n // check if already in memory?\n if (somehowInMemory) {\n commit(cache)\n } else {\n const serverDataJson = await dispatch(\"getServerData\");\n // store this json in memory?\n cache = serverDataJson;\n commit(cache);\n }\n}\n```\n\n```text\nnuxtServerInit\n```\n\n```js\nimport fs from \"fs\";\nconst getCachedApiRequests: Module<Options> = async function () {\n const data = await getData();\n fs.writeFileSync(\"./data.json\", JSON.stringify(data), \"utf8\");\n}\n\n\nconst config: NuxtConfig = {\n buildModules: [\n async () => {\n await getCachedApiRequests();\n }\n ]\n}\n```\n\n```js\nimport data from \"./data.json\";\n\nexport async function nuxtServerInit({ dispatch, commit }, context) {\n commit('setData', data);\n}\n```\n\n```js\nexport default {\n target: 'static' // default is 'server'\n}\n```\n\n```text\n<NuxtLink>\n```\n\n```text\nNuxtLinks\n```\n\n```text\ngenerate.exclude\n```\n\n========================================\n\nComments:\n- thanks! there are a ton of pages. How would this know all the `asyncData` to pull for each page (different data than my question)\n- @d-_-b Edited how you can generate for example thousands of blog posts. You need just create a page where you get links to those pages and print them in your template using `` tag.\n- Don't use `writefileSync` especially if you are in an async function as it will block the main thread, use the async variant. And consider giving an explanation of the code","metadata":{"transformedAt":"2026-08-18T18:33:07.872Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":132,"estimatedTokens":935}}503{"id":"stack-56435419","source":"stackoverflow","questionId":56435419,"title":"Nuxt production mode loading resources late","tags":["vue.js","webpack","vuetify.js","nuxt.js"],"text":"Title: Nuxt production mode loading resources late\nTags: vue.js, webpack, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am currently running a nuxt app that works fine in development mode. However when I switch to production mode, you can see that some of the css gets deferred to load later. I'm pretty sure this is some of the vuetify css. I say some because some of the classes do exist already.\n\nYou can see what I mean by refreshing this page (make sure to disable cache).\n\nIt seems like there's some sort of nuxt/webpack config that I'm missing to disable this but I'm not sure what it is.\n\nEdit: The staging site is down sometimes, so here's what's happening in gif form, you can see that certain critical css loads later.\nhttps://i.sstatic.net/kez2A.gif\n\nEdit #2: Minimal repro added here https://github.com/amritk/vuetify-nuxt-repro\n\nEdit #3: So @Sabee solved my minimal repro but that didn't solve my original problem. As you can see here, there are a few style blocks that are added on the client but are not there on the server. How do I ensure these styles are loaded on the server?\n\nServer:\n\nhttps://i.sstatic.net/XfEuy.png\n\nClient: \n\n[\n\nEdit#3: Specifically its the v-layout styles loading late. Is there any way to pre-load this css on the server?\n\n========================================\n\nTop Answer:\nI created a pull request to your repo and uploaded the code to codesandbox. I think you have a vuetify syntax problem , I recommend to you use vuetify default app layout markup, your code must look like this :\n\n**default.vue layout**\n\n```\n\nv-app\n v-toolbar(app color=\"primary\")\n\n v-toolbar-title.white--text SiteLogo\n v-spacer\n v-toolbar-items\n v-btn(flat dark to=\"/\" nuxt) home\n v-btn(flat dark to=\"/inspire\" nuxt) Inspiration\n v-btn(flat dark) about \n v-content\n nuxt\n\n```\n\n**and the index.vue**\n\n```\n\nv-container\n v-layout(row wrap)\n v-flex(xs12 sm6 offset-sm3)\n v-card\n v-img(src=\"https://cdn.vuetifyjs.com/images/cards/desert.jpg\" aspect-ratio=\"2.75\")\n v-card-title(primary-title)\n div\n h3(class=\"headline mb-0\") Kangaroo Valley Safari\n div {{ card_text }}\n v-card-actions\n v-btn(flat color=\"primary\") \n v-btn(flat color=\"primary\") Explore\n v-flex(pt-4) \n div PLACEHOLDDDDDDDDDDDEEEEEEEEEEEEERRRRRRRRRRRR\n v-btn(to=\"/inspire\" nuxt) inspuration\n\n export default {\n data () {\n return {\n card_text: 'Lorem ipsum dolor sit amet, brute iriure accusata ne mea. Eos suavitate referrentur ad, te duo agam libris qualisque, utroque quaestio accommodare no qui. Et percipit laboramus usu, no invidunt verterem nominati mel. Dolorem ancillae an mei, ut putant invenire splendide mel, ea nec propriae adipisci. Ignota salutandi accusamus in sed, et per malis fuisset, qui id ludus appareat.'\n }\n }\n }\n\n```\n\nThe second you dont need to write vuetify loader use the default. (if you need configure it)\nAnd add `ssr:false` to the vuetify style globaly lodading in`nuxt.config.js`, the better way is remove the vuetify style loading in `nuxt.config.js` do it in vuetify plugin.\n\n**Vuetify plugin**\n\n```\nimport Vue from 'vue'\nimport Vuetify from 'vuetify/lib'\n\nVue.use(Vuetify, {\n theme: {\n // HC Green\n primary: {\n lighten3: '#009546', // hc-light-green\n base: '#008940' // hc-green\n },\n // Blue\n accent: {\n lighten1: '#23BFFF', // light-blue\n base: '#0279D7', // medium-blue\n darken3: '#0D47A1' // dark-blue, darker-blue\n },\n // Grey\n secondary: {\n lighten5: '#FFFFFF', // white\n lighten4: '#EFEFEF', // lighter-grey, dark-white\n lighten3: '#DFDFDF', // light-medium-grey, light-grey\n base: '#9F9F9F', // medium-grey\n darken2: '#777777', // pastel-grey\n darken3: '#3E3E3E', // darker-grey, charcoal-grey, light-black, dark-medium-grey, dark-grey\n darken5: '#000000' // black\n },\n // Blue\n info: {\n base: '#0279D7' // medium-blue\n },\n // Orange/Yellow\n warning: {\n lighten3: '#fad53e', // light-orange aka yellow\n base: '#ff8800', // from https://www.google.com/search?q=css+warning+color\n darken3: '#e65100' // dark-orange\n },\n // Red\n error: {\n lighten1: '#ff5252', // light-red\n base: '#B71C1C' // medium-red\n },\n // Green\n success: {\n lighten3: '#4CAf50', // light-green\n base: '#28a745', // bootstrap green https://getbootstrap.com/docs/4.3/getting-started/theming/\n darken3: '#00592A' // dark-green\n }\n }\n})\n```\n\n**nuxt.config.js**\n\n```\nimport Sass from 'sass'\nimport dotenv from 'dotenv'\nimport vuetifyLoader from './src/plugins/vuetify-loader'\ndotenv.config()\n\nconst config = {\n mode: 'universal',\n debug: !(process.env.NODE_ENV === 'production'),\n\n // Loading bar color\n loading: {\n color: '#fff'\n },\n\n // Global css\n css: [{ src: '~/assets/style/vuetify.styl', lang: 'styl',ssr:false }],\n\n // Change src directory\n srcDir: 'src/',\n // Plugins\n plugins: [\n { src: '@/plugins/vuetify' }\n ],\n\n // Nuxt.js modules\n modules: [\n '@nuxtjs/axios',\n '@nuxtjs/dotenv',\n ['cookie-universal-nuxt', { alias: 'nuxtCookies' }]\n ],\n\n // Babel\n babel: {\n presets: ['@babel/preset-env'],\n plugins: [\n '@babel/plugin-transform-modules-commonjs',\n 'dynamic-import-node',\n '@babel/plugin-syntax-dynamic-import',\n [\n 'transform-runtime',\n {\n polyfill: false\n }\n ]\n ]\n },\n\n // Build Config\n build: {\n filenames: {\n app: ({ isDev }) => isDev ? '[name].js' : '[name]-[hash].js',\n chunk: ({ isDev }) => isDev ? '[name].js' : '[name]-[hash].js'\n },\n\n // Extend webpack config\n extend: (config, ctx) => {\n\n config.devtool = ctx.isClient ? 'eval-source-map' : 'inline-source-map'\n },\n\n loaders: {\n sass: {\n implementation: Sass\n }\n },\n\n // Vuetify Loader - To auto load your components\n transpile: [/^vuetify/],\n plugins: [ vuetifyLoader]\n }\n}\n\nexport default config\n```\n\n*If you have any questions please contact to me*\n\n========================================\n\nCode:\n```js\nimport Vue from 'vue'\nimport Vuetify, { VLayout } from 'vuetify/lib'\n\nVue.use(Vuetify, {\n options: {\n .\n .\n .\n },\n theme: {\n .\n .\n .\n },\n components: {\n VLayout\n }\n})\n```\n\n```text\n<template lang=\"pug\">\nv-app\n v-toolbar(app color=\"primary\")\n\n v-toolbar-title.white--text SiteLogo\n v-spacer\n v-toolbar-items\n v-btn(flat dark to=\"/\" nuxt) home\n v-btn(flat dark to=\"/inspire\" nuxt) Inspiration\n v-btn(flat dark) about \n v-content\n nuxt\n</template>\n```\n\n```text\n<template lang=\"pug\">\nv-container\n v-layout(row wrap)\n v-flex(xs12 sm6 offset-sm3)\n v-card\n v-img(src=\"https://cdn.vuetifyjs.com/images/cards/desert.jpg\" aspect-ratio=\"2.75\")\n v-card-title(primary-title)\n div\n h3(class=\"headline mb-0\") Kangaroo Valley Safari\n div {{ card_text }}\n v-card-actions\n v-btn(flat color=\"primary\") Share\n v-btn(flat color=\"primary\") Explore\n v-flex(pt-4) \n div PLACEHOLDDDDDDDDDDDEEEEEEEEEEEEERRRRRRRRRRRR\n v-btn(to=\"/inspire\" nuxt) inspuration\n</template>\n<script>\n export default {\n data () {\n return {\n card_text: 'Lorem ipsum dolor sit amet, brute iriure accusata ne mea. Eos suavitate referrentur ad, te duo agam libris qualisque, utroque quaestio accommodare no qui. Et percipit laboramus usu, no invidunt verterem nominati mel. Dolorem ancillae an mei, ut putant invenire splendide mel, ea nec propriae adipisci. Ignota salutandi accusamus in sed, et per malis fuisset, qui id ludus appareat.'\n }\n }\n }\n</script>\n```\n\n```text\nimport Vue from 'vue'\nimport Vuetify from 'vuetify/lib'\n\n\nVue.use(Vuetify, {\n theme: {\n // HC Green\n primary: {\n lighten3: '#009546', // hc-light-green\n base: '#008940' // hc-green\n },\n // Blue\n accent: {\n lighten1: '#23BFFF', // light-blue\n base: '#0279D7', // medium-blue\n darken3: '#0D47A1' // dark-blue, darker-blue\n },\n // Grey\n secondary: {\n lighten5: '#FFFFFF', // white\n lighten4: '#EFEFEF', // lighter-grey, dark-white\n lighten3: '#DFDFDF', // light-medium-grey, light-grey\n base: '#9F9F9F', // medium-grey\n darken2: '#777777', // pastel-grey\n darken3: '#3E3E3E', // darker-grey, charcoal-grey, light-black, dark-medium-grey, dark-grey\n darken5: '#000000' // black\n },\n // Blue\n info: {\n base: '#0279D7' // medium-blue\n },\n // Orange/Yellow\n warning: {\n lighten3: '#fad53e', // light-orange aka yellow\n base: '#ff8800', // from https://www.google.com/search?q=css+warning+color\n darken3: '#e65100' // dark-orange\n },\n // Red\n error: {\n lighten1: '#ff5252', // light-red\n base: '#B71C1C' // medium-red\n },\n // Green\n success: {\n lighten3: '#4CAf50', // light-green\n base: '#28a745', // bootstrap green https://getbootstrap.com/docs/4.3/getting-started/theming/\n darken3: '#00592A' // dark-green\n }\n }\n})\n```\n\n```text\nimport Sass from 'sass'\nimport dotenv from 'dotenv'\nimport vuetifyLoader from './src/plugins/vuetify-loader'\ndotenv.config()\n\nconst config = {\n mode: 'universal',\n debug: !(process.env.NODE_ENV === 'production'),\n\n // Loading bar color\n loading: {\n color: '#fff'\n },\n\n // Global css\n css: [{ src: '~/assets/style/vuetify.styl', lang: 'styl',ssr:false }],\n\n // Change src directory\n srcDir: 'src/',\n // Plugins\n plugins: [\n { src: '@/plugins/vuetify' }\n ],\n\n // Nuxt.js modules\n modules: [\n '@nuxtjs/axios',\n '@nuxtjs/dotenv',\n ['cookie-universal-nuxt', { alias: 'nuxtCookies' }]\n ],\n\n // Babel\n babel: {\n presets: ['@babel/preset-env'],\n plugins: [\n '@babel/plugin-transform-modules-commonjs',\n 'dynamic-import-node',\n '@babel/plugin-syntax-dynamic-import',\n [\n 'transform-runtime',\n {\n polyfill: false\n }\n ]\n ]\n },\n\n // Build Config\n build: {\n filenames: {\n app: ({ isDev }) => isDev ? '[name].js' : '[name]-[hash].js',\n chunk: ({ isDev }) => isDev ? '[name].js' : '[name]-[hash].js'\n },\n\n // Extend webpack config\n extend: (config, ctx) => {\n\n config.devtool = ctx.isClient ? 'eval-source-map' : 'inline-source-map'\n },\n\n loaders: {\n sass: {\n implementation: Sass\n }\n },\n\n // Vuetify Loader - To auto load your components\n transpile: [/^vuetify/],\n plugins: [ vuetifyLoader]\n }\n}\n\nexport default config\n```\n\n```text\nssr:false\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- It's specific to nuxt and vuetify. I've been using both in production for quite some time and I've spent countless hours on this. The only reasonable band-aid is to use `[v-cloak]` although this shouldn't happen with SSR.\n- @Ohgodwhy there's gotta be some config somewhere that allows you to fix this, I mean it works fine in development. It's definitely something that's supposed to be \"optimizing\" by deferring the loading of certain scripts. We just gotta find out where that config is and disable it.\n- It works fine in development because you're using `hot module reloading`. The reason why production doesn't have a 1:1 parity is because you're no longer using `hmr`.\n- hmr nothing to do with css flashing. Its hard to say what happens without a minimal repro\n- Alright i have added a minimnal repro github.com/amritk/vuetify-nuxt-repro\n- Alright i'll check it out. But I do need to use vuetify loader, since I'm using it to load my own components as well,\n- Alright, then use your own loader. Updated please check it out.\n- What does ssr: false do here on the css? On the JS it means load on the client only, but in this case, I want the CSS loaded on the server\n- ssr (true or false) means turning on or off Server Side Rendering with Nuxt.js\n- you don't really need ssr on your css styles, because it does not play a role in SEO, but in some cases if you use ssr with styles it can load slower\n- Actually I think css does play a role in seo. Google always said responsive websites get a boost in rankings, does it not get that from css? When I was doing SSR before switching to nuxt all the styles were loaded on the server and performance was excellent.\n- I'm sorry I didn't express myself well. You're right. SSR is required for the structure of the page to generate html from js code that search engines can interpret. css styles is definitely loaded without change.\n- That fixed my repro but didn't actually fix my original problem. Seems as if some vuetify styles are loading on the client but not on the server. I have applied all these fixes to my actual production code and it didn't help\n- actually what the styles you are missing?\n- I updated my question with the screenshots, they are from vuetify\n- You can also add the VLayout styles into default.vue","metadata":{"transformedAt":"2026-08-18T18:33:07.872Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":447,"estimatedTokens":3301}}504{"id":"stack-51396360","source":"stackoverflow","questionId":51396360,"title":"How to use Promise.all using Axios Async Await","tags":["javascript","vue.js","promise","nuxt.js"],"text":"Title: How to use Promise.all using Axios Async Await\nTags: javascript, vue.js, promise, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have this Axios Async Await code in Nuxt.js, I am not sure on how and where to put the `Promise.all` here. I am trying to promise the `getThemes()` and `getData()`. Could somebody help me with the `Promise.all` code?\n\nAnd do I have to put the `Promise.all` in the `mounted()`?\n\n```\nmounted() {\n this.getData(this.$route.params.id);\n this.getThemes();\n },\n\n methods: {\n async getThemes() {\n this.loading = true;\n await axios.get(`${process.env.API_URL}/v1/communication/email-themes`, {}).then((response) => {\n this.theme = response.data.data;\n this.selected = this.theme.filter(t => this.themeId === t.id)[0].id;\n this.loading = false;\n }).catch((error) => {\n this.loading = false;\n this.errormsg = error.response.data.message;\n });\n },\n\n async getData(id) {\n this.loading = true;\n await axios\n .get(`${process.env.API_URL}/v1/communication/email-templates/${id}`)\n .then(({\n data\n }) => {\n this.templateName = data.data.name;\n this.templateCode = data.data.content;\n this.themeId = data.data.theme_id;\n this.loading = false;\n }).catch((error) => {\n this.loading = false;\n this.errormsg = error.response.data.message;\n });\n },\n\n async patchData(id) {\n await axios.put(`${process.env.API_URL}/v1/communication/email-templates/${this.$route.params.id}`, {\n name: this.templateName,\n content: this.templateCode,\n theme_id: this.selected\n }).then((response) => {\n this.results = response.data;\n this.loading = false;\n }).catch((error) => {\n this.loading = false;\n this.errormsg = error.response.data.message;\n });\n }\n }\n```\n\n========================================\n\nTop Answer:\n```\nhere example how to wait axios all fetch\nlet url1=\"https://stackoverflow.com\";\nlet url2=\"https://stackoverflow.com/questions\";\nlet request1=axios.get(url1);\nlet request2=axios.get(url2);\nlet [answer1,answer2]=await axios.all([request1,request2]);\nconsole.log(answer1.data);\nconsole.log(answer2.data);\n```\n\n========================================\n\nCode:\n```text\nmounted() {\n this.getData(this.$route.params.id);\n this.getThemes();\n },\n\n methods: {\n async getThemes() {\n this.loading = true;\n await axios.get(`${process.env.API_URL}/v1/communication/email-themes`, {}).then((response) => {\n this.theme = response.data.data;\n this.selected = this.theme.filter(t => this.themeId === t.id)[0].id;\n this.loading = false;\n }).catch((error) => {\n this.loading = false;\n this.errormsg = error.response.data.message;\n });\n },\n\n async getData(id) {\n this.loading = true;\n await axios\n .get(`${process.env.API_URL}/v1/communication/email-templates/${id}`)\n .then(({\n data\n }) => {\n this.templateName = data.data.name;\n this.templateCode = data.data.content;\n this.themeId = data.data.theme_id;\n this.loading = false;\n }).catch((error) => {\n this.loading = false;\n this.errormsg = error.response.data.message;\n });\n },\n\n async patchData(id) {\n await axios.put(`${process.env.API_URL}/v1/communication/email-templates/${this.$route.params.id}`, {\n name: this.templateName,\n content: this.templateCode,\n theme_id: this.selected\n }).then((response) => {\n this.results = response.data;\n this.loading = false;\n }).catch((error) => {\n this.loading = false;\n this.errormsg = error.response.data.message;\n });\n }\n }\n```\n\n```text\nPromise.all\n```\n\n```text\ngetThemes()\n```\n\n```text\ngetData()\n```\n\n```text\nPromise.all\n```\n\n```text\nPromise.all\n```\n\n```text\nmounted()\n```\n\n```text\n{\n mounted() {\n this.loading = true;\n Promise.all([this.getThemes(), this.getData(this.$route.params.id)])\n .then(values => {\n //first return value\n this.theme = values[0];\n this.selected = this.theme.filter(t => this.themeId === t.id)[0].id;\n //second return value\n this.templateName = values[1].name;\n this.templateCode = values[1].content;\n this.themeId = values[1].theme_id;\n\n this.loading = false;\n })\n .catch(error => {\n this.errormsg = error.response.data.message;\n this.loading = false;\n });\n },\n methods: {\n async getThemes() {\n const response = await axios.get(\n `${process.env.API_URL}/v1/communication/email-themes`,\n {}\n );\n return response.data.data;\n },\n async getData(id) {\n const response = await axios.get(\n `${process.env.API_URL}/v1/communication/email-templates/${id}`\n );\n\n return response.data.data;\n }\n }\n};\n```\n\n```text\nPromise.all\n```\n\n```text\nmounted() {\n this.loadData();\n },\n methods: {\n async loadData() {\n this.loading = true\n try {\n await Promise.all([this.getThemes(), this.getData(this.$route.params.id)])\n } catch (error) {\n this.errormsg = error.message;\n } finally {\n this.loading = false\n }\n }\n getThemes() {\n return axios.get(`${process.env.API_URL}/v1/communication/email-themes`, {\n }).then((response) => {\n this.theme = response.data.data;\n this.selected = this.theme.filter(t => this.themeId === t.id)[0].id;\n })\n },\n\n getData(id) {\n return axios\n .get(`${process.env.API_URL}/v1/communication/email-templates/${id}`)\n .then(({ data }) => {\n this.templateName = data.data.name;\n this.templateCode = data.data.content;\n this.themeId = data.data.theme_id;\n })\n },\n }\n```\n\n```text\ngetThemes\n```\n\n```text\ngetData\n```\n\n```text\nhere example how to wait axios all fetch\nlet url1=\"https://stackoverflow.com\";\nlet url2=\"https://stackoverflow.com/questions\";\nlet request1=axios.get(url1);\nlet request2=axios.get(url2);\nlet [answer1,answer2]=await axios.all([request1,request2]);\nconsole.log(answer1.data);\nconsole.log(answer2.data);\n```\n\n========================================\n\nComments:\n- I think you are asking more than one thing here, my answer solves what you are actually asking, but maybe you should avoid setting `this` on `getThemes()` and `getData()`, instead, just use the return value of your promises inside `mounted()`. Also, you are using `await` poorly, you shouldn't be using `then` nor `catch`but a `try catch` block.\n- Another problem in your code is that if both `getThemes()' and`getData()` fail, one of them will replace the `errormsg` from the other. You can catch both errors and concatenate them once you use `Promise.all`.\n- Hi, thanks for replying, so do you think I should replace all of the methods? I'm pretty new at this Asnyc Await thing and the code above isn't mine, it was made by my co-worker and I have to fix his code.\n- You can start playing with my code and its mocked async requests, as you can see, there is no `then`. In order to catch errors, you should implement one or more `try catch' blocks.\n- You can also replace `getPromise()` with your axios calls: `getPromise(1)` would become `axios.get(`${process.env.API_URL}/v1/communication/email-the‌​mes`, {})`.\n- You can do `Promise.all([this.getThemes(), this.getData(this.$route.params.id)])`, but what do you then want to do with that promise in `mounted`?\n- Thank you for replying and it seems that is the way to do it, but I have another problem now, there is a console error stating \"Uncaught (in promise) TypeError: Cannot read property 'data' of undefined at _id.vue?e97a:100\" The error was in \"this.errormsg = error.response.data.message;\" inside the async loadData(). Could you help me a bit more?\n- I tried the code and sometimes it works but sometimes it shows the error, just like my previous code.\n- you can put `this.loading = false` in a `then(...)` after `catch(...)` which works similar to `always(...)` in jQuery: `.then( values => { ...}).catch( error => {...}).then( () => { this.loading = false; });`\n- I want to just comment here for anyone looking for the answer, that *this* should really be the accepted answer. Axios has this stuff built in. Unfortunately, the accepted answer reinvents the wheel and results in bad coding practices and bloat.","metadata":{"transformedAt":"2026-08-18T18:33:07.873Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":265,"estimatedTokens":2073}}505{"id":"stack-44126493","source":"stackoverflow","questionId":44126493,"title":"I want to use window.localStorage in Vuex in Nuxt.js","tags":["authentication","jwt","vuejs2","vuex","nuxt.js"],"text":"Title: I want to use window.localStorage in Vuex in Nuxt.js\nTags: authentication, jwt, vuejs2, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI developing nuxt.js app. And point is login & logout.\n\nWe will develop a login to the JWT system.\n\nYou must remain logged in at vuex.\n\nHowever, when I refresh the page, vuex is initialized.\n\nI've read git vuex-persistedstate , but it's hard to understand just how to initialize and set it.\n\nWhat is the best way to develop a login system in nuxt.js?\n\nThanks.\n\n========================================\n\nTop Answer:\nI have used vuex-persist package instead, very easy to get it up and running. This works for SSR too.\n\n\r\n\r\n\n```\nimport Vue from 'vue'\r\nimport Vuex from 'vuex'\r\nimport VuexPersist from 'vuex-persist'\r\nimport actions from './actions'\r\nimport mutations from './mutations'\r\nimport getters from './getters'\r\n\r\nVue.use(Vuex)\r\nlet vuexLocalStorage = null;\r\n\r\nif (process.browser) {\r\n\r\n vuexLocalStorage = new VuexPersist({\r\n key: 'vuex', // The key to store the state on in the storage provider.\r\n storage: window.localStorage, // or window.sessionStorage or localForage\r\n })\r\n}\r\n\r\nexport function createStore() {\r\n return new Vuex.Store({\r\n state: {\r\n \r\n },\r\n actions,\r\n mutations,\r\n getters,\r\n plugins: process.browser ? [vuexLocalStorage.plugin] : []\r\n })\r\n}\n```\n\n\r\n\r\n\r\n\nJust make sure to condition everything to just run in the browser\n\n========================================\n\nCode:\n```js\nimport createPersistedState from \"vuex-persistedstate\";\nimport * as Cookie from \"js-cookie\";\n\nVue.use(Vuex);\n\nexport const store = new Vuex.Store({\n state: {\n user: {\n name: \"john doe\",\n age: \" 16\",\n },\n loggedIn: false,\n hobbies: [\"eating\", \"partying\"],\n },\n plugins: [\n createPersistedState({\n paths: [\"user\", \"loggedIn\"],\n getState: (key) => Cookie.getJSON(key),\n setState: (key, state) =>\n Cookie.set(key, state, { expires: 1, secure: false }),\n }),\n ],\n});\n```\n\n```js\nimport createPersistedState from \"vuex-persistedstate\";\nimport * as Cookie from \"js-cookie\";\n\nimport myModule from \"./myModule\";\nimport myAnotherModule from \"./myAnotherModule\";\n\nVue.use(Vuex);\n\nexport const store = new Vuex.Store({\n state: {\n user: {\n name: \"john doe\",\n age: \" 16\",\n },\n loggedIn: false,\n hobbies: [\"eating\", \"partying\"],\n },\n modules: {\n myModule,\n myAnotherModule,\n },\n plugins: [\n createPersistedState({\n paths: [\"user\", \"loggedIn\", \"myModule.<nameOfThePropretyInState>\"],\n getState: (key) => Cookie.getJSON(key),\n setState: (key, state) =>\n Cookie.set(key, state, { expires: 1, secure: false }),\n }),\n ],\n});\n```\n\n```text\ncd\n```\n\n```text\nnpm install --save vuex-persistedstate\n```\n\n```text\nnpm install --save js-cookie\n```\n\n```text\npaths: ['user', 'loggedIn']\n```\n\n```text\nconsole.log(document.cookie\n```\n\n```js\nimport Vue from 'vue'\nimport Vuex from 'vuex'\nimport VuexPersist from 'vuex-persist'\nimport actions from './actions'\nimport mutations from './mutations'\nimport getters from './getters'\n\nVue.use(Vuex)\nlet vuexLocalStorage = null;\n\nif (process.browser) {\n\n vuexLocalStorage = new VuexPersist({\n key: 'vuex', // The key to store the state on in the storage provider.\n storage: window.localStorage, // or window.sessionStorage or localForage\n })\n}\n\nexport function createStore() {\n return new Vuex.Store({\n state: {\n \n },\n actions,\n mutations,\n getters,\n plugins: process.browser ? [vuexLocalStorage.plugin] : []\n })\n}\n```\n\n```js\n//call async ajax request to get UUID\nconst uuidReq = await dispatch('getUUID')\n\nif (uuidReq.hasOwnProperty('meta')) {\n commit('setState', {\n uuid: uuidReq.meta.links.me.meta.id,\n isLogin: true\n })\n\n // calculate expires\n const expDate = new Date()\n expDate.setTime(expDate.getTime() + (state.accExpKey - 0.3) * 1000)\n const expDate2 = new Date()\n expDate2.setTime(expDate.getTime() + 2592000 * 1000)\n\n const options = {\n path: '/',\n expires: expDate\n }\n const options2 = {\n path: '/',\n expires: expDate2\n }\n\n const cookieList = [{\n name: 'g_isLogin',\n value: true,\n opts: options2\n },\n {\n name: 'g_accKey',\n value: state.accKey,\n opts: options\n },\n {\n name: 'g_refKey',\n value: state.refKey,\n opts: options2\n },\n {\n name: 'g_userUUID',\n value: uuidReq.meta.links.me.meta.id,\n opts: options\n }\n ]\n this.$cookies.setAll(cookieList)\n}\n```\n\n```js\nexport default function({ store, route, redirect, app }) {\n const isLogin = app.$cookies.get('g_isLogin') === 'true'\n const accKey = app.$cookies.get('g_accKey') || ''\n const refKey = app.$cookies.get('g_refKey') || ''\n const userUUID = app.$cookies.get('g_userUUID') || ''\n\n // console.warn('authenticated isLogin:', isLogin)\n\n // If the user authenticated\n if (isLogin) {\n store.commit('user/setState', {\n isLogin: isLogin,\n accKey: accKey,\n refKey: refKey,\n uuid: userUUID\n })\n } else {\n return redirect('/?prevURL=' + route.path)\n }\n}\n```\n\n```js\nconst user = {\n namespaced: true,\n state: () => ({\n name: 'geeekfa'\n }),\n mutations: {\n name(state, name) {\n state.name = name;\n },\n },\n getters: {\n name: (state) => {\n return state.name;\n },\n }\n}\nexport default user\n```\n\n```js\n\"dependencies\": {\n ...\n \"cookie\": \"^0.3.1\",\n \"js-cookie\": \"^2.2.1\",\n \"vuex-persistedstate\": \"^4.0.0-beta.3\",\n ...\n }\n```\n\n```js\n// persistedState.js\nimport createPersistedState from 'vuex-persistedstate'\nimport * as Cookies from 'js-cookie'\nimport cookie from 'cookie'\n\nexport default ({ store, req }) => {\n createPersistedState({\n paths: ['user'], // your vuex module name\n storage: {\n\n getItem: (key) => {\n if (process.server) {\n const parsedCookies = cookie.parse(req.headers.cookie)\n return parsedCookies[key]\n } else {\n return Cookies.get(key)\n }\n },\n \n setItem: (key, value) =>\n Cookies.set(key, value, { expires: 365, secure: false }),\n removeItem: key => Cookies.remove(key)\n }\n })(store)\n}\n```\n\n```js\nplugins: [\n ...\n { src: '~/plugins/persistedState.js' }\n ...\n ],\n```\n\n```text\nvuex-persistedstate\n```\n\n```text\nVuex Module\n```\n\n```text\nuser\n```\n\n```text\nrefresh\n```\n\n```text\nroute\n```\n\n```text\npackage.json\n```\n\n```text\npersistedState.js\n```\n\n```text\n~/plugin/persistedState.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nuser\n```\n\n```text\n~/store/index.js\n```\n\n========================================\n\nComments:\n- You can not use window.localStorage in vuex. There is no hope for me here.\n- What is the problem you are facing intializing vuex-persisted state. I can help you with it.\n- @user7814783 first, My purpose is to implement the login function in nuxt.js. Vuex wants to manage login status. I want to manage it from cookies in the jwt way. However, when a page refresh occurs, vuex is initialized and can not remain logged in. Is there an easy way to do this?\n- i have added a descriptive answer on how to setup and use vuex-persisted state, have a look. Any doubts just comment\n- oh... thanks. but, I am still not enough. I started the project with nuxt / koa. What is the best way to develop a login system here?\n- In your response, I start the project with nuxt / koa. Create an index.js file in the store folder. I have applied your code. How can I check the contents stored in cookies afterwards? Document.cookie is invalid.\n- Do you know of any way to get this working with Nuxt specifically? I get a \"window is not defined error\" because of SSR.\n- I have the same issue @MichaelGiovanniPumo. Did you ever solve this?\n- @JonasLomholdt according to the docs of the library, if you call your plugin as `/plugins/persistedState.client.js` it would only be called on the client side. I'm using localstorage so that makes sense, if you are using cookies then check the docs, they have an example for cookies and nuxt too","metadata":{"transformedAt":"2026-08-18T18:33:07.873Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":374,"estimatedTokens":2020}}506{"id":"stack-75668869","source":"stackoverflow","questionId":75668869,"title":"VSCode Auto-Import doesn't work: Cannot find name","tags":["vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: VSCode Auto-Import doesn't work: Cannot find name\nTags: vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI have just upgraded Nuxt 3.1 to 3.2...\n\nhttps://i.sstatic.net/P3n8f.png\n\nHow to make it work properly? (starting server can be successful)\n\n========================================\n\nComments:\n- Try to run `npx nuxi clean` and restart your dev server. Then check that the `.nuxt/types/imports.d.ts` file is created and includes `defineNuxtComponent`.\n- I tried this and also the volar restart, but nothing helped. The imports file is generated properly though...\n- This situation has become increasingly frequent recently, especially when using Nuxt","metadata":{"transformedAt":"2026-08-18T18:33:07.873Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":17,"estimatedTokens":172}}507{"id":"stack-52649258","source":"stackoverflow","questionId":52649258,"title":"Nuxt.js: understanding component","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Nuxt.js: understanding component\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn Nuxt.js, I did this folder structure:\n\n```\n├── parent\n│ ├── child1.vue\n│ └── child2.vue\n├── parent.vue\n```\n\nIn **parent.vue**, I have this:\n\n```\n\n \n \n\n### Parent element\n\n \n \n- \n \n- \n \n \n\n```\n\nIn **child1.vue**:\n\n```\n\n \n \n\n### Child 1\n\n \n\n```\n\nIn **child2.vue**:\n\n```\n\n \n \n\n### Child 2\n\n \n\n```\n\nI launch the server (yarn run dev) and go this URI: `http://localohost:3000/parent` where I see this:\n\n```\nParent element \n - \n -\n```\n\nIf I go to `http://localohost:3000/parent/child1`, I see this:\n\n```\nParent element \n - Child 1\n - Child 1\n```\n\nIf I go to `http://localohost:3000/parent/child2`, I see this:\n\n```\nParent element \n - Child 2\n - Child 2\n```\n\n**Question:**\n\nFrom the documentation, I understand that **child1.vue** and **child2.vue** are children of parent.vue, so I expect to see them list when I visit `http://localhost:3000/parent`, but they were not displayed. Each child is displayed only when I point to its URI. Anyone to explain me this behavior?\n\n========================================\n\nCode:\n```text\n├── parent\n│ ├── child1.vue\n│ └── child2.vue\n├── parent.vue\n```\n\n```text\n<template>\n <div>\n <h3>Parent element</h3>\n <ul>\n <li><nuxt-child/></li>\n <li><nuxt-child/></li>\n </ul>\n </div>\n</template>\n```\n\n```text\n<template>\n <div>\n <h3>Child 1</h3>\n </div>\n</template>\n```\n\n```text\n<template>\n <div>\n <h3>Child 2</h3>\n </div>\n</template>\n```\n\n```text\nParent element \n - \n -\n```\n\n```text\nParent element \n - Child 1\n - Child 1\n```\n\n```text\nParent element \n - Child 2\n - Child 2\n```\n\n```text\nhttp://localohost:3000/parent\n```\n\n```text\nhttp://localohost:3000/parent/child1\n```\n\n```text\nhttp://localohost:3000/parent/child2\n```\n\n```text\nhttp://localhost:3000/parent\n```\n\n```text\n<template>\n <div>\n <h3>Parent element</h3>\n <nuxt-child/>\n </div>\n</template>\n```\n\n```text\n- events\n - christmas\n - easter\n```\n\n```text\n<nuxt-child/>\n```\n\n```text\nevent\n```\n\n```text\nevents/christmas\n```\n\n```text\nevents/easter\n```\n\n```text\nevents/\n```\n\n========================================\n\nComments:\n- I am aware of all what you said, and I would like if you could elaborate on **based on the route** because I feel the real explanation is nearby there. Thank you\n- How can I maintain the nested uri of \"parent/child\" without rendering the parent page contents when I navigate to the child?\n- @JacobKochocki I think that’s more of a Vue Router issue, I don’t think there is a way of doing that","metadata":{"transformedAt":"2026-08-18T18:33:07.873Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":200,"estimatedTokens":661}}508{"id":"stack-64834299","source":"stackoverflow","questionId":64834299,"title":"Show package.json version on NuxtJS application","tags":["version","package.json","nuxt.js"],"text":"Title: Show package.json version on NuxtJS application\nTags: version, package.json, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to use the version number that is configured on `package.json` into my components on NuxtJS application.\n\nCan this be done?\n\n========================================\n\nCode:\n```text\npackage.json\n```\n\n```text\nimport pkg from './package.json'\n```\n\n```text\nexport default {\n ...\n // https://nuxtjs.org/guide/runtime-config\n publicRuntimeConfig: {\n clientVersion: pkg.version,\n }\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n$config.clientVersion\n```\n\n========================================\n\nComments:\n- Somehow this seems like a bad idea...","metadata":{"transformedAt":"2026-08-18T18:33:07.873Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":42,"estimatedTokens":169}}509{"id":"stack-73098182","source":"stackoverflow","questionId":73098182,"title":"Children of NuxtLink rendered twice (hydration error?)","tags":["vue.js","nuxt.js","server-side-rendering","mismatch","hydration"],"text":"Title: Children of NuxtLink rendered twice (hydration error?)\nTags: vue.js, nuxt.js, server-side-rendering, mismatch, hydration\nSource: Stack Overflow\n\nQuestion:\nhttps://i.sstatic.net/TozRd.png\n\nMy hunch is that there is some hydration mismatch where the `FontAwesomeIcon` was not rendered on the server (only the `span`) and then on the client both child nodes of the `NuxtLink` were rendered (the `svg` and the `span`), prompting Nuxt to render the `span` twice.\n\nThe console does not return an error, though.\n\nAny thoughts on how to debug this?\n\nThis is the Vue component:\n\n```\n\n 0\" class=\"col-span-2 flex flex-col\">\n \n \n \n {{ item.title }}\n \n \n \n\nexport default defineComponent({\n props: {\n links: {\n type: Array,\n default: () => [\"instagram\", \"facebook\", \"email\"],\n },\n },\n computed: {\n routes() {\n return [\n {\n name: \"instagram\",\n path: \"https://www.instagram.com/insta.name/\",\n title: \"Instagram\",\n icon: [\"fab\", \"instagram\"],\n },\n {\n name: \"facebook\",\n path: \"https://www.facebook.com/fb.name\",\n title: \"Facebook\",\n icon: [\"fab\", \"facebook\"],\n },\n {\n name: \"email\",\n path: \"mailto:hello@example.com\",\n title: \"Email\",\n icon: [\"fas\", \"envelope\"],\n },\n ].filter((e) => this.links.includes(e.name));\n },\n },\n});\n\n```\n\n========================================\n\nTop Answer:\n**There is a better solution, see my other answer.**\n\nWrap you `` in a `` like so:\n\n```\n...\n\n \n {{ title }}\n\n...\n```\n\nAll credit goes to: https://stackoverflow.com/a/73487636/4862595\n\n========================================\n\nCode:\n```vue\n<template>\n <ul v-if=\"routes.length > 0\" class=\"col-span-2 flex flex-col\">\n <li v-for=\"(item, i) in routes\" :key=\"item.name\">\n <NuxtLink :to=\"item.path\" target=\"_blank\">\n <FontAwesomeIcon :icon=\"item.icon\" class=\"mr-3\" fixed-width />\n <span>{{ item.title }}</span>\n </NuxtLink>\n </li>\n </ul>\n</template>\n\n<script lang=\"ts\">\nexport default defineComponent({\n props: {\n links: {\n type: Array,\n default: () => [\"instagram\", \"facebook\", \"email\"],\n },\n },\n computed: {\n routes() {\n return [\n {\n name: \"instagram\",\n path: \"https://www.instagram.com/insta.name/\",\n title: \"Instagram\",\n icon: [\"fab\", \"instagram\"],\n },\n {\n name: \"facebook\",\n path: \"https://www.facebook.com/fb.name\",\n title: \"Facebook\",\n icon: [\"fab\", \"facebook\"],\n },\n {\n name: \"email\",\n path: \"mailto:hello@example.com\",\n title: \"Email\",\n icon: [\"fas\", \"envelope\"],\n },\n ].filter((e) => this.links.includes(e.name));\n },\n },\n});\n</script>\n```\n\n```text\nFontAwesomeIcon\n```\n\n```text\nspan\n```\n\n```text\nNuxtLink\n```\n\n```text\nsvg\n```\n\n```text\nspan\n```\n\n```text\nspan\n```\n\n```js\n// nuxt.config.ts\n\nexport default defineNuxtConfig({\n build: {\n transpile: [\n '@fortawesome/vue-fontawesome',\n ]\n },\n // ...\n})\n```\n\n```text\n@fortawesome/vue-fontawesome\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n@fortawesome/vue-fontawesome\n```\n\n```text\n...\n<NuxtLink to=\"/path\" target=\"_blank\">\n <span><FontAwesomeIcon :icon=\"icon\" fixed-width /></span>\n <span>{{ title }}</span>\n</NuxtLink>\n...\n```\n\n```text\n<FontAwesomeIcon />\n```\n\n```text\n<span>\n```\n\n========================================\n\nComments:\n- Not sure but apparently the error is only display when you build your project for production, try that one out. Otherwise, double check that your thing is actually as expected on the server side by disabling JS. And be careful with async code.\n- Yes, it's only in production and only with the `` component. This component is not async afaik. Wrapping the children in a `` component tackled the double hydration but it is not a solution because it's beside the point of SSR...\n- Try to compare both the DOM of the element on the server vs on the client. `client-only` is indeed not the best solution but at the same time, if it's an icon it doesn't really matter SEO-wise or anything. Maybe try to look into their specific github issues to see if they have something related, otherwise I can also recommend this solution: stackoverflow.com/a/72055404/8816585 Works great!\n- I have the same problem. How did you solve it?\n- @AlexanderHorner feel free to post a new question to get your issue solved.\n- I have the same issue. Did you find a solution? I have the same issue without errors.\n- I did not yet find a solution other than wrapping the `` in a ``.","metadata":{"transformedAt":"2026-08-18T18:33:07.873Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":206,"estimatedTokens":1111}}510{"id":"stack-71864831","source":"stackoverflow","questionId":71864831,"title":"How to avoid [Vue warn]: Injection \"xxxx\" not found","tags":["typescript","vue.js","nuxt.js","vuejs3"],"text":"Title: How to avoid [Vue warn]: Injection \"xxxx\" not found\nTags: typescript, vue.js, nuxt.js, vuejs3\nSource: Stack Overflow\n\nQuestion:\nI'm using inject/provide pattern in nuxt composition-api.\nFor example, Component A inject the function provided by Component B which is parent of Component A like below.\n\n```\n//Component B \nconst test = () => {}\nprovide('test', test)\n```\n\n```\n//Component A \nconst test = inject('test')\n```\n\nHowever when I want to use Component A without Component B, this warn is shown on console. I understand it's saying but in this case it doesn't need to use ''test'' function. Are there any way to avoid this warning ?\n\n[Vue warn]: Injection \"test\" not found\n\n========================================\n\nCode:\n```js\n//Component B \nconst test = () => {}\nprovide('test', test)\n```\n\n```js\n//Component A \nconst test = inject<Function>('test')\n```\n\n```js\nconst test = inject<Function>('test', () => {})\n```\n\n```text\ninject()\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.873Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":44,"estimatedTokens":237}}511{"id":"stack-48577766","source":"stackoverflow","questionId":48577766,"title":"Nuxt Sites not getting crawled","tags":["seo","nuxt.js"],"text":"Title: Nuxt Sites not getting crawled\nTags: seo, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have made a website using NUXT that needs SEO\n\nWhen I use www.xml-sitemaps.com website to see if it can find all my pages, it only finds the home page, and none of the other routes. When I try other NUXT demo websites it finds them all.\n\nMy `robots.txt` file looks like:\n\n```\nUser-agent: *\nDisallow: /profile/\nSitemap: https://www.example.com/sitemap.xml\n```\n\nI am using `@nuxtjs/sitemap` to generate the `sitemap.xml` that ends up looking something like this:\n\n```\n\n https://www.example.com/about \n https://www.example.com/ \n\n```\n\nAnd if this helps, my `nuxt.config.js` looks like:\n\n```\nmodule.exports = {\n /*\n ** Headers of the page\n */\n head: {\n title: 'Title',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: 'Title' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n mode: 'spa',\n loading: { color: '#3B8070' },\n build: {\n /*\n ** Run ESLint on save\n */\n extend (config, { isDev, isClient }) {\n if (isDev && isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n }\n },\n css: [\n '~/assets/main.css'\n ],\n modules: [\n '@nuxtjs/pwa',\n [\n '@nuxtjs/sitemap', {\n generate: true,\n hostname: 'https://www.example.com',\n exclude: [\n '/profile'\n ]\n }\n ]\n ],\n plugins: [\n '~/plugins/uikit.js',\n '~/plugins/fireauth.js'\n ],\n manifest: {\n name: 'Title',\n lang: 'en'\n },\n router: {\n middleware: 'router-auth'\n },\n vendor: [\n 'firebase',\n 'uikit'\n ]\n}\n```\n\n========================================\n\nTop Answer:\nI'm the creator of the nuxt sitemap module.\n\nYour sitemap-module configuration is set in the wrong section.\n\nPlease, update your `nuxt.config.js`:\n\n```\nmodules: ['@nuxtjs/pwa', '@nuxtjs/sitemap'],\nsitemap: {\n generate: true,\n hostname: 'https://www.example.com',\n exclude: [\n '/profile'\n ]\n},\nplugins: [\n```\n\nThen run `npm run generate`.\n\nFinally check your generated `sitemap.xml` in the `\\dist\\` folder.\n\n(If you have an other issue or question, you may open an issue on github project: https://github.com/nuxt-community/sitemap-module/issues)\n\n========================================\n\nCode:\n```text\nUser-agent: *\nDisallow: /profile/\nSitemap: https://www.example.com/sitemap.xml\n```\n\n```text\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:news=\"http://www.google.com/schemas/sitemap-news/0.9\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\" xmlns:mobile=\"http://www.google.com/schemas/sitemap-mobile/1.0\" xmlns:image=\"http://www.google.com/schemas/sitemap-image/1.1\" xmlns:video=\"http://www.google.com/schemas/sitemap-video/1.1\">\n<url> <loc>https://www.example.com/about</loc> </url>\n<url> <loc>https://www.example.com/</loc> </url>\n</urlset>\n```\n\n```text\nmodule.exports = {\n /*\n ** Headers of the page\n */\n head: {\n title: 'Title',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: 'Title' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n mode: 'spa',\n loading: { color: '#3B8070' },\n build: {\n /*\n ** Run ESLint on save\n */\n extend (config, { isDev, isClient }) {\n if (isDev && isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n }\n },\n css: [\n '~/assets/main.css'\n ],\n modules: [\n '@nuxtjs/pwa',\n [\n '@nuxtjs/sitemap', {\n generate: true,\n hostname: 'https://www.example.com',\n exclude: [\n '/profile'\n ]\n }\n ]\n ],\n plugins: [\n '~/plugins/uikit.js',\n '~/plugins/fireauth.js'\n ],\n manifest: {\n name: 'Title',\n lang: 'en'\n },\n router: {\n middleware: 'router-auth'\n },\n vendor: [\n 'firebase',\n 'uikit'\n ]\n}\n```\n\n```text\nrobots.txt\n```\n\n```text\n@nuxtjs/sitemap\n```\n\n```text\nsitemap.xml\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnpm install -g create-nuxt-app\n```\n\n```text\nmodules: ['@nuxtjs/pwa', '@nuxtjs/sitemap'],\nsitemap: {\n generate: true,\n hostname: 'https://www.example.com',\n exclude: [\n '/profile'\n ]\n},\nplugins: [\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnpm run generate\n```\n\n```text\nsitemap.xml\n```\n\n```text\n\\dist\\\n```\n\n```text\nuniversal\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.873Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":255,"estimatedTokens":1143}}512{"id":"stack-50101903","source":"stackoverflow","questionId":50101903,"title":"Nuxt Axios Module read status code","tags":["axios","nuxt.js"],"text":"Title: Nuxt Axios Module read status code\nTags: axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm calling a Rest API that returns at least 2 success status codes .\nA normal 200 OK and a 202 Accepted status code.\nBoth return a Content in the body.\nIf I execute in postman my calls I might get something like \n\nStatus code: 202 Accepted. With Body \"Queued\" or some other values\nhttps://i.sstatic.net/lvODq.png\nhttps://i.sstatic.net/82FH2.png\nor\n\nStatus code: 200 OK. With Body \"ValueOfSomeToken\"\nhttps://i.sstatic.net/YOvMm.png\nMaking the call with axios in my nuxt app: \n\n```\nthis.$axios.$get('/Controller/?id=1')\n .then((response)=>{\n if(response=='Queued'){\n //Do something\n }\n else if (response=='Expired'){\n //Do something\n }\n else{\n //Do something\n }\n })\n .catch((error)=>{\n console.log(error);\n });\n```\n\n..works, but I actually would like to get the status code (because 202 has other values for the body responses)\n\nI have no idea how to read the status codes.\n\nI tried using (response,code) =>... but code is then nothing.\n\n========================================\n\nTop Answer:\nYou can use non `$`-prefixed functions like `this.$axios.get()` instead of `this.$axios.$get()` to get the full response\n\n```\n// Normal usage with axios\nlet { data } = await $axios.get('...'));\n\n// Fetch Style\nlet data = await $axios.$get('...');\n```\n\n(source)\n\n========================================\n\nCode:\n```text\nthis.$axios.$get('/Controller/?id=1')\n .then((response)=>{\n if(response=='Queued'){\n //Do something\n }\n else if (response=='Expired'){\n //Do something\n }\n else{\n //Do something\n }\n })\n .catch((error)=>{\n console.log(error);\n });\n```\n\n```text\naxios.get(\"http://localhost:3000/testing\").then((response)=>{\n console.log(\"response \",response);\n if(response.status == 200){\n //do something\n }\n else if(response.status == 202){\n //do something\n }\n else if(response.status == 301){\n //do something\n }\n}).catch((err)=>{\n console.log(\"err11 \",err);\n})\n```\n\n```text\napp.get('/testing',(req, res)=> {\n res.status(202).send({\"res\" : \"hi\"});\n});\n```\n\n```text\nexport default function ({ $axios, redirect }) {\n $axios.onResponse(res=>{\n console.log(\"onResponse \", res);\n res.data.status = res.status; \n return res;\n })\n}\n```\n\n```text\nthis.$axios.$get(\"url\").then((response) =>{\n console.log(\"status \",response.status);\n}).catch((err) => {\n console.log(\"res err \",err);\n});\n```\n\n```text\nstatus codes\n```\n\n```text\naxios\n```\n\n```text\nstatus object\n```\n\n```text\nresponse.status\n```\n\n```text\nres.status()\n```\n\n```text\n@nuxtjs/axios\n```\n\n```text\nresponse.data\n```\n\n```text\n.then((response))\n```\n\n```text\n$axios.onResponse\n```\n\n```text\n$axios.onResponse\n```\n\n```text\nplugin/axios.js\n```\n\n```text\nplugins\n```\n\n```text\nplugins : ['~/plugins/axios']\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nres object\n```\n\n```text\nres object\n```\n\n```text\nres.data\n```\n\n```text\nres.data\n```\n\n```text\nres object\n```\n\n```text\nres.data.status = res.status;\n```\n\n```text\naxios\n```\n\n```text\nres.data\n```\n\n```text\nres.data.status\n```\n\n```text\nresponse\n```\n\n```text\n.then((response))\n```\n\n```text\nresponse.status\n```\n\n```text\nthis.$axios\n```\n\n```text\n// Normal usage with axios\nlet { data } = await $axios.get('...'));\n\n// Fetch Style\nlet data = await $axios.$get('...');\n```\n\n```text\n$\n```\n\n```text\nthis.$axios.get()\n```\n\n```text\nthis.$axios.$get()\n```\n\n========================================\n\nComments:\n- Thank you for your answer. But as I stated, I want to use the NUXT.js axios module.. not axios as separate package. I know that with axios it works. I wonder why it is not working on the axios nuxt module. Even thou with postman I see the correct status sent back.My response only has the string... no data object or status/status text\n- @CodeHacker i have updated the answer with details of @nuxtjs/axios module. Let me know if it helps\n- That was the answer I was looking for. Works great!\n- @divine Thanks for the detailed explanation however I'm not being able to use any of the event handlers (onError, onResponse...). I always get a `$axios.onResponse is not a function` error. Any idea why that is?\n- @Anonymous may be its a configuration problem. can you your code on github?","metadata":{"transformedAt":"2026-08-18T18:33:07.873Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":256,"estimatedTokens":1074}}513{"id":"stack-52571675","source":"stackoverflow","questionId":52571675,"title":"Nuxt.js: Module Error (from ./node_modules/eslint-loader/index.js):","tags":["javascript","css-loader","nuxt.js"],"text":"Title: Nuxt.js: Module Error (from ./node_modules/eslint-loader/index.js):\nTags: javascript, css-loader, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI installed Nuxt starter template the recommended way:\n\n```\nnpx create-nuxt-app fffff\n```\n\nOnce inside `fffff` I installed css-loder (`npm install --save-dev css-loader`) then I launched the server: `npm run dev`\n\nI got this error message:\n\n```\n> fffff@1.0.0 dev /home/begueradj/fffff\n> nuxt\n\n INFO Building project\n\n✔ success Builder initialized\n✔ success Nuxt files generated\n\n ERROR Failed to compile with 1 errors 22:09:09\n\n error in ./layouts/default.vue\n\nModule Error (from ./node_modules/eslint-loader/index.js):\n\n/home/begueradj/fffff/layouts/default.vue\n 89:1 error Delete `··` prettier/prettier\n 90:3 error Delete `··` prettier/prettier\n 91:1 error Replace `······` with `····` prettier/prettier\n 92:1 error Delete `··` prettier/prettier\n 93:1 error Replace `········` with `······` prettier/prettier\n 94:1 error Delete `··` prettier/prettier\n 95:1 error Replace `········` with `······` prettier/prettier\n 96:1 error Delete `··` prettier/prettier\n 97:1 error Replace `··········` with `········` prettier/prettier\n 98:7 error Delete `··` prettier/prettier\n 99:1 error Delete `··` prettier/prettier\n 100:7 error Delete `··` prettier/prettier\n 101:1 error Delete `··` prettier/prettier\n 102:7 error Delete `··` prettier/prettier\n 103:5 error Delete `··` prettier/prettier\n 104:1 error Replace `····` with `··` prettier/prettier\n 105:1 error Delete `··` prettier/prettier\n\n✖ 17 problems (17 errors, 0 warnings)\n 17 errors and 0 warnings potentially fixable with the `--fix` option.\n\n @ ./.nuxt/App.js 4:0-47 6:14-23\n @ ./.nuxt/index.js\n @ ./.nuxt/client.js\n @ multi webpack-hot-middleware/client?name=client&reload=true&timeout=30000&path=/__webpack_hmr ./.nuxt/client.js\n\n READY Listening on http://localhost:3000\n```\n\nWhat causes this? How to fix it?\n\n========================================\n\nTop Answer:\nNot recommended but useful if you just want to play around\n\n```\n// nuxt.config.js\n modules: [\n '@nuxtjs/axios'\n // '@nuxtjs/eslint-module' :: bypass this module\n ],\n```\n\nI hope that helps.\n\n========================================\n\nCode:\n```text\nnpx create-nuxt-app fffff\n```\n\n```text\n> fffff@1.0.0 dev /home/begueradj/fffff\n> nuxt\n\n\n\n INFO Building project\n\n✔ success Builder initialized\n✔ success Nuxt files generated\n\n\n ERROR Failed to compile with 1 errors 22:09:09\n\n error in ./layouts/default.vue\n\nModule Error (from ./node_modules/eslint-loader/index.js):\n\n/home/begueradj/fffff/layouts/default.vue\n 89:1 error Delete `··` prettier/prettier\n 90:3 error Delete `··` prettier/prettier\n 91:1 error Replace `······` with `····` prettier/prettier\n 92:1 error Delete `··` prettier/prettier\n 93:1 error Replace `········` with `······` prettier/prettier\n 94:1 error Delete `··` prettier/prettier\n 95:1 error Replace `········` with `······` prettier/prettier\n 96:1 error Delete `··` prettier/prettier\n 97:1 error Replace `··········` with `········` prettier/prettier\n 98:7 error Delete `··` prettier/prettier\n 99:1 error Delete `··` prettier/prettier\n 100:7 error Delete `··` prettier/prettier\n 101:1 error Delete `··` prettier/prettier\n 102:7 error Delete `··` prettier/prettier\n 103:5 error Delete `··` prettier/prettier\n 104:1 error Replace `····` with `··` prettier/prettier\n 105:1 error Delete `··` prettier/prettier\n\n✖ 17 problems (17 errors, 0 warnings)\n 17 errors and 0 warnings potentially fixable with the `--fix` option.\n\n\n @ ./.nuxt/App.js 4:0-47 6:14-23\n @ ./.nuxt/index.js\n @ ./.nuxt/client.js\n @ multi webpack-hot-middleware/client?name=client&reload=true&timeout=30000&path=/__webpack_hmr ./.nuxt/client.js\n\n\n\n READY Listening on http://localhost:3000\n```\n\n```text\nfffff\n```\n\n```text\nnpm install --save-dev css-loader\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpx prettier --write \"**/*.{vue,js}\"\n```\n\n```text\ncreate-nuxt-app\n```\n\n```text\n91:1 error Replace '······' with '····'\n```\n\n```text\nlayouts/default.vue\n```\n\n```js\n// nuxt.config.js\n modules: [\n '@nuxtjs/axios'\n // '@nuxtjs/eslint-module' :: bypass this module\n ],\n```\n\n========================================\n\nComments:\n- that's nice, do you know how to set it that is it runs that all the time, e.g. on save?\n- yes! you can this doc to run a watcher: prettier.io/docs/en/watching-files.html\n- or, you may configure your Editor to run Prettier on save: prettier.io/docs/en/editors.html\n- I created a new nuxt app for the first time ever and couldn't get it running because of this ESLint error. This solved it for me, except that the module was under buildModules.","metadata":{"transformedAt":"2026-08-18T18:33:07.873Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":178,"estimatedTokens":1286}}514{"id":"stack-71852756","source":"stackoverflow","questionId":71852756,"title":"How to increase speed performance in Nuxt with SSR","tags":["vue.js","nuxt.js","server-side-rendering","google-pagespeed","pagespeed-insights"],"text":"Title: How to increase speed performance in Nuxt with SSR\nTags: vue.js, nuxt.js, server-side-rendering, google-pagespeed, pagespeed-insights\nSource: Stack Overflow\n\nQuestion:\nHow we can increase the speed performance in Nuxt with SSR for the following points.\n\n- Reduce unused JavaScript\n\n- Avoid serving legacy JavaScript to modern\n\n- Minimize main-thread work\n\n- Reduce JavaScript execution time\n\n- Avoid enormous network payloads\n\n========================================\n\nTop Answer:\nFor speed optimization, we need to the following steps.\n\n- Need to optimize the images\n\n- Use shouldPreload in the render function nuxt.config.js\n\n- Use compressor: shrinkRay(), for compression\n\n- Use dns-prefetch for Google fonts\n\n- Use minify js and css\n\n- optimize API queries\n\n========================================\n\nComments:\n- You can even host your own google fonts, even better. Nuxt minifies the code already by default, did you needed some extra work there.\n- This is not really solving the issue as stated in the project. Use some real solution rather.","metadata":{"transformedAt":"2026-08-18T18:33:07.873Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":39,"estimatedTokens":264}}515{"id":"stack-57335203","source":"stackoverflow","questionId":57335203,"title":"How do I get the IP of a user in Nuxt's asyncData method?","tags":["javascript","vue.js","geolocation","nuxt.js"],"text":"Title: How do I get the IP of a user in Nuxt's asyncData method?\nTags: javascript, vue.js, geolocation, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nNuxt uses asyncData to run code server-side and then merges it with the data object.\n\nI want to make a call that requires me to know the user's IP. I see that I can get to the `req` object which does have it but it's buried deep, deep in there and I worry this is not a reliable way of doing it.\n\nHow can I access the calling user's IP address server-side instead of client-side?\n\n========================================\n\nTop Answer:\nThere was a github thread about this which makes grabbing the IP trivial in both environments (locally, production)\n\n```\nconst ip = req.connection.remoteAddress || req.socket.remoteAddress\n```\n\nBut be aware that you'll need to ensure the proxy headers are forwarded correctly. Because nuxt runs behind a traditional web server, without having the proxy headers forwarded, you'll always get the Local IP of the web server (127.0.0.1 unless loop back was changed).\n\n========================================\n\nCode:\n```text\nreq\n```\n\n```text\nproxy_set_header Host $host;\nproxy_set_header X-Forwarded-Proto $scheme;\nproxy_set_header X-Real-IP $remote_addr;\nproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n```\n\n```text\nasync asyncData(context) {\n if (process.server) {\n const req = context.req\n const headers = (req && req.headers) ? Object.assign({}, req.headers) : {}\n const xForwardedFor = headers['x-forwarded-for'] \n const xRealIp = headers['x-real-ip']\n console.log(xForwardedFor)\n console.log(xRealIp)\n }\n }\n```\n\n```text\nconst ip = req.connection.remoteAddress || req.socket.remoteAddress\n```\n\n========================================\n\nComments:\n- I'm unable to figure this out as I'm hosting on Heroku and it seems that I get an array of `remoteAddress` and I really don't want to expose sensitive keys client side\n- This solution is brilliant client-side but doesn't seem to work in `asyncData` piece in Nuxt returning `undefined`\n- Great answer, I hadn't considered taking advantage of the server itself. What used to worry me about that - you'd get a series of IP addresses like you mentioned.","metadata":{"transformedAt":"2026-08-18T18:33:07.873Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":59,"estimatedTokens":559}}516{"id":"stack-54062533","source":"stackoverflow","questionId":54062533,"title":"How to access a global function (Vue.prototype.myFn) from another function?","tags":["javascript","vue.js","vuejs2","nuxt.js"],"text":"Title: How to access a global function (Vue.prototype.myFn) from another function?\nTags: javascript, vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am on a nuxt.js project and trying to create global functions and I am this error:\n\n```\nCannot read property '$toggleBodyClass' of undefined\n```\n\nHere is my code (plugins/globals.js):\n\n```\nimport Vue from 'vue';\n\nVue.prototype.$toggleBodyClass = (addRemoveClass, className) => {\n const elBody = document.body;\n\n if (addRemoveClass === 'addClass') {\n elBody.classList.add(className);\n } else {\n elBody.classList.remove(className);\n }\n};\n\nVue.prototype.$setModalBackdrop = () => {\n this.$toggleBodyClass('addClass', 'modal-open'); // ** How to make this work? **\n};\n```\n\nThis work just fine when I use it in my component (components/myComp.vue):\n\n```\n\n \n Toggle Class\n \n\nexport default {\n methods: {\n handleClick() {\n this.$toggleBodyClass('addClass', 'modal-open');\n },\n },\n};\n\n```\n\nplease help, thanks.\n\n========================================\n\nTop Answer:\nIn nuxt you can use inject function to make it accessible from context, vuex store etc also inject\n\n```\nexport default ({ app }, inject) => {\n inject('myInjectedFunction', (string) => console.log('That was easy!', string))\n}\n```\n\n========================================\n\nCode:\n```text\nCannot read property '$toggleBodyClass' of undefined\n```\n\n```text\nimport Vue from 'vue';\n\nVue.prototype.$toggleBodyClass = (addRemoveClass, className) => {\n const elBody = document.body;\n\n if (addRemoveClass === 'addClass') {\n elBody.classList.add(className);\n } else {\n elBody.classList.remove(className);\n }\n};\n\nVue.prototype.$setModalBackdrop = () => {\n this.$toggleBodyClass('addClass', 'modal-open'); // ** How to make this work? **\n};\n```\n\n```text\n<template>\n <div>\n <button @click=\"handelClick\">Toggle Class</button>\n </div>\n</template>\n\n<script>\nexport default {\n methods: {\n handleClick() {\n this.$toggleBodyClass('addClass', 'modal-open');\n },\n },\n};\n</script>\n```\n\n```text\nthis.$toggleBodyClass\n```\n\n```text\nVue.prototype.$toggleBodyClass\n```\n\n```text\nexport default ({ app }, inject) => {\n inject('myInjectedFunction', (string) => console.log('That was easy!', string))\n}\n```\n\n========================================\n\nComments:\n- Have you tried `Vue.prototype.$toggleBodyClass` instead of `this.$toggleBodyClass`?\n- @SamiHult wow! that simply worked :) thanks. Can you add this as answer I'll mark it accepted.\n- This is quite ugly solution.","metadata":{"transformedAt":"2026-08-18T18:33:07.873Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":125,"estimatedTokens":623}}517{"id":"stack-54002348","source":"stackoverflow","questionId":54002348,"title":"How to resolve the \"Module not found: Error: Can't resolve 'fs'\" in nuxt.js?","tags":["node.js","vue.js","nuxt.js"],"text":"Title: How to resolve the \"Module not found: Error: Can't resolve 'fs'\" in nuxt.js?\nTags: node.js, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm a bit new to node, but from a lot of searching, it looks like 'fs' broke a lot of things in the past. I've come across several packages I've tried to install via npm and have run into the `Module not found: Error: Can't resolve 'fs'` error way too much. \n\nI've run the npm install, and fs downloads a placeholder package, but I'm really at a halt because a package (among several) still has a dependency on fs.\n\nNearly every solution I find has resulted in declaring `fs` as empty in the node section of the webpack settings:\n\n```\nnode: {\n fs: 'empty'\n},\n```\n\nUnfortunately, I'm using Vue.js and nuxt and there is no webpack settings file (that I know of). I've tried to add it into my nuxt_config.js but haven't been successful.\n extend(config, ctx) {\n config.node = {\n fs: \"empty\"\n };\n }\n\n**Is there a way to run the exclude inside of the nuxt_config? Also, is there a way to run it while still preserving my settings to run eslint on save?**\n\n```\nextend(config, ctx) {\n // Run ESLint on save\n if (ctx.isDev && ctx.isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n}\n```\n\nThanks.\n\n========================================\n\nTop Answer:\nJust in case it helps. In my case this error appeared all of a sudden and wasn't able to tell why. After trying everything (deleting and reinstalling npm packages, etc...) I found out that VS CODE auto referenced a package in a file I had just saved and I didn't notice.\n\nIn my case it added\n`import { query } from 'express'.`\n\nDeleted the line and everything worked again.\n\n========================================\n\nCode:\n```text\nnode: {\n fs: 'empty'\n},\n```\n\n```text\nextend(config, ctx) {\n // Run ESLint on save\n if (ctx.isDev && ctx.isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n}\n```\n\n```text\nModule not found: Error: Can't resolve 'fs'\n```\n\n```text\nfs\n```\n\n```text\nbuild: {\n extend (config, { isDev, isClient }) {\n\n config.node: {\n fs: 'empty'\n }\n\n // ....\n }\n}\n```\n\n```text\nfs\n```\n\n```text\n'empty'\n```\n\n```text\nimport { query } from 'express'.\n```\n\n```text\nbuild: {\n extend (config, { isDev, isClient }) { \n config.node = {\n fs: \"empty\"\n }\n })\n }\n```\n\n========================================\n\nComments:\n- Thanks much, @adamrights. I thought I'd done it the way you presented, but obviously, I did not - it works correctly the way you've presented. Can I ask a followup: is there a way to combine what you have with my eslint-on-save settings `if (ctx.isDev...` above inside of the extend block?\n- `{ isDev, isClient }` is the ctx object in your example. try... build: { ... // EXTEND extend (config, { isClient }) { if (isClient) { config.module.rules.push({ enforce: 'pre', test: /\\.js$/, loader: 'eslint-loader', exclude: /(node_modules)/, },{ enforce: 'pre', test: /\\.vue$/, loader: 'eslint-loader', exclude: /(node_modules)/, }) } } },\n- Thanks - I was able to get it ... realized I was just using a comma to separate the two sections and I need to remove it. Very much appreciation for the help!\n- You just saved my day.... or week. The exact same thing happened to me and I've been reinstalling and deleting things like crazy. Thank you so much Nadine!\n- Thankyou so much, this was my issue also. Was sending me crazy.\n- I've spent a whole day in frustration and the answer was this simple!! thank you!","metadata":{"transformedAt":"2026-08-18T18:33:07.873Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":127,"estimatedTokens":923}}518{"id":"stack-58205391","source":"stackoverflow","questionId":58205391,"title":"NuxtJS - Use asyncData method in layout or component","tags":["typescript","vue.js","vue-component","nuxt.js","asyncdata"],"text":"Title: NuxtJS - Use asyncData method in layout or component\nTags: typescript, vue.js, vue-component, nuxt.js, asyncdata\nSource: Stack Overflow\n\nQuestion:\nHow I can use `asyncData` in layout or component (*forbidden apparently*) ?\n\nBecause my sidebar component is used in default layout, and I need to use `asyncData` to display data from backend.\nAnd if I use Vuex to fetch data... I don't know how I can fetch this with global on every page.\n\n### My layout component annotation:\n\n```\n@Component({\n components: {\n LeftDrawer\n },\n async asyncData({ app }) {\n const latestPosts = await app.$axios.get(`/posts/latest`);\n\n return {\n latestPosts: latestPosts.data,\n };\n }\n })\n```\n\n========================================\n\nTop Answer:\nThe new `fetch` on `Nuxt >= 2.12` now supports fetching on the `layout` and `component` level.\n\nRight now it's slightly broken for me on the `layout` level for my statically generated site so I use `fetchOnServer: false`. By the time future people read this it'll hopefully be fixed, so feel free to edit this out.\n\nHere's some useful reading material :)\n\nDocs\n\nGeneral guide\n\nGuide for static sites\n\n========================================\n\nCode:\n```text\n@Component({\n components: {\n LeftDrawer\n },\n async asyncData({ app }) {\n const latestPosts = await app.$axios.get(`/posts/latest`);\n\n return {\n latestPosts: latestPosts.data,\n };\n }\n })\n```\n\n```text\nasyncData\n```\n\n```text\nasyncData\n```\n\n```text\nactions: {\n async nuxtServerInit({ dispatch }) {\n await dispatch('core/load')\n }\n}\n```\n\n```text\nfetch\n```\n\n```text\nNuxt >= 2.12\n```\n\n```text\nlayout\n```\n\n```text\ncomponent\n```\n\n```text\nlayout\n```\n\n```text\nfetchOnServer: false\n```\n\n========================================\n\nComments:\n- I am also noticing issues with `async fetch()` when combined with `target: \"static\"` in my Nuxt config. `fetchOnServer: false` fixes my issue for some components, but when applied to others, it breaks my build...Still troubleshooting.\n- Make another Stack Overflow question and tag me, I'll see if I can see something obvious. If not, you might need to make a Github issue.\n- Our current solution which my coworker found is to do `created() { this.$fetch(); }` I asked him about it and his theory is that in the server `mounted()` won't run until `created()` is done. Since we call the fetch API in the created lifecycle method, the data will be available when the mounted lifecycle method runs. The QA passed, so I am assuming this method works for our use case of fetching yaml translation files on build.\n- Glad you got it working, still worth making a Github issue so they they can either fix this or add it to the docs. Good luck with the rest of your project :)","metadata":{"transformedAt":"2026-08-18T18:33:07.874Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":107,"estimatedTokens":682}}519{"id":"stack-57646790","source":"stackoverflow","questionId":57646790,"title":"How to copy element into clipboard using Nuxt.js?","tags":["nuxt.js"],"text":"Title: How to copy element into clipboard using Nuxt.js?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI created a Nuxt webpage with Vuetify.js that generates an Email signature from a form to fill in. The render of the signature is displayed in a `v-card` element. I have added a `v-btn` to automatically copy the signature into the clipboard of the user, but I have some issues with it...\n\nI tried to use `nuxt-clipboard2` from npm to help me doing this but nothing works...\n\nIs anyone knows how to use this package correctly or have an alternative to copy content into the clipboard with Nuxt.js?\n\nThanks in advance :)\n\nEDIT\n\nHere's my code:\n\n```\n\n \n\n Email signature\n\n \n\n \n\n \n \n \n \n \n \n \n \n \n \n mdi-content-copyCopy the signature\n \n \n \n\n \n\nimport signTemplate from '~/components/SignTemplate.vue'\nimport signForm from '~/components/signForm.vue'\n\nexport default {\n methods: {\n async copySign() {\n try {\n await this.$copyText(foo);\n } catch (e) {\n console.error(e);\n }\n }\n },\n components: {\n signTemplate,\n signForm\n }\n}\n\n```\n\nEDIT #2\n\nHere's the `signTemplate.vue`code.\n\n```\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n {{this.$store.getters[\"getSignFirstName\"]}} {{this.$store.getters[\"getSignLastName\"]}}\n \n \n {{this.$store.getters[\"getSignJob\"]}} {{this.$store.getters[\"getSignDiv\"]}}\n \n \n tel: 01.43.70.26.56\n \n \n mobile: {{this.$store.getters[\"getSignPhone\"]}}\n \n \n email: {{this.$store.getters[\"getSignEmail\"]}}\n \n \n 6 Rue des immeubles Industriels\n \n \n 75011, Paris\n \n \n \n \n https://fr-fr.facebook.com/junior.entreprises/\n https://fr.linkedin.com/company/conf-d-ration-nationale-des-junior-entreprises\n https://twitter.com/cnje\n https://www.instagram.com/cnje/\n \n \n \n \n \n \n \n \n Avec le soutiens de nos partenaires premiums: BNP Paribas, Alten, EY et Engie.\n \n \n \n \n\n```\n\nEDIT #3\n\nHere's a screenshot of what looks like my page right now. I would like to copy all the signature that is inside the `v-card` element by clinking on the button \"Selectionner la signature\".\n\nhttps://i.sstatic.net/wDGLs.png\n\n========================================\n\nTop Answer:\nI honestly don't think npm package is needed for this. Just go with vanilla js solution. It's so simple. \n\nHere's the modern one. It has pretty solid browser support\n\n```\nmethods: {\n copySign() {\n //btw writeText() returns a promise so you could utilize that somehow if you want\n navigator.clipboard.writeText(this.$refs.foo.$el.outerHTML)\n }\n}\n```\n\nThat's it. One line of code. \n\nBut if you are looking to support older browsers use this old and longer approach.\n\n```\n//Creating textarea element\nlet textarea = document.createElement(\"textarea\")\n//Settings its value to the thing you want to copy\ntextarea.value = this.$refs.foo.$el.outerHTML\n//Appending the textarea to body\ndocument.body.appendChild(textarea)\n//Selecting its content\ntextarea.focus()\ntextarea.select()\n//Copying the selected content to clipboard\ndocument.execCommand(\"copy\")\n//Removing the textarea\ndocument.body.removeChild(textarea)\n```\n\n========================================\n\nCode:\n```html\n<template>\n <v-container fluid>\n\n <div class=\"display-3\">Email signature</div>\n\n <signForm></signForm>\n\n <v-divider></v-divider>\n\n <v-container>\n <v-row justify=\"center\" align=\"center\">\n <v-col md=\"12\">\n <v-row justify=\"center\" align=\"center\">\n <v-card color=\"fafafa\" class=\"pa-3\">\n <signTemplate ref=\"foo\"></signTemplate>\n </v-card>\n </v-row>\n </v-col>\n <v-btn class=\"ma-2\" @click=\"copySign\" tile>\n <v-icon left>mdi-content-copy</v-icon>Copy the signature\n </v-btn>\n </v-row>\n </v-container>\n\n </v-container>\n</template>\n\n\n<script>\nimport signTemplate from '~/components/SignTemplate.vue'\nimport signForm from '~/components/signForm.vue'\n\nexport default {\n methods: {\n async copySign() {\n try {\n await this.$copyText(foo);\n } catch (e) {\n console.error(e);\n }\n }\n },\n components: {\n signTemplate,\n signForm\n }\n}\n</script>\n```\n\n```html\n<template>\n <div>\n <table cellpadding=\"0\" cellspacing=\"0\" style=\"font-variant-ligatures: normal; orphans: 2; widows: 2; border-spacing: 0px; border-collapse: collapse; color: rgb(68, 68, 68); width: 480px; font-size: 10pt; font-family: Arial, sans-serif; line-height: normal;\">\n <tbody>\n <tr>\n <td valign=\"top\" style=\"font-family: Roboto, RobotoDraft, Helvetica, Arial, sans-serif; margin: 0px; padding: 10px 0px 12px; width: 160px; vertical-align: top;\">\n <a href=\"https://junior-entreprises.com/\" target=\"_blank\" style=\"background-color: transparent; color: rgb(51, 122, 183);\">\n <img border=\"0\" alt=\"Logo\" width=\"141\" src=\"https://junior-entreprises.com/wp-content/uploads/2019/01/Logo-50-ans-JE-site.png\" style=\"border: 0px; vertical-align: middle; width: 141px; height: auto;\">\n </a>\n </td>\n <td style=\"font-family: Roboto, RobotoDraft, Helvetica, Arial, sans-serif; margin: 0px; padding: 6px 0px; width: 320px;\">\n <table cellpadding=\"0\" cellspacing=\"0\" style=\"border-spacing: 0px; border-collapse: collapse; background-color: transparent;\">\n <tbody>\n <tr>\n <td style=\"font-family: Arial, sans-serif; margin: 0px; padding: 0px; font-size: 12pt; font-weight: bold; color: rgb(61, 60, 63);\"> {{this.$store.getters[\"getSignFirstName\"]}} {{this.$store.getters[\"getSignLastName\"]}}</td>\n </tr>\n <tr>\n <td style=\"font-family: Arial, sans-serif; margin: 0px; padding: 0px 0px 11px; font-size: 10pt; color: rgb(61, 60, 63);\">{{this.$store.getters[\"getSignJob\"]}} {{this.$store.getters[\"getSignDiv\"]}}</td>\n </tr>\n <tr>\n <td style=\"font-family: Arial, sans-serif; margin: 0px; padding: 0px; color: rgb(155, 155, 155);\"><font style=\"font-size: 12px;\">tel: 01.43.70.26.56</font></td>\n </tr>\n <tr>\n <td style=\"font-family: Arial, sans-serif; margin: 0px; padding: 0px; color: rgb(155, 155, 155);\"><font style=\"font-size: 12px;\">mobile: {{this.$store.getters[\"getSignPhone\"]}}</font></td>\n </tr>\n <tr>\n <td style=\"font-family: Arial, sans-serif; margin: 0px; padding: 0px; color: rgb(155, 155, 155);\"><font style=\"font-size: 12px;\">email: <span style=\"color: rgb(23, 147, 210);\"><span style=\"color: rgb(183, 26, 81);\"><a href=\"mailto:\" target=\"_blank\">{{this.$store.getters[\"getSignEmail\"]}}</a></span></span></font></td>\n </tr>\n <tr>\n <td style=\"font-family: Arial, sans-serif; margin: 0px; padding: 0px; color: rgb(155, 155, 155);\"><font style=\"font-size: 12px;\">6 Rue des immeubles Industriels</font></td>\n </tr>\n <tr>\n <td style=\"font-family: Arial, sans-serif; margin: 0px; padding: 0px; color: rgb(155, 155, 155);\"><font style=\"font-size: 12px;\">75011, Paris</font></td>\n </tr>\n <tr>\n <td style=\"margin: 0px; padding: 6px 0px 0px;\">\n <span style=\"display: inline-block; height: 22px;\">\n <a href=\"https://fr-fr.facebook.com/junior.entreprises/\" target=\"_blank\" style=\"background-color: transparent; color: rgb(51, 122, 183);\"><img alt=\"Facebook icon\" border=\"0\" width=\"23\" height=\"23\" src=\"https://codetwocdn.azureedge.net/images/mail-signatures/generator/elegant-logo/fb.png\" style=\"border: 0px; vertical-align: middle; height: 20px; width: 20px;\"></a>\n <a href=\"https://fr.linkedin.com/company/conf-d-ration-nationale-des-junior-entreprises\" target=\"_blank\" style=\"background-color: transparent; color: rgb(51, 122, 183);\"><img alt=\"LinkedIn icon\" border=\"0\" width=\"23\" height=\"23\" src=\"https://codetwocdn.azureedge.net/images/mail-signatures/generator/elegant-logo/ln.png\" style=\"border: 0px; vertical-align: middle; height: 20px; width: 20px;\"></a>\n <a href=\"https://twitter.com/cnje\" target=\"_blank\" style=\"background-color: transparent; color: rgb(51, 122, 183);\"><img alt=\"Twitter icon\" border=\"0\" width=\"23\" height=\"23\" src=\"https://codetwocdn.azureedge.net/images/mail-signatures/generator/elegant-logo/tt.png\" style=\"border: 0px; vertical-align: middle; height: 20px; width: 20px;\"></a>\n <a href=\"https://www.instagram.com/cnje/\" target=\"_blank\" style=\"background-color: transparent; color: rgb(51, 122, 183);\"><img alt=\"Instagram icon\" border=\"0\" width=\"23\" height=\"23\" src=\"https://codetwocdn.azureedge.net/images/mail-signatures/generator/elegant-logo/it.png\" style=\"border: 0px; vertical-align: middle; height: 20px; width: 20px;\"></a>\n </span>\n </td>\n </tr>\n </tbody>\n </table>\n </td>\n </tr>\n <tr>\n <td colspan=\"2\" style=\"font-size: 13px; margin: 0px; padding: 8px 0px 0px; border-top-width: 1px; border-top-style: solid; border-top-color: rgb(183, 26, 81); width: 480px; color: rgb(155, 155, 155); text-align: center;\">Avec le soutiens de nos partenaires premiums: <a href=\"https://group.bnpparibas/\" target=\"_blank\">BNP Paribas</a>, <a href=\"https://www.alten.fr/\" target=\"_blank\">Alten</a>, <a href=\"https://www.ey.com/fr/fr/home\" target=\"_blank\">EY</a> et <a href=\"https://particuliers.engie.fr/\" target=\"_blank\">Engie</a>.</td>\n </tr>\n </tbody>\n </table>\n </div>\n</template>\n```\n\n```text\nv-card\n```\n\n```text\nv-btn\n```\n\n```text\nnuxt-clipboard2\n```\n\n```text\nsignTemplate.vue\n```\n\n```text\nv-card\n```\n\n```text\nawait this.$copyText(this.$refs.foo)\n```\n\n```text\nref\n```\n\n```text\nsignTemplate\n```\n\n```text\nv-model\n```\n\n```text\nsignTemplate\n```\n\n```text\nawait this.$copyText(this.$refs.foo.$el.innerHTML)\n```\n\n```text\ninnerText\n```\n\n```js\nmethods: {\n copySign() {\n //btw writeText() returns a promise so you could utilize that somehow if you want\n navigator.clipboard.writeText(this.$refs.foo.$el.outerHTML)\n }\n}\n```\n\n```js\n//Creating textarea element\nlet textarea = document.createElement(\"textarea\")\n//Settings its value to the thing you want to copy\ntextarea.value = this.$refs.foo.$el.outerHTML\n//Appending the textarea to body\ndocument.body.appendChild(textarea)\n//Selecting its content\ntextarea.focus()\ntextarea.select()\n//Copying the selected content to clipboard\ndocument.execCommand(\"copy\")\n//Removing the textarea\ndocument.body.removeChild(textarea)\n```\n\n========================================\n\nComments:\n- Can you please post the relevant code?\n- I have edited my question to add my code.\n- You're probably right, the Vue ref doesn't contain the formated text I want to copy... When I try to replace by `await this.$copyText(this.$refs.foo)` the value copy to the clipboard is `[object Object]`. Do you think if I pass my the `v-model` this will work? I will try now :)\n- In `copySign` method, place `console.log(this.$refs.foo)` to see in console devtools whats your Object contain. But I think it's a `VueComponent`. Try this `await this.$copyText(this.$refs.foo.textContent)` but it's not a good practice to do like that...\n- By passing by `this.$refs.foo.$refs.textContent` I obtain only text without format... And after exploring the response of `console.log(this.$refs.foo)` I think is not possible to copy the formatted content in this way...\n- Do know if it possible to process another way by only pre-selected the content and let the user process the `crtl+c`? I already view this case on this website by clicking on the button at the end of the form.\n- `this.$refs.foo.$refs.textContent`? You mean `this.$refs.foo.textContent`. You can also access data with `this.$refs.foo.$data`. Publish the code of the `signTemplate` component to provide more information, it'll be easier to answer...\n- Ouch, signTemplate is a very ulgly component with many bad practice. Sorry. Anyway, which value do you want to copy? It's unclear...\n- OK. I made a codesandbox with nuxt-clipboard2. Take a look on it: codesandbox.io/s/codesandbox-nuxt-wuuo5\n- Thanks a lot for the sandbox! :) Yeah... SignTemplate is a plenty HTML with CSS component that contains the signature, it may be not the good way to process but I started Nuxt.js with this project a few weeks ago and I still learning. I have added a screenshot of my page in my post to show what is look like and wich element I would like to copy.\n- Let us continue this discussion in chat.\n- Most likely should be `navigator.clipboard.writeText(this.$refs.foo.innerHTML)`\n- This doesn't work and returns `TypeError: navigator.clipboard is undefined`\n- @DavidRhoderick If `navigator.clipboard` is `undefined` on a live website, make sure it is running on the secure https protocol. Otherwise, it won't work. If that's not the case, I sadly can't help you without any specific details.","metadata":{"transformedAt":"2026-08-18T18:33:07.874Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":371,"estimatedTokens":3479}}520{"id":"stack-51644901","source":"stackoverflow","questionId":51644901,"title":"Using tawk.to with Nuxt/Vue Application","tags":["javascript","html","vue.js","nuxt.js","tawk.to"],"text":"Title: Using tawk.to with Nuxt/Vue Application\nTags: javascript, html, vue.js, nuxt.js, tawk.to\nSource: Stack Overflow\n\nQuestion:\nDoes anyone know how to use tawk.to in a Nuxt application?\n\nI created a file \"tawk.js\" on my plugin folder with the following code:\n\n```\nvar Tawk_API = Tawk_API || {},\n Tawk_LoadStart = new Date()\n (function () {\n var s1 = document.createElement('script')\n s0 = document.getElementsByTagName('script')[0]\n s1.async = true\n s1.src = 'https://embed.tawk.to/[my_ID_HERE]/default'\n s1.charset = 'UTF-8'\n s1.setAttribute('crossorigin', '*')\n s0.parentNode.insertBefore(s1, s0)\n })()\n```\n\nAnd I put it on nuxt.config.js as well:\n\n```\nplugins: [\n { src: '~/plugins/tawk.js', ssr: false }\n ]\n```\n\nIt didn't work. It does show some compiled errors:\n\n```\n1:1 error Split initialized 'var' declarations into multiple statements\n1:5 error Identifier 'Tawk_API' is not in camel case\n1:16 error Identifier 'Tawk_API' is not in camel case\n1:16 error 'Tawk_API' was used before it was defined\n2:3 error Identifier 'Tawk_LoadStart' is not in camel case\n2:3 error 'Tawk_LoadStart' is assigned a value but never used\n2:29 error Unexpected space between function name and paren\n3:3 error Unexpected newline between function and ( of function call\n5:5 error 's0' is not defined\n10:5 error 's0' is not defined\n10:36 error 's0' is not defined\n```\n\n========================================\n\nTop Answer:\nThe best way to integrate `tawk.to` in nuxt project is to\ngo to `nuxt.config.js` and add it as a `script` tag.\n\n```\n// nuxt.config.js\nexport default {\n // ...\n head: {\n // ...\n script: [\n // ...\n {\n hid: 'tawk.to',\n src:\n 'https://embed.tawk.to/5edf699a9e5f694422903412/default',\n defer: true\n }\n ]\n },\n},\n```\n\n========================================\n\nCode:\n```text\nvar Tawk_API = Tawk_API || {},\n Tawk_LoadStart = new Date()\n (function () {\n var s1 = document.createElement('script')\n s0 = document.getElementsByTagName('script')[0]\n s1.async = true\n s1.src = 'https://embed.tawk.to/[my_ID_HERE]/default'\n s1.charset = 'UTF-8'\n s1.setAttribute('crossorigin', '*')\n s0.parentNode.insertBefore(s1, s0)\n })()\n```\n\n```text\nplugins: [\n { src: '~/plugins/tawk.js', ssr: false }\n ]\n```\n\n```text\n1:1 error Split initialized 'var' declarations into multiple statements\n1:5 error Identifier 'Tawk_API' is not in camel case\n1:16 error Identifier 'Tawk_API' is not in camel case\n1:16 error 'Tawk_API' was used before it was defined\n2:3 error Identifier 'Tawk_LoadStart' is not in camel case\n2:3 error 'Tawk_LoadStart' is assigned a value but never used\n2:29 error Unexpected space between function name and paren\n3:3 error Unexpected newline between function and ( of function call\n5:5 error 's0' is not defined\n10:5 error 's0' is not defined\n10:36 error 's0' is not defined\n```\n\n```text\nimport Tawk from 'vue-tawk'\n\nVue.use(Tawk, {\n tawkSrc: 'https://embed.tawk.to/5d5528ee2xxxxxxxxxxxx/default'\n})\n```\n\n```js\n// nuxt.config.js\nexport default {\n // ...\n head: {\n // ...\n script: [\n // ...\n {\n hid: 'tawk.to',\n src:\n 'https://embed.tawk.to/5edf699a9e5f694422903412/default',\n defer: true\n }\n ]\n },\n},\n```\n\n```text\ntawk.to\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nscript\n```\n\n========================================\n\nComments:\n- All errors, except the last three, come from your linter settings (I guess eslint?). Read them carefully and you should be able to fix them. The `'s0' is not defined` error suggests, that `document.getElementsByTagName('script')[0]` didnt find the `script` tag it was looking for and you might want to use another element (which actually exists) as parent element.\n- Thanks Oskar. I could fix the eslint errors with `/* eslint-disable */` but I couldn't figure out how to deal with the 's0' error as the \"script\" ID might be on their chat widget.\n- The `s0` error happens, because your code tries to find an existing `script` tag to use as insertion point for the Tawk script, but it doesnt find one. You can try to append the script to the document body directly like so: Remove `s0 = document.getElementsByTagName('script')[0]` and replace `s0.parentNode.insertBefore(s1, s0)` with `document.body.appendChild(s1);`.\n- did this work for you ? I tried it in my nuxt website and chat widget is not loading. there is not error in console.\n- it worked for me, but is there any way to stop tawk from loading on some routes?\n- created() { window.Tawk_API.onLoad = function () { window.Tawk_API.hideWidget(); }; }, Use this to stop tawk from loading on some components","metadata":{"transformedAt":"2026-08-18T18:33:07.874Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":157,"estimatedTokens":1172}}521{"id":"stack-41761761","source":"stackoverflow","questionId":41761761,"title":"I can't use third party components in Nuxt.js/vue.js","tags":["javascript","vue.js","nuxt.js"],"text":"Title: I can't use third party components in Nuxt.js/vue.js\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI attempt use this library for my Nuxt project:\ngetting-started\n\nI tried do how to written in docs, but in all variants get an error for example: Unknown custom element: - did you register the component correctly?\n\nFor recursive components, make sure to provide the \"name\" option.\nwhat I tried:\n\n```\n\n \n \n\n### grge\n\n \n \n\n \n\n .div-wrapper {\n background: #f4f4f4;\n padding: 95px 15px 50px 15px;\n }\n\n import Vue from 'vue';\n export default {\n data() {\n return {\n USstate: ['Alabama', 'Alaska', 'Arizona'],\n asyncTemplate: '{{ item.formatted_address }}',\n githubTemplate: ' {{item.login}}'\n }\n },\n mounted(){\n var typeahead = require('vue-strap/src/Typeahead');\n Vue.component('typeahead',typeahead);\n new Vue({\n el: 'typeahead'\n })\n },\n methods: {\n googleCallback(items, targetVM) {\n const that = targetVM;\n that.reset()\n that.value = items.formatted_address\n },\n githubCallback(items) {\n window.open(items.html_url, '_blank')\n }\n }\n }\n\n```\n\nget error: window is undefined.\nthan i try this:\n\n```\nmounted(){\n var typeahead = require('vue-strap/src/Typeahead');\n Vue.component('typeahead',typeahead);\n new Vue({\n el: 'typeahead'\n })\n }\n```\n\nrender but have many errors:\n\nAnd tried write as plugin how to described in ru.nuxtjs.org/examples/plugins\nbut unsuccessfully.\nPlease help me correctly plug this library.\n\n========================================\n\nCode:\n```text\n<template>\n <div class=\"div-wrapper\">\n <h1>grge</h1>\n <div id=\"typeahead\"><typeahead :data=\"USstate\" placeholder=\"USA states\">\n </typeahead></div>\n\n\n\n </div>\n</template>\n<style lang=\"less\">\n .div-wrapper {\n background: #f4f4f4;\n padding: 95px 15px 50px 15px;\n }\n</style>\n<script>\n import Vue from 'vue';\n export default {\n data() {\n return {\n USstate: ['Alabama', 'Alaska', 'Arizona'],\n asyncTemplate: '{{ item.formatted_address }}',\n githubTemplate: '<img width=\"18px\" height=\"18px\" :src=\"item.avatar_url\"> <span>{{item.login}}</span>'\n }\n },\n mounted(){\n var typeahead = require('vue-strap/src/Typeahead');\n Vue.component('typeahead',typeahead);\n new Vue({\n el: 'typeahead'\n })\n },\n methods: {\n googleCallback(items, targetVM) {\n const that = targetVM;\n that.reset()\n that.value = items.formatted_address\n },\n githubCallback(items) {\n window.open(items.html_url, '_blank')\n }\n }\n }\n</script>\n```\n\n```text\nmounted(){\n var typeahead = require('vue-strap/src/Typeahead');\n Vue.component('typeahead',typeahead);\n new Vue({\n el: 'typeahead'\n })\n }\n```\n\n```text\nimport Vue from 'vue'\nimport VueTouch from 'vue-touch'\n```\n\n```text\nVue.use(VueTouch, {name: 'v-touch'})\n```\n\n```text\nif (process.BROWSER_BUILD) { \n Vue.use(VueTouch, {name: 'v-touch'})\n}\n```\n\n```text\nconsole.log('plugin v-touch is locked and loaded')\n```\n\n```text\nplugins: ['~plugins/vue-touch'],\nbuild: {\n ...\n}\n```\n\n```text\n<v-touch @swipe=\"onswipeleft\" class=\"dragme\">SWIIIIIIPE</v-touch>\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.874Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":169,"estimatedTokens":830}}522{"id":"stack-74884488","source":"stackoverflow","questionId":74884488,"title":"nuxt 3 useFetch() returns the error fetch failed()","tags":["vue.js","nuxt.js","runtime-error","vuejs3","nuxt3.js"],"text":"Title: nuxt 3 useFetch() returns the error fetch failed()\nTags: vue.js, nuxt.js, runtime-error, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI have set up the nuxt 3 from the nuxt 3 official documents and used the only useFetch() composable to fetch data in app.vue file but it returns the error `Error: fetch failed()` when we reload the page.\n\nPlease check my below code of app.vue file\n\n```\n\n{{data}}\n\n const { data, pending, error, refresh } = useFetch('https://api.nuxtjs.dev/mountains',\n {\n method: \"get\",\n });\n\n console.log(data.value);\n if (error.value) {\n console.log(error.value);\n }\n\n```\n\nI have tried useFetch and useLazyFetch composable to fetch the data but both returns the same error when we reload the page. I think there is some issue with client side or server side but don't know much about this. Also useFetch() returns result correctly when we visit that page again but it occurring error on initial api call or we hard reload the page.\n\n========================================\n\nTop Answer:\nReal subject here is why fetch or axios.get would fail in SSR mode and what configuration allows us to keep SSR and still get data.\nStill looking into that on my side.\n\n========================================\n\nCode:\n```html\n<template>\n{{data}}\n</template>\n\n<script setup>\n const { data, pending, error, refresh } = useFetch('https://api.nuxtjs.dev/mountains',\n {\n method: \"get\",\n });\n\n console.log(data.value);\n if (error.value) {\n console.log(error.value);\n }\n</script>\n```\n\n```text\nError: fetch failed()\n```\n\n```js\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n ssr: false,\n})\n```\n\n```text\nssr: false\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nssr: false\n```\n\n```text\nssr: false\n```\n\n```text\nNODE_TLS_REJECT_UNAUTHORIZED=0\n```\n\n```text\n.env\n```\n\n```html\n<template>\n <div>\n <pre>{{ data }}</pre>\n </div>\n</template>\n\n<script setup>\n// api call (async implied in this context)\n// this call is a GET by default\nconst { data, error } = await useFetch('https://api.nuxtjs.dev/mountains')\n\n// log response (data will be a ref)\nif (error.value) console.log('ERROR from useFetch: ', error.value)\nif (data.value) console.log('data returned from useFetch: ', data)\n</script>\n```\n\n```text\n<template>\n{{data}}\n</template>\n\n<script setup>\nawait nextTick(()=>{\n const { data, pending, error, refresh } = useFetch('https://api.nuxtjs.dev/mountains',\n {\n method: \"get\",\n });\n\n console.log(data.value);\n if (error.value) {\n console.log(error.value);\n }\n})\n</script>\n```\n\n```text\n<template>\n{{pending ? 'loading' : data}}\n</template>\n\n<script setup>\n const { data, pending, error, refresh } = await useFetch('https://api.nuxtjs.dev/mountains',\n {\n method: \"get\",\n });\n\n if (error.value) console.log('ERROR from useFetch: ', error.value)\n if (data.value) console.log('data returned from useFetch: ', data.value)\n</script>\n```\n\n```text\nlocalhost\n```\n\n```text\n127.0.0.1\n```\n\n```text\nlocalhost\n```\n\n========================================\n\nComments:\n- Works perfectly fine on my side, even after a hard refresh. Are you using nuxt `v3.0.0`? Also, which package manager are you using? Do you have a public GitHub repo? Are you using v18 or v16?\n- @kissu Yes I am using nuxt version `v3.0.0`, Node Version: `v19.3.0` Package manager: `npm` Do you have a public GitHub repo: `No` Please let me know if you need with any other things.\n- Don't use an unstable version of Node. Use v18 or v16 rather (even versions).\n- @kissu I have tried with node version `18.12.1, 18.0.0, 16.0.0,` still it returns the same error. I just switch one by one mentioned version->delete package.loc.json file -> delete node module->npm install->npm run dev Still returns the same error. Please help me with this. Also, I think there is some SSR and client side rendering issue?\n- Try to also delete the `.nuxt` directory, it's a cache. Remove `method: get` also, it's not needed. Try with `yarn` and maybe Firefox just to see if you have some other error (more verbose). I know that NPM can have some issues getting all the dependencies sometimes. How have you created the project? With `npx`? Your code snippet works well on my side. Also, what is your OS ?\n- @kissu Thank you for your answering on this. My OS is `ubuntu` and I have create the project with the command `npx nuxi init ` from [link]nuxt.com/docs/getting-started/installation this documentation Meanwhile I am trying to removing the .nuxt folder with `yarn` I will get back soon if its work or not.\n- @kissu I just created a fresh nuxt3 setup and used `yarn` with node version `18.12.1` but still, it returns the same error `Error: fetch failed ()`. Even it returns some experimental error `ERROR (node:60811) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time` when we run `yarn install`.\n- @kissu Thank you very much for your answer. I have tried with your provided code but still returning the same error `ERROR from useFetch: Error: fetch failed ()`. I have also tried `server: false` but still it not working.\n- I think there is one setting on `nuxt.config.ts` file `ssr: false` I just did it and it is working fine. Can you please explain whether this is the right way or not and when we need to keep this `ssr: false`? If you can explain with a real scenario or example that would be great!..! Thank you for helping me!\n- This is more a workaround than a fix. Without SSR, you don't really need `useFetch`, since the fetch just happens on the client, anyway.\n- @rudolfbyker Can you please tell me if this above is the valid fix or not?\n- As I said, this is a workaround, not a fix.\n- @rudolfbyker what about Axios if we could use it with nuxt 3 to overcome this if make sens\n- @rudolfbyker I have updated the answer and added case 2. this will be a standard fix for this error. Here we can not break the SSR feature.\n- I am using `Node v 19` I have tried with node 16 but it was no working hence I have done `ssr: false` Is this an appropriate fix?\n- As I said, disabling SSR so you don't face the fetch bug is like riding a bike since a motorcycle runs out of gas. It beats the purpose. But if doing client-side rendering fits your needs, then why not :D\n- Yes I am working on single page application so there no need of server side rendering\n- I updated to Node v20.10.0, However I couldn't solve the problem.","metadata":{"transformedAt":"2026-08-18T18:33:07.874Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":176,"estimatedTokens":1604}}523{"id":"stack-68986253","source":"stackoverflow","questionId":68986253,"title":"My SASS variables into :root are not interpolated","tags":["css","vue.js","sass","nuxt.js"],"text":"Title: My SASS variables into :root are not interpolated\nTags: css, vue.js, sass, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm fairly new to the Nuxt ecosystem. Awesome package that makes our lives much easier.\n\nI'm trying to add `sass` to my project. After following the documentation my build runs perfectly but my `scss` files are not being compiled. An example of the problem:\n\nhttps://i.sstatic.net/ySEem.png\n\nNotice that `--thm-font` is set to `$primaryTypography` and not the actual value from the `.scss`.\n\nI'm expecting to see `--thm-font: 'Barlow', sans-serif`. I'm assuming that the `sass` is not being compiled. It is important to note I'm not looking for a component base style but I'm trying to have a `main.scss` where I will import the component, layouts and many other styles.\n\n### _variables.scss\n\n```\n// Base colors\n$base: #ee464b;\n$baseRgb: (238, 70, 75);\n$black: #272839;\n$blackRgb: (39, 40, 57);\n$grey: #f4f4f8;\n\n// Typography\n$primaryTypography: 'Barlow', sans-serif;\n\n@debug $primaryTypography; // -> this one outputs the correct value\n\n:root {\n --thm-font: $primaryTypography;\n --thm-base: $base;\n --thm-base-rgb: $baseRgb;\n --thm-black: $black;\n --thm-black-rgb: $blackRgb;\n --thm-gray: $grey;\n}\n```\n\n### nuxt.config.js\n\n```\nexport default {\n mode: 'universal',\n loading: { color: '#fff' },\n css: [\n '~assets/scss/main.scss'\n ],\n plugins: [\n ],\n buildModules: [\n ],\n modules: [\n ],\n optimizedImages: {\n optimizeImages: true\n },\n build: {\n extend (config, ctx) {\n },\n loaders: {\n sass: {\n prependData: '@import \"~@/assets/scss/main.scss\";'\n }\n }\n },\n server: {\n port: process.env.APP_PORT\n }\n}\n```\n\n### package.json\n\n```\n{\n \"name\": \"zimed\",\n \"version\": \"1.1.0\",\n \"description\": \"Zimed - Vue Nuxt App Landing Page Template\",\n \"author\": \"Layerdrops\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"@bazzite/nuxt-optimized-images\": \"^0.3.0\",\n \"nuxt\": \"^2.0.0\",\n \"sass-loader\": \"10\"\n },\n \"devDependencies\": {\n \"fibers\": \"^5.0.0\",\n \"sass\": \"^1.38.2\"\n }\n}\n```\n\nWhich configuration am I missing so that `.scss` files get compiled?\n\n========================================\n\nCode:\n```text\n// Base colors\n$base: #ee464b;\n$baseRgb: (238, 70, 75);\n$black: #272839;\n$blackRgb: (39, 40, 57);\n$grey: #f4f4f8;\n\n// Typography\n$primaryTypography: 'Barlow', sans-serif;\n\n@debug $primaryTypography; // -> this one outputs the correct value\n\n:root {\n --thm-font: $primaryTypography;\n --thm-base: $base;\n --thm-base-rgb: $baseRgb;\n --thm-black: $black;\n --thm-black-rgb: $blackRgb;\n --thm-gray: $grey;\n}\n```\n\n```text\nexport default {\n mode: 'universal',\n loading: { color: '#fff' },\n css: [\n '~assets/scss/main.scss'\n ],\n plugins: [\n ],\n buildModules: [\n ],\n modules: [\n ],\n optimizedImages: {\n optimizeImages: true\n },\n build: {\n extend (config, ctx) {\n },\n loaders: {\n sass: {\n prependData: '@import \"~@/assets/scss/main.scss\";'\n }\n }\n },\n server: {\n port: process.env.APP_PORT\n }\n}\n```\n\n```text\n{\n \"name\": \"zimed\",\n \"version\": \"1.1.0\",\n \"description\": \"Zimed - Vue Nuxt App Landing Page Template\",\n \"author\": \"Layerdrops\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"@bazzite/nuxt-optimized-images\": \"^0.3.0\",\n \"nuxt\": \"^2.0.0\",\n \"sass-loader\": \"10\"\n },\n \"devDependencies\": {\n \"fibers\": \"^5.0.0\",\n \"sass\": \"^1.38.2\"\n }\n}\n```\n\n```text\nsass\n```\n\n```text\nscss\n```\n\n```text\n--thm-font\n```\n\n```text\n$primaryTypography\n```\n\n```text\n.scss\n```\n\n```text\n--thm-font: 'Barlow', sans-serif\n```\n\n```text\nsass\n```\n\n```text\nmain.scss\n```\n\n```text\n.scss\n```\n\n```text\n--thm-font: #{$primaryTypography};\n```\n\n```text\n:root\n```\n\n========================================\n\nComments:\n- Can you try the solution here: stackoverflow.com/a/68730454/8816585?\n- Btw `mode: 'universal'` is deprecated: stackoverflow.com/a/68272664/8816585\n- @kissu thanks for the answer. Unfortunately, it is not working. Still getting `$primaryFont` and not the actual value of the variable.\n- What if you try `--thm-font: #{$primaryTypography};`? Does it work in the component btw (for debuging purposes)?\n- @kissu doing `--thm-font: #{$primaryTypography};`. Any idea on why this is happening?\n- Not sure if you're missing a word here, I'll suppose that it works with it? I found it here: stackoverflow.com/a/52603882/8816585 Probably that `:root` does have some kind of specific context.\n- @kissu adding `body { background-color: $black; }` works. I guess that sass doesn't understand the variable expansion inside `:root` ?!\n- @kissu feel free to answer the question so I can accept your answer. Your idea lead me to the solution :)\n- Does this answer your question? Unable to set SCSS variable to CSS variable?\n- @null The pseudoclass `:root` has no influence on how SASS/SCSS resolves variables. But for css custom properties like `--foo` any value is a valid value and therefore `$some-color` is a valid string value for `--foo`. Hence explicit string interpolation has to be used with `--foo: #{$some-color};`","metadata":{"transformedAt":"2026-08-18T18:33:07.874Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":241,"estimatedTokens":1297}}524{"id":"stack-52491872","source":"stackoverflow","questionId":52491872,"title":"Is it possible to use Socket.io with NuxtJs?","tags":["socket.io","nuxt.js"],"text":"Title: Is it possible to use Socket.io with NuxtJs?\nTags: socket.io, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to use socket.io in my Nuxtjs. Is it possible?\n\nI tried this tutorial but I am getting the following error:\n\n```\nThese dependencies were not found:\n\n* fs in ./node_modules/socket.io/lib/index.js\n* uws in ./node_modules/engine.io/lib/server.js\n```\n\n========================================\n\nTop Answer:\n***Updated answer with linked example on GitHub***\n\nI would suggest to use the **`nuxt-socket-io` module**. It is really easy to set up and has a nice documentation.\n\nI built this litte demo example and I will list the steps that I took to build it (this is even a bit more thorough than the Setup section of the npm package):\n\nAdd nuxt-socket-io dependency to your project:\n\n`yarn add nuxt-socket-io # or npm install nuxt-socket-io`\n\n(If you already have a socket.io server you can skip this part)\n\nAdd following line to your `nuxt.config.js` file: `serverMiddleware: [ \"~/serverMiddleware/socket-io-server.js\" ]` (Please do not mix up serverMiddleware with middleware, this are two different things)\n\nThen, create the file `./serverMiddleware/socket-io-server.js` where you can implement your socket.io *server*.\n\n```\n// This file is executed once when the server is started\n\n// Setup a socket.io server on port 3001 that has CORS disabled\n// (do not set this to port 3000 as port 3000 is where\n// the nuxt dev server serves your nuxt application)\nconst io = require(\"socket.io\")(3001, {\n cors: {\n // No CORS at all\n origin: '*',\n }\n});\n\nvar i = 0;\n// Broadcast \"tick\" event every second\n// Or do whatever you want with io ;)\nsetInterval(() => {\n i++;\n io.emit(\"tick\", i);\n}, 1000);\n\n// Since we are a serverMiddleware, we have to return a handler,\n// even if this it does nothing\nexport default function (req, res, next) {\n next()\n}\n```\n\n(If you already have Vuex set up, you can skip this)\n\nAdd following empty Vuex store, i.e., create the file `./store/index.js`, since the module needs Vuex set up.\n\n```\nexport const state = () => ({})\n```\n\nAdd nuxt-socket-io to the modules section of `nuxt.config.js`, this will enable socket-io client:\n\n```\n{\n modules: [\n 'nuxt-socket-io',\n ],\n // socket.io configuration\n io: {\n // we could have multiple sockets that we identify with names\n // one of these sockets may have set \"default\" to true\n sockets: [{\n default: true, // make this the default socket\n name: 'main', // give it a name that we can later use to choose this socket in the .vue file\n url: 'http://localhost:3001' // URL wherever your socket IO server runs\n }]\n },\n}\n```\n\nUse it in your components:\n\n```\n{\n data() {\n return {\n latestTickId: 0,\n };\n },\n mounted() {\n const vm = this;\n\n // use \"main\" socket defined in nuxt.config.js\n vm.socket = this.$nuxtSocket({\n name: \"main\" // select \"main\" socket from nuxt.config.js - we could also skip this because \"main\" is the default socket\n });\n\n vm.socket.on(\"tick\", (tickId) => {\n vm.latestTickId = tickId;\n });\n },\n}\n```\n\nRun it with `npm run dev` and enjoy your tick events :)\n\nhttps://i.sstatic.net/dXbAs.gif\n\n========================================\n\nCode:\n```text\nThese dependencies were not found:\n\n* fs in ./node_modules/socket.io/lib/index.js\n* uws in ./node_modules/engine.io/lib/server.js\n```\n\n```js\nexport default {\n ...,\n serverMiddleware: [\n {path: '/ws', handler: '~/api/srv.js'},\n ],\n}\n```\n\n```js\nconst app = require('express')()\nconst socket = require('socket.io')\nlet server = null\nlet io = null\n\napp.all('/init', (req, res) => {\n if (!server) {\n server = res.connection.server\n io = socket(server)\n\n io.on('connection', function (socket) {\n console.log('Made socket connection');\n\n socket.on('msg', msg => {\n console.log('Recived: ' + msg)\n\n setTimeout(() => {\n socket.emit('msg', `Response to: ${msg}`)\n }, 1000)\n })\n\n socket.on('disconnect', () => console.log('disconnected'))\n })\n }\n\n res.json({ msg: 'server is set' })\n})\n\nmodule.exports = app\n```\n\n```html\n<template>\n <div class=\"container\">\n <input v-model=\"msg\">\n <button @click=\"socket.emit('msg', msg)\">send</button>\n <br/>\n <textarea v-model=\"resps\"></textarea>\n </div>\n</template>\n\n<script>\nexport default {\n head: {\n script: [\n {src: 'https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js'},\n ],\n },\n data () {\n return {\n socket: null,\n msg: 'wwJd',\n resps: '',\n }\n },\n mounted () {\n this.$axios.$get('/ws/init')\n .then(resp => {\n this.socket = io()\n this.socket.on('msg', msg => this.resps += `${msg}\\n`)\n })\n },\n}\n</script>\n```\n\n```text\nnpm i socket.io\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n/app/srv.js\n```\n\n```text\nres.connection.server\n```\n\n```text\npages/index.vue\n```\n\n```text\nnpm run dev\n```\n\n```js\n// This file is executed once when the server is started\n\n// Setup a socket.io server on port 3001 that has CORS disabled\n// (do not set this to port 3000 as port 3000 is where\n// the nuxt dev server serves your nuxt application)\nconst io = require(\"socket.io\")(3001, {\n cors: {\n // No CORS at all\n origin: '*',\n }\n});\n\nvar i = 0;\n// Broadcast \"tick\" event every second\n// Or do whatever you want with io ;)\nsetInterval(() => {\n i++;\n io.emit(\"tick\", i);\n}, 1000);\n\n// Since we are a serverMiddleware, we have to return a handler,\n// even if this it does nothing\nexport default function (req, res, next) {\n next()\n}\n```\n\n```js\nexport const state = () => ({})\n```\n\n```js\n{\n modules: [\n 'nuxt-socket-io',\n ],\n // socket.io configuration\n io: {\n // we could have multiple sockets that we identify with names\n // one of these sockets may have set \"default\" to true\n sockets: [{\n default: true, // make this the default socket\n name: 'main', // give it a name that we can later use to choose this socket in the .vue file\n url: 'http://localhost:3001' // URL wherever your socket IO server runs\n }]\n },\n}\n```\n\n```js\n{\n data() {\n return {\n latestTickId: 0,\n };\n },\n mounted() {\n const vm = this;\n\n // use \"main\" socket defined in nuxt.config.js\n vm.socket = this.$nuxtSocket({\n name: \"main\" // select \"main\" socket from nuxt.config.js - we could also skip this because \"main\" is the default socket\n });\n\n vm.socket.on(\"tick\", (tickId) => {\n vm.latestTickId = tickId;\n });\n },\n}\n```\n\n```text\nnuxt-socket-io\n```\n\n```text\nyarn add nuxt-socket-io # or npm install nuxt-socket-io\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nserverMiddleware: [ \"~/serverMiddleware/socket-io-server.js\" ]\n```\n\n```text\n./serverMiddleware/socket-io-server.js\n```\n\n```text\n./store/index.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnpm run dev\n```\n\n========================================\n\nComments:\n- which version of Node.js do you use? then can you the list of deps in your \"package.json\" file ?\n- Hi, I hope I'm not too late to the party but I decided to modularize that example, make it a bit more \"npm-friendly\" and push to the npm repo. I just authored nuxt-socket-io The idea is: just npm install it, configure sockets in nuxt.config, and just use it.\n- Hi @Markus I tried it but doesn't work, may I missed server.js ? please could you set all steps ? thanks\n- upvoted! could you kindly what your server file looks like?\n- Hello @BKF. My original answer did not include any server code. I updated my answer to show the complete client *and* server side.\n- Hello @PirateApp. I did not have access to the code anymore, but I used my Saturday to set up the following demo project and updated the answer accordingly. Hope this helps! github.com/NeonMika/nuxt-socket-io-demo","metadata":{"transformedAt":"2026-08-18T18:33:07.874Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":342,"estimatedTokens":1915}}525{"id":"stack-56233773","source":"stackoverflow","questionId":56233773,"title":"How to refetch user in Vuex with Nuxt Auth Module?","tags":["vuex","nuxt.js"],"text":"Title: How to refetch user in Vuex with Nuxt Auth Module?\nTags: vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nShort Question: Is it possible to update the user data in Vuex manually via the Nuxt Auth Module?\n\nWhy do I have that Question: My problem is this. I save some Likes/Follows in MongoDB in the user document. My authentication is realized with Nuxt Auth. Nuxt Auth stores my user document in Vuex on login.\n\nIf an user likes something now, it will be stored in the database, but I don't get it into the auth state of Nuxt Auth in Vuex.\n\nAn alternative (I thought) would be to change the data in Vuex the same way as in the database. But here I get problems with the \"Strict\" mode of Vuex.\n\nOne possibility that works for me would be to save the user data one more time in a separate state and always update it manually. But do I really have to save the user data several times in Vuex? Doesn't make sense to me.\n\n========================================\n\nCode:\n```text\nthis.$auth.fetchUser()\n```\n\n========================================\n\nComments:\n- This just refetches from your API endpoint; it doesn't populate a custom state.\n- But just that refetch from the API was my Question. Of course there are better ways. I only was for a quick and dirty solution.\n- Ok. You might want to rephrase your question in such case, eg: \"how to fetch user in Nuxt auth module\"","metadata":{"transformedAt":"2026-08-18T18:33:07.874Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":28,"estimatedTokens":344}}526{"id":"stack-57386325","source":"stackoverflow","questionId":57386325,"title":"What is the best way of using normalize.css in Nuxt.js projects?","tags":["nuxt.js","normalize-css"],"text":"Title: What is the best way of using normalize.css in Nuxt.js projects?\nTags: nuxt.js, normalize-css\nSource: Stack Overflow\n\nQuestion:\nI have scaffolded a new Nuxt.js project using `npx create-nuxt-app` command and used **Bulma** for UI framework.\nI learned that bulma.css file has been included in *nuxt.config.js* file with the following configuration.\n\n```\nmodules: [\n '@nuxtjs/bulma'\n]\n```\n\nBut then I want to use normalize.css to make sure the styles keep consistency in all browsers. To make this work properly, this normalize.css file should be included at the top of all css files.\n\nI have tried importing it in `layout/default.vue` file like this. (I referenced this)\n\n```\n\n @import '~/node_modules/normalize.css/normalize.css'\n\n```\n\nBut then I learned as I inspect on Chrome devtools that normalize.css file is actually included at the bottom.\n\nhttps://i.sstatic.net/aYfcJ.png\n\nThe style that is included before the normalize.css is *bulma.css*\n\nSo the question is: How can I properly import **normalize.css** in this Nuxt.js project so that it is imported/included at the top of the css file list?\n\n========================================\n\nCode:\n```text\nmodules: [\n '@nuxtjs/bulma'\n]\n```\n\n```text\n<style lang=\"scss\">\n @import '~/node_modules/normalize.css/normalize.css'\n</style>\n```\n\n```text\nnpx create-nuxt-app\n```\n\n```text\nlayout/default.vue\n```\n\n```text\ncss: [\n 'normalize.css/normalize.css'\n],\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- which folder did you put this css file inside, assets, or static?\n- I have installed normalize.css through npm command - `npm install normalize.css`","metadata":{"transformedAt":"2026-08-18T18:33:07.874Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":70,"estimatedTokens":412}}527{"id":"stack-53350264","source":"stackoverflow","questionId":53350264,"title":"Is it possible to deploy Nuxt SSR application on AWS?","tags":["amazon-web-services","nuxt.js"],"text":"Title: Is it possible to deploy Nuxt SSR application on AWS?\nTags: amazon-web-services, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm new to AWS. I can't find any explanation on how to deploy Nuxt SSR app on AWS although I could find ones on how to deploy static Nuxt app there. Is it possible to deploy Nuxt SSR app on AWS? I have spent long enough time already so please let me ask for your help. Thanks.\n\n========================================\n\nTop Answer:\nWhen it comes to AWS there are usually a few ways to skin a cat. I have however deployed a containerised SSR NUXT application with AWS CloudFront and AWS Fargate/ECS using AWS Copilot. AWS Amplify is great for static deployment.\n\nIf you are actually running the NUXT application in *ssr: true* (this is the default configuration) and/or *target: 'server'*, then you can't deploy it in the same way that you would deploy your usual 'static' web application (e.g. S3 hosting with AWS won't work with an SSR application). So if you run 'nuxt build' to build the application you will see a (hidden) .nuxt/ directory will be generated in your application directory. If you run 'nuxt generate' however, you will see a /dist folder in your application directory that isn't hidden. In the latter case, you are most likely not leveraging NUXT's SSR capabilities (check your *ssr* and *target* properties in your *nuxt.config.js* file to see if it is 'universal' and/or 'server' respectively, see docs on ssr here and target here) and could deploy to AWS S3 with CloudFront or with AWS Amplify.\n\nIn the case you are using SSR, then this tutorial from AWS is will help you to deploy a containerised version of your app to AWS ECS.\n\nUPDATE: I spoke to AWS this week who advised that AWS Amplify now supports container deployment, so you could dockerise the application and deploy it there quite easily.\n\n========================================\n\nComments:\n- Hi bwest! Thank you for your answer! Your link really helped me although I haven't been able to deploy to AWS as I encountered another problem. But thank you very much!\n- I am glad it helped!\n- I wrote tutorial on AWS Amplify details if anybody is interested kodius.com/blog/nuxt-ssr-on-amplify\n- dont recommend using lambda for this unless you know how to workaround cold start that the server experiences","metadata":{"transformedAt":"2026-08-18T18:33:07.875Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":25,"estimatedTokens":579}}528{"id":"stack-66730445","source":"stackoverflow","questionId":66730445,"title":"Avoid Mutating Props Directly in a Nuxt VueJs","tags":["javascript","vue.js","vuejs2","nuxt.js","vuetify.js"],"text":"Title: Avoid Mutating Props Directly in a Nuxt VueJs\nTags: javascript, vue.js, vuejs2, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nSo I see a lot of posts about this issue but I can't wrap my head as to why I am doing wrong here. I have a form that I place in a component. It's mostly made up of TextFields using vuetify. I am then reusing this form somewhere else. I've tried different things but I am still getting the error, here is my component.\n\n```\n\n \n \n \n \n \n \n \n\n \n \n \n\n \n \n \n \n \n \n\nexport default {\n props: {\n modalFirstNameValue: {\n },\n modalLastNameValue:{\n\n },\n modalEmailValue:{\n\n },\n\n```\n\nImport Component\n\n```\n\n \n \n \n\nimport FormModal from \"~/components/FormModal\";\nexport default {\n name: 'app',\n components: {\n FormModal,\n },\n\n data(){\n return{\n modalEmailLabel : 'Email',\n modalEmailValue : '',\n modalLastNameLabel : 'Last Name',\n modalLastNameValue : '',\n modalFirstNameLabel : 'First Name',\n }\n }\n}\n\n```\n\nWhen I try to write in one of the text fields I get the error of avoiding mutating props, not sure I understand what is causing this. I'd like to not have this error and do best practice here. Any suggestions?\n\n========================================\n\nCode:\n```text\n<v-window continuous v-model=\"step\">\n <v-window-item :value=\"1\">\n <v-form>\n <v-container>\n <v-row>\n <v-col\n cols=\"12\"\n md=\"4\"\n >\n <v-text-field\n label=\"First name\"\n required\n autocomplete=\"off\"\n clearable\n\n v-model=\"modalFirstNameValue\"\n\n ></v-text-field>\n </v-col>\n\n <v-col\n cols=\"12\"\n md=\"4\"\n >\n <v-text-field\n label=\"Last name\"\n required\n autocomplete=\"off\"\n clearable\n\n v-model=\"modalLastNameValue\"\n\n ></v-text-field>\n </v-col>\n\n <v-col\n cols=\"12\"\n md=\"4\"\n >\n <v-text-field\n label=\"E-mail\"\n required\n autocomplete=\"off\"\n clearable\n v-model=\"modalEmailValue\"\n ></v-text-field>\n </v-col>\n </v-container>\n </v-form>\n </v-window-item>\n<script>\nexport default {\n props: {\n modalFirstNameValue: {\n },\n modalLastNameValue:{\n\n },\n modalEmailValue:{\n\n },\n</script>\n```\n\n```text\n<template>\n <div id=\"app\">\n <FormModal\n v-show=\"isModalVisible\"\n @close=\"closeModal\"\n modalTitle=\"Book Appointment Form\"\n v-bind:modalFirstNameValue=\"modalFirstNameValue\"\n v-bind:modalFirstNameLabel=\"modalFirstNameLabel\"\n v-bind:modalLastNameValue=\"modalLastNameValue\"\n v-bind:modalLastNameLabel=\"modalLastNameLabel\"\n v-bind:modalEmailValue=\"modalEmailValue\"\n v-bind:modalEmailLabel=\"modalEmailLabel\"\n />\n </div>\n</template>\n\n<script>\nimport FormModal from \"~/components/FormModal\";\nexport default {\n name: 'app',\n components: {\n FormModal,\n },\n\n data(){\n return{\n modalEmailLabel : 'Email',\n modalEmailValue : '',\n modalLastNameLabel : 'Last Name',\n modalLastNameValue : '',\n modalFirstNameLabel : 'First Name',\n }\n }\n}\n</script>\n```\n\n```text\nv-model\n```\n\n```text\nv-model\n```\n\n```text\n@input\n```\n\n```text\n:value\n```\n\n```text\nv-model\n```\n\n```text\nv-model\n```\n\n========================================\n\nComments:\n- `props` are used as initial value (like query parameters). There is only one-way databinding from parent to child so that's why you recieve warning (modifying in child). If you want to mutate some data, use `data()` instead.\n- @bigless thank you, can you give me an example?\n- Just join it into one component without props.","metadata":{"transformedAt":"2026-08-18T18:33:07.875Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":207,"estimatedTokens":1153}}529{"id":"stack-48606325","source":"stackoverflow","questionId":48606325,"title":"How to resize images for different responsive views?","tags":["image-resizing","nuxt.js"],"text":"Title: How to resize images for different responsive views?\nTags: image-resizing, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI created a site with nuxt.js and bootstrap. For the responsive views i need to create different image sizes. Nuxt.js can't resize images. How do you do this?\n\n========================================\n\nTop Answer:\nIf you don't want to rely on webpack for responsively loading images, you may want to try this nuxt module: https://github.com/reallifedigital/nuxt-image-loader-module\n\nThe downside to this module is that it doesn't currently support `srcset` natively and requires a local installation of the Graphicsmagick library. The upside is that anything that's available in Graphicsmagick (image manipulation wise) can be used to process your images. Also, you can implement your own image `srcset` from following the instructions and implementing your image tag like this:\n\n```\n\n```\n\nYou should be able to implement any responsive image this way.\n\nFor our responsive views in nuxt, such as a 'feed' of latest content, we wanted to use smaller images from what was being used on the main articles, so this module does exactly what we need it to.\n\nDisclosure: I wrote this module to solve our particular responsive requirement which, given the original poster's description, sounds like there's a lot of overlap.\n\n========================================\n\nCode:\n```js\nbuild: {\n /*\n ** Run ESLint on save\n */\n extend (config, { isDev, isClient }) {\n\n // Default block\n if (isDev && isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n // Default block end\n\n\n // here I tell webpack not to include jpgs and pngs\n // as base64 as an inline image\n config.module.rules.find(\n rule => rule.loader === \"url-loader\"\n ).exclude = /\\.(jpe?g|png)$/;\n\n // now i configure the responsive-loader\n config.module.rules.push({\n test: /\\.(jpe?g|png)$/i,\n loader: 'responsive-loader',\n options: {\n min: 575,\n max: 1140,\n steps: 7,\n placeholder: false,\n quality: 60,\n adapter: require(\"responsive-loader/sharp\")\n }\n })\n\n }\n}\n```\n\n```text\n<img :src=\"require('~/assets/images/Foo.jpg?size=400')\" :srcset=\"require('~/assets/images/Foo.jpg').srcSet\">\n```\n\n```text\nresponsive-loader\n```\n\n```text\nsharp\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nbuild: {}\n```\n\n```text\nsrcSet\n```\n\n```text\nresponsive-loader\n```\n\n```text\n<img src=\"image.png\" srcset=\"image-1x.png?style=1x 1x, image-2x.png?style=2x 2x alt=\"\" />\n```\n\n```text\nsrcset\n```\n\n```text\nsrcset\n```\n\n========================================\n\nComments:\n- thanks for the answer. Do you use nuxt with responsive-loader?\n- hehe, at the moment, i can't get it to run. I will keep trying.\n- Quick update: The `nuxt-image-loader-module` now supports `srcset` for responsive images. Enjoy!","metadata":{"transformedAt":"2026-08-18T18:33:07.875Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":116,"estimatedTokens":750}}530{"id":"stack-75794580","source":"stackoverflow","questionId":75794580,"title":"Nuxt 3 (nuxt generate) change static output directory?","tags":["vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: Nuxt 3 (nuxt generate) change static output directory?\nTags: vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nNuxt 2 we were able to specify the output directory:\n\n```\nexport default {\n target: 'static',\n\n generate: {\n dir: 'build/_site',\n },\n}\n```\n\nNow I'm using Nuxt 3 and cannot figure out how to specify the output directory when running generate. Was the generate support removed?\n\n========================================\n\nCode:\n```text\nexport default {\n target: 'static',\n\n generate: {\n dir: 'build/_site',\n },\n}\n```\n\n```text\nconst path = require('path');\n\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n ...\n nitro: {\n output: {\n publicDir: path.join(__dirname, 'your path here')\n }\n },\n ...\n}\n```\n\n```text\nnuxt.config.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.875Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":50,"estimatedTokens":206}}531{"id":"stack-61717198","source":"stackoverflow","questionId":61717198,"title":"Nuxt Auth Two Local Endpoints","tags":["vue.js","nuxt.js"],"text":"Title: Nuxt Auth Two Local Endpoints\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI would like to make two local endpoints as following: \n\n```\nstrategies: {\n localOne: {\n endpoints: {\n login: { url: \"token/\", method: \"post\", propertyName: \"access\" },\n user: { url: \"user/me/\", method: \"get\", propertyName: false },\n logout: false,\n }\n },\n localTwo: {\n endpoints: {\n login: { url: \"user/token/\", method: \"post\", propertyName: \"access\" },\n user: { url: \"user/me/\", method: \"get\", propertyName: false },\n logout: false,\n }\n }\n},\n```\n\nBut I am having the following issue in the console\n\n```\nclient.js?06a0:77 TypeError: Cannot read property 'mounted' of undefined\nat Auth.mounted (auth.js?facc:112)\nat Auth.setStrategy (auth.js?facc:108)\nat Auth.loginWith (auth.js?facc:123)\nat _callee3$ (log-in.vue?f35c:175)\nat tryCatch (runtime.js?96cf:45)\nat Generator.invoke [as _invoke] (runtime.js?96cf:271)\nat Generator.prototype. [as next] (runtime.js?96cf:97)\nat asyncGeneratorStep (asyncToGenerator.js?1da1:3)\nat _next (asyncToGenerator.js?1da1:25)\nat eval (asyncToGenerator.js?1da1:32)\n```\n\nHow can I make two endpoints for two different auth in nuxt js? Thank you in advance\n\n========================================\n\nCode:\n```text\nstrategies: {\n localOne: {\n endpoints: {\n login: { url: \"token/\", method: \"post\", propertyName: \"access\" },\n user: { url: \"user/me/\", method: \"get\", propertyName: false },\n logout: false,\n }\n },\n localTwo: {\n endpoints: {\n login: { url: \"user/token/\", method: \"post\", propertyName: \"access\" },\n user: { url: \"user/me/\", method: \"get\", propertyName: false },\n logout: false,\n }\n }\n},\n```\n\n```text\nclient.js?06a0:77 TypeError: Cannot read property 'mounted' of undefined\nat Auth.mounted (auth.js?facc:112)\nat Auth.setStrategy (auth.js?facc:108)\nat Auth.loginWith (auth.js?facc:123)\nat _callee3$ (log-in.vue?f35c:175)\nat tryCatch (runtime.js?96cf:45)\nat Generator.invoke [as _invoke] (runtime.js?96cf:271)\nat Generator.prototype.<computed> [as next] (runtime.js?96cf:97)\nat asyncGeneratorStep (asyncToGenerator.js?1da1:3)\nat _next (asyncToGenerator.js?1da1:25)\nat eval (asyncToGenerator.js?1da1:32)\n```\n\n```text\nthis.$axios.post('user/token/', {\n id : res.data.id,\n firstname: res.data.firstname,\n lastname : res.data.lastname,\n email: res.data.email\n })\n .then((resp) => {\n this.$auth.setToken('local', 'Bearer ' + resp.data.access)\n this.$axios.setHeader('Authorization', 'Bearer ' + resp.data.access)\n this.$auth.ctx.app.$axios.setHeader('Authorization', 'Bearer ' + resp.data.access)\n })\n .then(() => {\n this.$axios.get('user/me/')\n .then((resp) => { \n this.$auth.setUser(resp.data); \n this.$router.push('/') \n })\n .catch(() => {\n console.log(err)\n })\n```\n\n========================================\n\nComments:\n- When i refresh the page, or make any request with $auth, it still doesnt use the token. i'm not user why\n- i finally figured why. Thank you! your answer saved my code\n- Thank You a lot !!!! I had the same issue with two strategies and the new one didn't work","metadata":{"transformedAt":"2026-08-18T18:33:07.875Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":109,"estimatedTokens":815}}532{"id":"stack-74573830","source":"stackoverflow","questionId":74573830,"title":"NuxtJs - how to check useFetch response code?","tags":["nuxt.js","response","httpresponse","nuxt3.js"],"text":"Title: NuxtJs - how to check useFetch response code?\nTags: nuxt.js, response, httpresponse, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nHow can I check response status code when using NuxtJs `useFetch`?\n\nCurrently I'm handling response as follows, but I cannot find anywhere how to get the exact response status code, only an error message e.g. `FetchError: 403 Forbidden`.\n\n```\nuseFetch(url, options).then(\n (res) => {\n const data = res.data.value;\n const error = res.error.value;\n\n if (error) {\n console.error(error);\n // handle error\n } else {\n console.log(data);\n // handle success\n }\n },\n (error) => {\n console.error(error);\n }\n);\n```\n\n========================================\n\nTop Answer:\nThe following way is better if you want to do something in the script part (set sepcific message etc)\n\n```\nawait useFetch(URL, {\n onResponse({request, response, options}) {\n // Process the response data\n if (response.status === 200) {\n //your code\n }\n },\n onResponseError({request, response, options}) {\n \n if (response.status === 400) {\n //your code\n } else {\n //your code\n }\n router.push(\"/\")\n },\n });\n```\n\n========================================\n\nCode:\n```js\nuseFetch(url, options).then(\n (res) => {\n const data = res.data.value;\n const error = res.error.value;\n\n if (error) {\n console.error(error);\n // handle error\n } else {\n console.log(data);\n // handle success\n }\n },\n (error) => {\n console.error(error);\n }\n);\n```\n\n```text\nuseFetch\n```\n\n```text\nFetchError: 403 Forbidden\n```\n\n```text\n<template>\n <div>\n error : {{ error.statusCode }}\n </div>\n</template>\n\n<script setup>\nconst { data, pending, error, refresh } = await useFetch(\"https://api.nuxtjs.dev/mountais\",\n { pick: [\"title\"] }\n);\nconsole.log(error.value.statusCode);\n</script>\n```\n\n```text\nerror.statusCode\n```\n\n```text\nerror.value.statusCode\n```\n\n```text\nerror\n```\n\n```text\nawait useFetch(URL, {\n onResponse({request, response, options}) {\n // Process the response data\n if (response.status === 200) {\n //your code\n }\n },\n onResponseError({request, response, options}) {\n \n if (response.status === 400) {\n //your code\n } else {\n //your code\n }\n router.push(\"/\")\n },\n });\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.875Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":131,"estimatedTokens":600}}533{"id":"stack-64218232","source":"stackoverflow","questionId":64218232,"title":"Vuex action \"not a function\" inside Nuxt fetch","tags":["vue.js","vuex","nuxt.js"],"text":"Title: Vuex action \"not a function\" inside Nuxt fetch\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have just introduced error handling to one of my Nuxt pages and apparently the action mapped and called inside `fetch` raises a *not a function* error. If the `try`/`catch` block isn't there it works as expected and there's no error at all.\n\nHere is my component stripped to the essential parts:\n\n```\nexport default {\n name: 'ViewArticle',\n async fetch ({ error }) {\n try {\n await this.fetchArticle({ articleSlug: this.articleSlug })\n } catch (err) {\n error({ statusCode: 404, message: 'May the force be with you' })\n }\n },\n computed: {\n ...mapGetters({\n article: 'article/single'\n }),\n articleSlug () {\n return this.$route.params.articleSlug\n }\n },\n methods: {\n ...mapActions({\n fetchArticle: 'article/fetchOne'\n })\n }\n}\n```\n\nI am assuming that somehow mapActions only gets executed later in the spiel, but can't figure out how to prevent the error. This way, basically every time I load the page it gets immediately redirected to the error page.\n\nThe error message I'm getting is the following. Obviously `fetchArticle` *is* a function, and unless it's inside the `try`/`catch` block, it works as expected.\n\n```\nthis.fetchArticle is not a function 03:30:51\n\n at Object.fetch (52.js:32:18)\n at server.js:2881:39\n at Array.map ()\n at module.exports../.nuxt/server.js.__webpack_exports__.default (server.js:2864:51)\n```\n\n========================================\n\nTop Answer:\nUse `async fetch({store})`\n\n```\nasync fetch ({ error, store }) {\n try {\n await store.dispatch( 'article/fetchOne' , { articleSlug: this.articleSlug })\n } catch (err) {\n error({ statusCode: 404, message: 'May the force be with you' })\n }\n```\n\n========================================\n\nCode:\n```js\nexport default {\n name: 'ViewArticle',\n async fetch ({ error }) {\n try {\n await this.fetchArticle({ articleSlug: this.articleSlug })\n } catch (err) {\n error({ statusCode: 404, message: 'May the force be with you' })\n }\n },\n computed: {\n ...mapGetters({\n article: 'article/single'\n }),\n articleSlug () {\n return this.$route.params.articleSlug\n }\n },\n methods: {\n ...mapActions({\n fetchArticle: 'article/fetchOne'\n })\n }\n}\n```\n\n```text\nthis.fetchArticle is not a function 03:30:51\n\n at Object.fetch (52.js:32:18)\n at server.js:2881:39\n at Array.map (<anonymous>)\n at module.exports../.nuxt/server.js.__webpack_exports__.default (server.js:2864:51)\n```\n\n```text\nfetch\n```\n\n```text\ntry\n```\n\n```text\ncatch\n```\n\n```text\nfetchArticle\n```\n\n```text\ntry\n```\n\n```text\ncatch\n```\n\n```text\nfetch(context)\n```\n\n```text\nfetch(context) {\n let store = context.store;\n}\n```\n\n```text\nfetch({ store }) {}\n```\n\n```text\nasync fetch ({ error, store }) {\n try {\n await store.dispatch('article/fetchOne', { articleSlug: this.articleSlug })\n } catch (err) {\n error({ statusCode: 404, message: 'May the force be with you' })\n }\n },\n```\n\n```text\ncontext\n```\n\n```text\nis not an function\n```\n\n```text\nasync fetch ({ error, store }) {\n try {\n await store.dispatch( 'article/fetchOne' , { articleSlug: this.articleSlug })\n } catch (err) {\n error({ statusCode: 404, message: 'May the force be with you' })\n }\n```\n\n```text\nasync fetch({store})\n```\n\n========================================\n\nComments:\n- What is the exact error message, please\n- @Phil just updated my question with it\n- what version of Nuxt you are using?","metadata":{"transformedAt":"2026-08-18T18:33:07.875Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":175,"estimatedTokens":897}}534{"id":"stack-75321567","source":"stackoverflow","questionId":75321567,"title":"Nuxt3: How to set runtime environment variables after docker build via process.env","tags":["node.js","docker","vue.js","environment-variables","nuxt.js"],"text":"Title: Nuxt3: How to set runtime environment variables after docker build via process.env\nTags: node.js, docker, vue.js, environment-variables, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nMy nuxt3 app works great if I build & run it locally with docker-compose and environment variables.\n\nBut when I push the built docker image to my remote production environment I'm not able to apply the production environment variables in the runtimeConfig. Probably because process.env[\"SECRET_KEY\"] gets replaced with \"the real secret key\" during the build phase.\n\nIf I name environment variables NUXT_PUBLIC_XXXX / NUXT_XXXX, I'm able to update runtimeConfig even after building the image.\n\nBut as I use a PaaS Service for my production deployment, I am not in control of the variable naming. Therefore I'm unable to dynamically provide the right runtime config for my remote environment -> *I always end up with the local values which were set during the build phase on my local machine.* (see clientID in example below)\n\n**Is there a way how to set the runtime config via process.env[\"custom env name\"] even after the image was built?** Or do you have any other idea how to dynamically provide the runtime config? (I'd like to avoid building separate containers for each environment\n\nThx a lot for your inputs. Any help is highly appreciated!\n\n```\n#nuxt.config.ts\n...\nruntimeConfig: {\n\n#in production ENVs are accessible under the key \"VCAP_SERVICES\", if key is not present the local development env is applied\nclientId: process.env[\"VCAP_SERVICES\"] ? process.env[\"VCAP_SERVICES\"][\"clientId\"] : process.env[\"UAA_CLIENT_ID\"],\nsecretKey: process.env[\"NUXT_SECRET_KEY\"]\n\n public: {\n backendApi: 'http://127.0.0.1:5000', // will be overridden by NUXT_PUBLIC_BACKEND_API environment variable\n environment: \"production\", // will be overridden by NUXT_PUBLIC_ENVIRONMENT environment variable\n }\n },\n```\n\n========================================\n\nTop Answer:\n### Not exactly the answer to the actual question\n\nThis is for those who require a read variable from Environment instead of the `.env` file\n\nthe comment describes how you should read each key\n\n```\nruntimeConfig: {\n abcXyz: process.env.abcXyz, // Environmnet can override via: `NUXT_ABC_XYZ`\n\n LMN_OPQ: process.env.LMN_OPQ, // Environmnet can override via: `NUXT_LMN_OPQ`\n\n public: {\n abcXyz: process.env.abcXyz // Environmnet can override via: `NUXT_PUBLIC_ABC_XYZ`\n },\n}\n```\n\nIll then define the environment variable using `docker-compose.yml`\n\n```\nservices:\n api:\n image: xyz-api:latest\n container_name: xyz.api\n ports: \n - \"7002:443\"\n\n app:\n image: xyz-app:latest\n container_name: xyz.app\n environment: #internal port\n - NUXT_PUBLIC_ABC_XYZ=https://localhost:7002/api\n```\n\n========================================\n\nCode:\n```text\n#nuxt.config.ts\n...\nruntimeConfig: {\n\n#in production ENVs are accessible under the key \"VCAP_SERVICES\", if key is not present the local development env is applied\nclientId: process.env[\"VCAP_SERVICES\"] ? process.env[\"VCAP_SERVICES\"][\"clientId\"] : process.env[\"UAA_CLIENT_ID\"],\nsecretKey: process.env[\"NUXT_SECRET_KEY\"]\n\n public: {\n backendApi: 'http://127.0.0.1:5000', // will be overridden by NUXT_PUBLIC_BACKEND_API environment variable\n environment: \"production\", // will be overridden by NUXT_PUBLIC_ENVIRONMENT environment variable\n }\n },\n```\n\n```js\nruntimeConfig: {\n abcXyz: process.env.abcXyz, // Environmnet can override via: `NUXT_ABC_XYZ`\n\n LMN_OPQ: process.env.LMN_OPQ, // Environmnet can override via: `NUXT_LMN_OPQ`\n\n public: {\n abcXyz: process.env.abcXyz // Environmnet can override via: `NUXT_PUBLIC_ABC_XYZ`\n },\n}\n```\n\n```yaml\nservices:\n api:\n image: xyz-api:latest\n container_name: xyz.api\n ports: \n - \"7002:443\"\n\n app:\n image: xyz-app:latest\n container_name: xyz.app\n environment: #internal port\n - NUXT_PUBLIC_ABC_XYZ=https://localhost:7002/api\n```\n\n```text\n.env\n```\n\n```text\ndocker-compose.yml\n```\n\n========================================\n\nComments:\n- Which PaaS Service are you using? Your env vars names are dynamically generated on each deploy on this platform?\n- I'm using cloud foundry. As services like a database are added to my app, a new key-value pair is added to the ENV named VCAP_SERVICES with a predefined & service specific structure (I would know how to access each value upfront e.g process.env[\"VCAP_SERVICES\"][DatabaseServices][0][DB_User]. See docs.cloudfoundry.org/devguide/deploy-apps/…\n- Maybe you're getting your env var VCPA_SERVICES as a string. You could try to parse that string as a JSON in order to get your \"clientId\" as you do. E.g `JSON.parse(process.env[\"VCAP_SERVICES\"])[\"clientId\"]`\n- How do you inject the env and overwrite the in docker? I'm not able to achieve this stackoverflow.com/questions/75970917/…. Any help appriciated\n- @Vikkes: I updated the answer with a better explanation of the nuxt runtime config","metadata":{"transformedAt":"2026-08-18T18:33:07.875Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":133,"estimatedTokens":1229}}535{"id":"stack-74054152","source":"stackoverflow","questionId":74054152,"title":"Nuxt 3 file upload and store in locally in the project","tags":["file-upload","nuxt.js","vuejs3","multipartform-data"],"text":"Title: Nuxt 3 file upload and store in locally in the project\nTags: file-upload, nuxt.js, vuejs3, multipartform-data\nSource: Stack Overflow\n\nQuestion:\nI want to create a simple Nuxt 3 file upload implementation that stores the file in the locally in a folder in the Nuxt project. In PHP the server side code is very easy and straight forward but I am finding it difficult doing the same thing in Nuxt 3 server side.\n\n========================================\n\nTop Answer:\n**First:**\n\n`npm install formidable`\n\n**second:**\n\ndefine formidable in **Nuxt config** file inside modules list.\n\n```\nexport default defineNuxtConfig({\nmodules: [\"formidable\"],\n});\n```\n\nthen in your handler for example upload.post.js :\n\n```\nimport formidable from \"formidable\";\nimport fs from \"fs\";\nimport path from \"path\";\n\nexport default defineEventHandler(async (event) => {\n let imageUrl = \"\";\n let oldPath = \"\";\n let newPath = \"\";\n\n const form = formidable({ multiples: true });\n const data = await new Promise((resolve, reject) => {\n form.parse(event.req, (err, fields, files) => {\n if (err) {\n reject(err);\n }\n if (!files.photo) {\n resolve({\n status: \"error\",\n message: \"Please upload a photo with name photo in the form\",\n });\n }\n if (files.photo.mimetype.startsWith(\"image/\")) {\n let imageName =\n Date.now() +\n Math.round(Math.random() * 100000) +\n files.photo.originalFilename;\n oldPath = files.photo.filepath;\n newPath = `${path.join(\"public\", \"uploads\", imageName)}`;\n imageUrl = \"./public/upload/\" + imageName;\n fs.copyFileSync(oldPath, newPath);\n resolve({\n status: \"ok\",\n url: imageUrl,\n });\n } else {\n resolve({\n status: \"error\",\n message: \"Please upload nothing but images.\",\n });\n }\n });\n });\n return data;\n});\n```\n\ndon't forget to name the input field \"photo\" in the client side or change it here in every \"files.photo\".\nALso the path of uploaded photos will be in public/uploads directory you can change it too if you like in \"path.join\" method.\nGood luck\n\n========================================\n\nCode:\n```text\nimport { readFiles } from 'h3-formidable';\nimport fs from \"fs\";\nimport path from \"path\";\n\nexport default defineEventHandler(async (event) => {\n const { files: { photo: [ { filepath, mimetype } ] } } = await readFiles(event, {\n includeFields: true\n });\n\n let imageName = String(Date.now()) + String(Math.round(Math.random() * 10000000));\n let newPath = `${path.join(\"public\", \"uploads\", imageName)}.${ mimetype.split('/')[1] }`;\n fs.copyFileSync(filepath, newPath);\n\n return { success: true }\n});\n```\n\n```js\nexport default defineNuxtConfig({\nmodules: [\"formidable\"],\n});\n```\n\n```js\nimport formidable from \"formidable\";\nimport fs from \"fs\";\nimport path from \"path\";\n\nexport default defineEventHandler(async (event) => {\n let imageUrl = \"\";\n let oldPath = \"\";\n let newPath = \"\";\n\n const form = formidable({ multiples: true });\n const data = await new Promise((resolve, reject) => {\n form.parse(event.req, (err, fields, files) => {\n if (err) {\n reject(err);\n }\n if (!files.photo) {\n resolve({\n status: \"error\",\n message: \"Please upload a photo with name photo in the form\",\n });\n }\n if (files.photo.mimetype.startsWith(\"image/\")) {\n let imageName =\n Date.now() +\n Math.round(Math.random() * 100000) +\n files.photo.originalFilename;\n oldPath = files.photo.filepath;\n newPath = `${path.join(\"public\", \"uploads\", imageName)}`;\n imageUrl = \"./public/upload/\" + imageName;\n fs.copyFileSync(oldPath, newPath);\n resolve({\n status: \"ok\",\n url: imageUrl,\n });\n } else {\n resolve({\n status: \"error\",\n message: \"Please upload nothing but images.\",\n });\n }\n });\n });\n return data;\n});\n```\n\n```text\nnpm install formidable\n```\n\n```text\n//server/api/index.post.js\nimport { MediasModel } from \"./../../models/Medias.model\";\nimport { readFiles } from \"h3-formidable\";\nimport { firstValues } from \"h3-formidable/helpers\";\nimport fs from \"fs\";\nimport path from \"path\";\n\nexport default defineEventHandler(async (event) => {\n // create media directory if it doesn't exist\n if (!fs.existsSync(\"public/uploads\")) {\n fs.mkdirSync(path.join(\"public\", \"uploads\"));\n }\n\n const { fields, form, files } = await readFiles(event, {\n includeFields: true,\n multiples: true,\n maxFiles: 10,\n maxFilesSize: 5 * 1024 * 1024,\n maxFields: 8,\n filter: function ({ name, originalFilename, mimetype }) {\n // keep only images and pdf's\n return (\n mimetype && (mimetype.includes(\"image\") || mimetype.includes(\"pdf\"))\n );\n },\n });\n\n // Gets first values of fields\n const exceptions = [\"thisshouldbeanarray\"];\n const fieldsSingle = firstValues(form, fields, exceptions);\n\n const name = fieldsSingle.name;\n let value = files.value || fieldsSingle.value;\n const tag = fieldsSingle.tag;\n const type = fieldsSingle.type;\n\n // Save media archive\n let listFiles = [];\n if (files.value) {\n for (const file of files.value) {\n const fileName = `${Date.now()}-${file.newFilename}-${\n file.mimetype.split(\"/\")[1]\n }`;\n const newPath = `${path.join(\"public\", \"uploads\", fileName)}`;\n fs.copyFileSync(file.filepath, newPath);\n listFiles.push(fileName);\n }\n value = listFiles;\n }\n\n // Create new media in model\n const media = await MediasModel.create({\n name,\n value,\n tag,\n type,\n });\n});\n```\n\n```text\nimport path from 'path'\nimport fs from 'fs'\n\nexport default defineEventHandler(async (event) => {\n const files = await readMultipartFormData(event)\n\n const uploadedFilePaths: string[] = []\n\n files?.forEach((file) => {\n const filePath = path.join(\n process.cwd(),\n 'public',\n file.filename as string,\n )\n fs.writeFileSync(filePath, file.data)\n uploadedFilePaths.push(`/${file.filename}`)\n })\n\n return uploadedFilePaths\n})\n```\n\n```text\nupload.post.ts\n```\n\n```text\n/server/api\n```\n\n========================================\n\nComments:\n- In Nuxt, it's as easy. Check a tutorial on how to achieve that with Node.js or provide more effort regarding what you already tried.\n- event.req is depreciated in nuxt 3.\n- @Horizon try `event.node.req`.\n- how can I associate this code with additional fields appended, and run mongodb queries?\n- Have you tested it in production? It does not work for me\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- It won't work in production!!!\n- What's the problem?\n- Look Here github.com/nuxt/nuxt/issues/15779 and github.com/unjs/nitro/issues/992\n- I found that readMultipartFormData() was failing silently. Then I uninstalled h3-formidable and everything started working correctly. Weird","metadata":{"transformedAt":"2026-08-18T18:33:07.875Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":260,"estimatedTokens":1745}}536{"id":"stack-59067585","source":"stackoverflow","questionId":59067585,"title":"How to send a request from Nuxt.js client over Nuxt.js server and receive the response back to the client","tags":["vue.js","axios","nuxt.js"],"text":"Title: How to send a request from Nuxt.js client over Nuxt.js server and receive the response back to the client\nTags: vue.js, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm developing a Vue.js application which has only frontend (no server) and send a lot of requests to different APIs. The originally quite simple app became more complex. And there are problems with some APIs, because browsers do not accept the responses due to CORS. That is why I'm trying to test, if I can migrate the app to Nuxt.js.\n\nMy approach is as follows (inspired by this comment), but I expect, that there is probably a better way to send the requests from the client over the server.\n\npages/test-page.vue\n\n```\nmethods: {\n async sendRequest(testData) {\n const response = await axios.post('api', testData)\n // Here can I use the response on the page.\n }\n}\n```\n\nnuxt.config.js\n\n```\nserverMiddleware: [\n { path: '/api', handler: '~/server-middleware/postRequestHandler.js' }\n],\n```\n\nserver-middleware/postRequestHandler.js\n\n```\nimport axios from 'axios'\n\nconst configs = require('../store/config.js')\n\nmodule.exports = function(req, res, next) {\n let body = ''\n\n req.on('data', (data) => {\n body += data\n })\n\n req.on('end', async () => {\n if (req.hasOwnProperty('originalUrl') && req.originalUrl === '/api') {\n const parsedBody = JSON.parse(body)\n\n // Send the request from the server.\n const response = await axios.post(\n configs.state().testUrl,\n body\n )\n\n req.body = response\n }\n next()\n })\n}\n```\n\nmiddleware/test.js (see: API: The Context)\n\n```\nexport default function(context) {\n // Universal keys\n const { store } = context\n // Server-side\n if (process.server) {\n const { req } = context\n store.body = req.body\n }\n}\n```\n\npages/api.vue\n\n```\n\n {{ body }}\n\nexport default {\n middleware: 'test',\n computed: {\n body() {\n return this.$store.body\n }\n }\n}\n\n```\n\nWhen the user makes an action on the page \"test\", which will initiate the method \"sendRequest()\", then the request \"axios.post('api', testData)\" will result in a response, which contains the HTML code of the page \"api\". I can then extract the JSON \"body\" from the HTML.\n\nI find the final step as suboptimal, but I have no idea, how can I send just the JSON and not the whole page. But I suppose, that there must be a much better way to get the data to the client.\n\n========================================\n\nTop Answer:\nNow with nuxtjs3 :\n\nnuxtjs3 rc release\n\n- you have fetch or useFetch no need to import axios or other libs, what is great, automatic parsing of body, automatic detection of head\n\nfetching data\n\n- you have middleware and server api on same application, you can add headers on queries, hide for example token etc\n\nserver layer\n\na quick example here in vue file i call server api :\n\n```\nconst { status } = await $fetch.raw( '/api/newsletter', { method: \"POST\", body: this.form.email } )\n .then( (response) => ({\n status: response.status,\n }) )\n .catch( (error) => ({\n status: error?.response?.status || 500,\n }) );\n```\n\nit will call a method on my server, to init the server on root directory i created a folder name server then api, and a file name newsletter.ts (i use typescript)\nthen in this file :\n\n```\nexport default defineEventHandler(async (event) => {\nconst {REST_API, MAILINGLIST_UNID, MAILINGLIST_TOKEN} = useRuntimeConfig();\nconst subscriber = await readBody(event);\nconsole.log(\"url used for rest call\" + REST_API);\nconsole.log(\"token\" + MAILINGLIST_TOKEN);\nconsole.log(\"mailing list unid\" + MAILINGLIST_UNID);\nlet recipientWebDTO = {\n email: subscriber,\n subscriptions: [{\n \"mailingListUnid\": MAILINGLIST_UNID\n }]\n};\nconst {status} = await $fetch.raw(REST_API, {\n method: \"POST\",\n body: recipientWebDTO,\n headers: {\n Authorization: MAILINGLIST_TOKEN,\n },\n}).then((response) => ({\n status: response.status,\n}))\n .catch((error) => ({\n status: error?.response?.status || 500,\n }));\nevent.res.statusCode = status;\nreturn \"\";\n})\n```\n\nWhat are the benefits ?\n\nREST_API,MAILING_LIST_UNID, MAILING_LIST_TOKEN are not exposed on\nclient and even file newsletter.ts is not available on debug browser.\n\nYou can add log only on server side You event not expose api url to avoid some attacks\n\nYou don't have to create a new backend just to hide some criticals token or datas\n\nthen it is up to you to choose middleware route or server api. You don't have to import new libs, h3 is embedded via nitro with nuxtjs3 and fetch with vuejs3\n\nfor proxy you have also sendProxy offered by h3 : sendProxy H3\n\nWhen you build in dev server and client build in same time(and nothing to implement or configure in config file), and with build to o, just don deploy your project in static way (but i think you can deploy front in static and server in node i don't know)\n\n========================================\n\nCode:\n```text\nmethods: {\n async sendRequest(testData) {\n const response = await axios.post('api', testData)\n // Here can I use the response on the page.\n }\n}\n```\n\n```text\nserverMiddleware: [\n { path: '/api', handler: '~/server-middleware/postRequestHandler.js' }\n],\n```\n\n```text\nimport axios from 'axios'\n\nconst configs = require('../store/config.js')\n\nmodule.exports = function(req, res, next) {\n let body = ''\n\n req.on('data', (data) => {\n body += data\n })\n\n req.on('end', async () => {\n if (req.hasOwnProperty('originalUrl') && req.originalUrl === '/api') {\n const parsedBody = JSON.parse(body)\n\n // Send the request from the server.\n const response = await axios.post(\n configs.state().testUrl,\n body\n )\n\n req.body = response\n }\n next()\n })\n}\n```\n\n```text\nexport default function(context) {\n // Universal keys\n const { store } = context\n // Server-side\n if (process.server) {\n const { req } = context\n store.body = req.body\n }\n}\n```\n\n```text\n<template>\n {{ body }}\n</template>\n<script>\nexport default {\n middleware: 'test',\n computed: {\n body() {\n return this.$store.body\n }\n }\n}\n</script>\n```\n\n```text\nmodule.exports = {\n...\n modules: [\n '@nuxtjs/axios',\n '@nuxtjs/proxy'\n ],\n proxy: {\n '/proxy/packagist-search/': {\n target: 'https://packagist.org',\n pathRewrite: {\n '^/proxy/packagist-search/': '/search.json?q='\n },\n changeOrigin: true\n }\n },\n ...\n}\n```\n\n```text\naxios\n .get('/proxy/packagist-search/' + this.search.phpLibrary.searchPhrase)\n .then((response) => {\n console.log(\n 'Could get the values packagist.org',\n response.data\n )\n }\n })\n .catch((e) => {\n console.log(\n 'Could not get the values from packagist.org',\n e\n )\n })\n```\n\n```text\n...\napp.post('/api/confluence', confluence.send)\napp.use(nuxt.render)\n...\n```\n\n```text\nconst axios = require('axios')\nconst config = require('../nuxt.config.js')\n\nexports.send = function(req, res) {\n let body = ''\n let page = {}\n\n req.on('data', (data) => {\n body += data\n })\n\n req.on('end', async () => {\n const parsedBody = JSON.parse(body)\n try {\n page = await axios.get(\n config.api.confluence.url.api + ...,\n config.api.confluence.auth\n )\n } catch (e) {\n console.log('ERROR: ', e)\n }\n }\n\n res.json({\n page\n })\n}\n```\n\n```text\nthis.$axios\n .post('api/confluence', postData)\n .then((response) => {\n console.log('Wiki response: ', response.data)\n })\n .catch((e) => {\n console.log('Could not update the wiki page. ', e)\n })\n```\n\n```text\nconst { status } = await $fetch.raw( '/api/newsletter', { method: \"POST\", body: this.form.email } )\n .then( (response) => ({\n status: response.status,\n }) )\n .catch( (error) => ({\n status: error?.response?.status || 500,\n }) );\n```\n\n```text\nexport default defineEventHandler(async (event) => {\nconst {REST_API, MAILINGLIST_UNID, MAILINGLIST_TOKEN} = useRuntimeConfig();\nconst subscriber = await readBody(event);\nconsole.log(\"url used for rest call\" + REST_API);\nconsole.log(\"token\" + MAILINGLIST_TOKEN);\nconsole.log(\"mailing list unid\" + MAILINGLIST_UNID);\nlet recipientWebDTO = {\n email: subscriber,\n subscriptions: [{\n \"mailingListUnid\": MAILINGLIST_UNID\n }]\n};\nconst {status} = await $fetch.raw(REST_API, {\n method: \"POST\",\n body: recipientWebDTO,\n headers: {\n Authorization: MAILINGLIST_TOKEN,\n },\n}).then((response) => ({\n status: response.status,\n}))\n .catch((error) => ({\n status: error?.response?.status || 500,\n }));\nevent.res.statusCode = status;\nreturn \"\";\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.875Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":369,"estimatedTokens":2110}}537{"id":"stack-54173320","source":"stackoverflow","questionId":54173320,"title":"Firestore User Management Best Practices?","tags":["firebase","vue.js","firebase-authentication","nuxt.js"],"text":"Title: Firestore User Management Best Practices?\nTags: firebase, vue.js, firebase-authentication, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSo I'm developing a web app using Firestore and Nuxt, and while I got the authentication working I would like to ensure I am following best practices.\n\nUsing Firebase Authentication only gives me an identifier (email in this case) and an UID. Then I created a user collection to store additional data such as:\n\n```\n{\n \"UID\": \"6TIupYLKlcOE97b5Fe63uinf6Ik1\",\n \"app_metadata\": {\n \"role\": \"admin\",\n \"status\": \"approved\"\n },\n \"firstName\": \"Jon\",\n \"lastName\": \"Doe\"\n}\n```\n\nCurrently I am doing the following after user is authenticated to get the user's role:\n\n```\n// Getting user details\ndb.collection('users')\n.where('UID', '==', user.uid)\n.limit(1)\n.get()\n.then((snapshot) => {\n snapshot.forEach(doc => {\n console.log(doc.id, '=>', doc.data().app_metadata.role)\n dispatch('setROLE', doc.data().app_metadata.role)\n })\n})\n.catch((err) => {\n console.log('Error getting documents', err);\n})\n```\n\nIs there a better way to handle storing additional user data and tie it all together with Firebase Authentication?\n\n========================================\n\nTop Answer:\nA more conventional way is to use the UID as the ID of the document. This lets you find the document simply by saying:\n\n```\ndb.collection('users').doc(uid).get() // either 0 or 1 document\n```\n\nThis is easier than having to do a query and having to perform a query with a limit. When what you have now, what happens if 'users' accidentally gets two document for a particular uid?\n\n========================================\n\nCode:\n```text\n{\n \"UID\": \"6TIupYLKlcOE97b5Fe63uinf6Ik1\",\n \"app_metadata\": {\n \"role\": \"admin\",\n \"status\": \"approved\"\n },\n \"firstName\": \"Jon\",\n \"lastName\": \"Doe\"\n}\n```\n\n```text\n// Getting user details\ndb.collection('users')\n.where('UID', '==', user.uid)\n.limit(1)\n.get()\n.then((snapshot) => {\n snapshot.forEach(doc => {\n console.log(doc.id, '=>', doc.data().app_metadata.role)\n dispatch('setROLE', doc.data().app_metadata.role)\n })\n})\n.catch((err) => {\n console.log('Error getting documents', err);\n})\n```\n\n```text\nusers\n```\n\n```text\nfirebase.auth().currentUser.uid\n```\n\n```text\nfirebase.auth().currentUser\n```\n\n```text\n.onAuthStateChanged\n```\n\n```text\nfirebase.firestore().collection('users').doc(firebase.auth().currentUser.uid).update({age:25})\n```\n\n```text\n.onSnapshot\n```\n\n```text\nuserDocument\n```\n\n```text\nuserDocument = userDoc\n```\n\n```text\nuserDoc\n```\n\n```text\nuserDocument\n```\n\n```text\nusers\n```\n\n```text\nfirebase.auth()\n```\n\n```text\ndb.collection('users').doc(uid).get() // either 0 or 1 document\n```\n\n========================================\n\nComments:\n- You may have a look at savvyapps.com/blog/…\n- is this still a best practice in 2021 ? If so, can you provide a code example? I am using Nuxt/Vue, if that helps. Thanks for the interesting perspective!","metadata":{"transformedAt":"2026-08-18T18:33:07.875Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":142,"estimatedTokens":729}}538{"id":"stack-56882507","source":"stackoverflow","questionId":56882507,"title":"Custom 404 Page using Nuxt generate working only in dev mode","tags":["javascript","webpack","nuxt.js"],"text":"Title: Custom 404 Page using Nuxt generate working only in dev mode\nTags: javascript, webpack, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have an `error.vue` page inside the `layouts` folder.\n\nWhen I'm on development mode accessing the site throughout localhost, if I reach a page with the wrong name the 404 page shows up but when I'm in production I can't see that page. Instead, another page appears:\n\nhttps://i.sstatic.net/OO4P0.png\n\nHere is the code:\n\n```\n\n \n \n \n \n \n \n \n \n\n### Oops!\n\n \n\n### The page you are looking for is not found.\n\n \n \n \n \n\nexport default {\n props: ['error'],\n data() {\n return {\n }\n }\n}\n\n .light-grey{\n color: #4f4f4f;\n }\n\n```\n\nNuxt version: 2.8.1\n\nFollowing this https://nuxtjs.org/guide/views/\n\nAm I missing something?\n\n========================================\n\nCode:\n```text\n<template>\n <v-app>\n <v-container>\n <v-layout row wrap align-center justify-center fill-height>\n <v-flex xs12 sm12 md6>\n <v-img\n :src=\"require('@/assets/images/404.svg')\"\n width=\"90%\"\n ></v-img>\n </v-flex>\n <v-flex xs12 sm12 md6 class=\"mb-5\">\n <h1 class=\"display-4 light-grey font-weight-medium text-xs-center text-sm-center text-md-left mb-3\">Oops!</h1>\n <h1 class=\"display-3 light-grey font-weight-medium text-xs-center text-sm-center text-md-left\">The page you are looking for is not found.</h1>\n </v-flex>\n </v-layout>\n </v-container>\n </v-app>\n</template>\n\n<script>\nexport default {\n props: ['error'],\n data() {\n return {\n }\n }\n}\n</script>\n\n<style scoped>\n .light-grey{\n color: #4f4f4f;\n }\n</style>\n```\n\n```text\nerror.vue\n```\n\n```text\nlayouts\n```\n\n========================================\n\nComments:\n- Thanks for your answer. I was missing the `generate: { fallback: '404.html' },` / `generate: { fallback: true },` on `nuxt.config`. It does generate a `404.html` page on my `dist` folder but not the one I created.","metadata":{"transformedAt":"2026-08-18T18:33:07.875Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":107,"estimatedTokens":486}}539{"id":"stack-74888503","source":"stackoverflow","questionId":74888503,"title":"How to add a typeorm in nuxt 3","tags":["orm","nuxt.js","typeorm","nuxt3.js"],"text":"Title: How to add a typeorm in nuxt 3\nTags: orm, nuxt.js, typeorm, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI create an typeorm ESM project by running the command\n\nnpx typeorm init --name MyProject --database sqlite--module esm\n\nas explained on https://typeorm.io. Running the project, everything works fine.\nThen I create a nuxt 3 project: \"npx nuxi init nuxt-project\". Then I supplement the contents of the package.json and tsconfig.json files in the nuxt project with the appropriate typeorm values.\n\n```\npackage.json:\n {\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\",\n \"postinstall\": \"nuxt prepare\",\n \"start\": \"node --loader ts-node/esm src/index.ts\",\n \"typeorm\": \"typeorm-ts-node-esm\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^18.11.17\",\n \"nuxt\": \"3.0.0\",\n \"ts-node\": \"10.9.1\",\n \"typescript\": \"4.9.4\"\n },\n \"dependencies\": {\n \"@npmcli/fs\": \"^3.1.0\",\n \"reflect-metadata\": \"^0.1.13\",\n \"sqlite3\": \"^5.1.4\",\n \"typeorm\": \"^0.3.11\"\n }\n }\ntsconfig.json:\n {\n // https://nuxt.com/docs/guide/concepts/typescript\n \"extends\": \"./.nuxt/tsconfig.json\",\n \"compilerOptions\": {\n \"lib\": [\n \"es2021\"\n ],\n \"target\": \"es2021\",\n \"module\": \"es2022\",\n \"moduleResolution\": \"node\",\n \"allowSyntheticDefaultImports\": true,\n \"outDir\": \"./build\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"sourceMap\": true\n }\n }\n```\n\nI copy the entity, the configured data-source, the base and add code to the App.vue.\n\n```\n\nimport \"reflect-metadata\"\nimport { User } from \"./db/entity/User.js\"\nimport { AppDataSource } from \"./db/data-source\";\n\nAppDataSource.initialize().then(async () => {\n const user = new User()\n user.firstName = \"Timber\"\n user.lastName = \"Saw\"\n user.age = 25\n await AppDataSource.manager.save(user)\n const users = await AppDataSource.manager.find(User)\n console.log(\"Loaded users: \", users)\n}).catch(error => console.log(error))\n\n \n \n \n\n```\n\nI run a nuxt project and get an error:\n\n[nuxt] [request error] [unhandled] [500] Column type for\nUser#firstName is not defined and cannot be guessed. Make sure you\nhave turned on an \"emitDecoratorMetadata\": true option in\ntsconfig.json. Also make sure you have imported \"reflect-metadata\" on\ntop of the main entry file in your application (before any entity\nimported).If you are using JavaScript instead of TypeScript you must\nexplicitly provide a column type.\n\nJust in case, I add import reflect-metadata before the entity, but the error doesn't go away. I wonder if there is a good wizard who will guide me to the right path?\n\nBy the way, before that I tried to work with Sequelize, and also failed. It didn't fail on reflect-metadata, but:\n\n```\nCould not resolve \"pg-hstore\": const hstore = require(\"pg-hstore\")\n```\n\nAny orm will work for me (that allows working with oracle, so Prisma is unfortunately out of the question). Any advice or an example?\n\n========================================\n\nCode:\n```text\npackage.json:\n {\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\",\n \"postinstall\": \"nuxt prepare\",\n \"start\": \"node --loader ts-node/esm src/index.ts\",\n \"typeorm\": \"typeorm-ts-node-esm\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^18.11.17\",\n \"nuxt\": \"3.0.0\",\n \"ts-node\": \"10.9.1\",\n \"typescript\": \"4.9.4\"\n },\n \"dependencies\": {\n \"@npmcli/fs\": \"^3.1.0\",\n \"reflect-metadata\": \"^0.1.13\",\n \"sqlite3\": \"^5.1.4\",\n \"typeorm\": \"^0.3.11\"\n }\n }\ntsconfig.json:\n {\n // https://nuxt.com/docs/guide/concepts/typescript\n \"extends\": \"./.nuxt/tsconfig.json\",\n \"compilerOptions\": {\n \"lib\": [\n \"es2021\"\n ],\n \"target\": \"es2021\",\n \"module\": \"es2022\",\n \"moduleResolution\": \"node\",\n \"allowSyntheticDefaultImports\": true,\n \"outDir\": \"./build\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"sourceMap\": true\n }\n }\n```\n\n```text\n<script setup lang=\"ts\">\nimport \"reflect-metadata\"\nimport { User } from \"./db/entity/User.js\"\nimport { AppDataSource } from \"./db/data-source\";\n\nAppDataSource.initialize().then(async () => {\n const user = new User()\n user.firstName = \"Timber\"\n user.lastName = \"Saw\"\n user.age = 25\n await AppDataSource.manager.save(user)\n const users = await AppDataSource.manager.find(User)\n console.log(\"Loaded users: \", users)\n}).catch(error => console.log(error))\n</script>\n<template>\n <div>\n <NuxtWelcome />\n </div>\n</template>\n```\n\n```text\nCould not resolve \"pg-hstore\": const hstore = require(\"pg-hstore\")\n```\n\n```text\n@Column('text',{nullable:true})\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.875Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":181,"estimatedTokens":1200}}540{"id":"stack-73395032","source":"stackoverflow","questionId":73395032,"title":"Aspect-ratio elements overflow container","tags":["vue.js","nuxt.js","tailwind-css","aspect-ratio"],"text":"Title: Aspect-ratio elements overflow container\nTags: vue.js, nuxt.js, tailwind-css, aspect-ratio\nSource: Stack Overflow\n\nQuestion:\nI want to contain two `16:9` video elements vertically within a wrapper. I want that the elements respect the bounds of the wrapper and resize responsively to the window while maintaining their aspect ratio. When I have more than one element, it overflows the wrapper. In version 3 of TailwindCSS, the new aspect ratio classes work fine. I am using the `@tailwindcss/aspect-ratio@0.4.0` tailwind plugin.\n\nhttps://codesandbox.io/s/aspect-ratio-tailwind-error-slbobj?file=/pages/index.vue\n\n```\n\n \n \n \n \n top bar\n \n\n \n \n \n \n \n \n \n \n \n \n \n\n \n \n bottom bar\n \n \n \n \n```\n\nhttps://i.sstatic.net/ufQdT.png\n\nWhat I want is:\n\nhttps://i.sstatic.net/kxYKQ.jpg\n\npackage\nversion\n\ntailwindcss\n2.2.15\n\n@tailwindcss/aspect-ratio\n0.4.0\n\n========================================\n\nCode:\n```html\n<div class=\"flex flex-col min-h-screen\">\n <main class=\"flex-1 flex bg-gray-900 max-h-screen text-white\">\n <div class=\"flex-1 flex flex-col min-h-0 max-h-full\">\n <!-- header -->\n <div class=\"flex-shink-0 flex items-center justify-between p-6\">\n top bar\n </div>\n\n <!-- content -->\n <div class=\"flex-1 w-full max-w-[1200px] min-h-0 max-h-full mx-auto p-6 bg-green-500\">\n <!-- video 1 -->\n <div class=\"aspect-w-16 aspect-h-9\">\n <div class=\"w-full h-full bg-yellow-500\"></div>\n </div>\n <!-- video 2 -->\n <div class=\"aspect-w-16 aspect-h-9\">\n <div class=\"w-full h-full bg-red-500\"></div>\n </div>\n </div>\n\n <!-- footer -->\n <div class=\"flex-shink-0 flex items-center justify-between p-6\">\n bottom bar\n </div>\n </div>\n </main>\n </div>\n```\n\n```text\n16:9\n```\n\n```text\n@tailwindcss/aspect-ratio@0.4.0\n```\n\n```html\n<script src=\"https://unpkg.com/tailwindcss-jit-cdn\"></script>\n\n<div class=\"flex flex-col min-h-screen\">\n <main class=\"flex-1 flex bg-gray-900 max-h-screen text-white\">\n <div class=\"flex-1 flex flex-col min-h-0 max-h-full\">\n <!-- header -->\n <div class=\"flex-shink-0 flex items-center justify-between p-6\">top bar</div>\n\n <!-- content -->\n <div class=\"flex-1 w-full max-w-[calc(100vh-300px)] min-h-0 max-h-full mx-auto p-6 bg-green-500\">\n <!-- video 1 -->\n <div class=\"aspect-w-16 aspect-h-9\">\n <div class=\"w-full h-full bg-yellow-500\"></div>\n </div>\n <!-- video 2 -->\n <div class=\"aspect-w-16 aspect-h-9\">\n <div class=\"w-full h-full bg-red-500\"></div>\n </div>\n </div>\n\n <!-- footer -->\n <div class=\"flex-shink-0 flex items-center justify-between p-6\">bottom bar</div>\n </div>\n </main>\n</div>\n```\n\n```text\nmax-w-[1200px]\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.875Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":126,"estimatedTokens":703}}541{"id":"stack-66896108","source":"stackoverflow","questionId":66896108,"title":"Nuxt.js - Add two layouts in page","tags":["vue.js","nuxt.js","vue-router"],"text":"Title: Nuxt.js - Add two layouts in page\nTags: vue.js, nuxt.js, vue-router\nSource: Stack Overflow\n\nQuestion:\nI am a beginner in **Nuxt.js** and I am converting a project of Vue to Nuxt.js and I wanted to use two layouts (the default one and another) on one page. The logic is this:\nThe first layout is the (default) or header which is on all pages and the second layout is the **settings bar**.\n\nIn **settings** page i have 3 routes (see project structure here: image):\n\n- settings/avatar\n\n- settings/account\n\n- settings/about\n\nI want the **Settings bar** to be the same for three routes. I can add the Settings bar to all three child pages like: `layout: 'settings-bar'` but then could not set the Header layout. In my Vue project i only used in settings page: Settings bar component and below `` to change the components. Any idea how i can do this? in docs can not find anything. See other screenshots here to better understand: \n\nhttps://i.sstatic.net/Axk95.png\n\n========================================\n\nTop Answer:\nIt is actually doable to have nested layouts in Nuxt, meanwhile: it's a bit hacky and hard to read and I'm not sure that I may recommend it at a bigger scale. Tried it, do not recommend but if it's really needed, here is the solution.\n\n`layouts/default.vue`\n\n```\n\n \n \n \n \n\n```\n\n`layouts/newLayout.vue`\n\n```\n\n \n \n\n### Surrounding layout\n\n \n \n\nimport DefaultLayout from '~/layouts/default.vue';\n\nexport default {\n components: {\n DefaultLayout\n }\n}\n\n```\n\nThen, you can use it anywhere with\n\n```\n\nexport default {\n layout: 'newLayout' // name of your new layout\n}\n\n```\n\nKudos to this article: https://constantsolutions.dk/2020/02/nested-layouts-in-nuxt-vue-js/\n\nNot sure, but the article itself may be from this github post: https://github.com/nuxt/nuxt.js/issues/785#issuecomment-422365721\n\n========================================\n\nCode:\n```text\nlayout: 'settings-bar'\n```\n\n```text\n<router-view></router-view>\n```\n\n```html\n<template>\n <div>\n <nuxt v-if=\"!$slots.default\" />\n <slot />\n </div>\n</template>\n```\n\n```html\n<template>\n <default-layout>\n <h1>Surrounding layout</h1>\n <nuxt />\n </default-layout>\n</template>\n\n<script>\nimport DefaultLayout from '~/layouts/default.vue';\n\nexport default {\n components: {\n DefaultLayout\n }\n}\n</script>\n```\n\n```html\n<script>\nexport default {\n layout: 'newLayout' // name of your new layout\n}\n</script>\n```\n\n```text\nlayouts/default.vue\n```\n\n```text\nlayouts/newLayout.vue\n```\n\n========================================\n\nComments:\n- Thanks for helping, I managed to fix it somehow, folders structure: link & putting `` in settings.vue\n- This is a matter of ordering. Layouts contain pages, pages contain components. So it doesn't make sense to have multiple layouts in a single page: *there aren't **ever** any layouts in a page*, instead the pages are inside the layout. As answer suggests, check out components.\n- It is doable, check my answer for the *how*.\n- This will cause `default-layout` to re-render each time there is a transitions between routes with different \"child\" layouts. I was wondering if it's possible in Nuxt to have a wrapper layout w/o re-renders, e.g. for global components as notifications list, header with user info etc\n- At the end, using a simple component is probably simpler and more clean. Nesting layouts is kinda a hack anyway. @markoffden","metadata":{"transformedAt":"2026-08-18T18:33:07.876Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":135,"estimatedTokens":837}}542{"id":"stack-68741697","source":"stackoverflow","questionId":68741697,"title":"How can I style the first element of a v-for in vue?","tags":["javascript","vue.js","vuejs2","nuxt.js"],"text":"Title: How can I style the first element of a v-for in vue?\nTags: javascript, vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to set an `active` class just to first button in this code:\n\n```\n\n {{ item.question }} \n\n```\n\nIt means than when the page is loaded, if 4 buttons were in it, first of them should have `optional-red-outlined-btn` class and `active` class but others just have `optional-red-outlined-btn` class.\n\nof course but i want when click on other button remove active of first button ,I use it for just one button have active style button:focus{ background-color: $optional-red; color: #fff; } but i want in default first button have this style\n\n========================================\n\nTop Answer:\nI am pretty sure your `btnIndex` variable has 0 value by default.\nSo you can apply conditional class\n\n```\n:class=\"btnIndex == index ?'active':''\"\n```\n\n========================================\n\nCode:\n```html\n<button\n class='optional-red-outlined-btn'\n v-for=\"(item, index) in faq\"\n :key=\"item._id\"\n @click=\"btnIndex = index\"\n>\n {{ item.question }} \n</button>\n```\n\n```text\nactive\n```\n\n```text\noptional-red-outlined-btn\n```\n\n```text\nactive\n```\n\n```text\noptional-red-outlined-btn\n```\n\n```html\n:class=\"{ active: index === 0 }\"\n```\n\n```text\nbutton.special {\n color: blue\n}\nbutton.special:first {\n color: red\n}\n```\n\n```text\n:class=\"btnIndex == index ?'active':''\"\n```\n\n```text\nbtnIndex\n```\n\n========================================\n\nComments:\n- Take a look here\n- vuejs.org/v2/guide/class-and-style.html#Object-Syntax\n- of course but i want when click on other button remove active of first button\n- I use it for just one button have active style button:focus{ background-color: $optional-red; color: #fff; } but i want in default first button have this style\n- @faezeh if you have other conditions, just add them next to the index, for example `index === 0 && buttonNotClickedYet`.\n- what `buttonNotClickedYet` means?\n- @faezeh it could be a computed that is triggered once you have once clicked on your button. Or any condition really.\n- of course but i want when click on other button remove active of first button ,I use it for just one button have active style button:focus{ background-color: $optional-red; color: #fff; } but i want in default first button have this style\n- Ok I've updated my answer. Please see it.","metadata":{"transformedAt":"2026-08-18T18:33:07.876Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":90,"estimatedTokens":588}}543{"id":"stack-75667222","source":"stackoverflow","questionId":75667222,"title":"NuxtJS nested routes with param","tags":["nuxt.js","nuxt3.js","nuxtjs2"],"text":"Title: NuxtJS nested routes with param\nTags: nuxt.js, nuxt3.js, nuxtjs2\nSource: Stack Overflow\n\nQuestion:\n`https://dev.site.io/websites/1bbe6526-61c1-4077-8400-77a642580eac/apps/30620171-af2f-4e82-854e-2bb797c017d8`\n\nwhat would the folder structure look like to access both website and app id in:\n\n`https://dev.site.io/websites/1bbe6526-61c1-4077-8400-77a642580eac/apps/30620171-af2f-4e82-854e-2bb797c017d8/overview`\n\ncannot getting nested routes working at all\n\n========================================\n\nCode:\n```text\nhttps://dev.site.io/websites/1bbe6526-61c1-4077-8400-77a642580eac/apps/30620171-af2f-4e82-854e-2bb797c017d8\n```\n\n```text\nhttps://dev.site.io/websites/1bbe6526-61c1-4077-8400-77a642580eac/apps/30620171-af2f-4e82-854e-2bb797c017d8/overview\n```\n\n```text\n- pages\n - index.vue // This is the home page\n - websites.vue - // NuxtPage\n - website // FOLDER\n - index.vue // Websites page content\n - [id].vue // NuxtPage - for Dynamic content based on the ID \n - [id] // FOLDER\n - index.vue // Dynamic ID content\n - apps.vue // Nuxtpage\n - apps // FOLDER\n - index.vue // Apps page content\n - [id].vue // NuxtPage - for Dynamic content based on the ID\n - [id] // FOLDER\n - index // Dynamic ID content\n - overview.vue // NuxtPage\n - overview // FOLDER\n - index // Overview page content\n```\n\n========================================\n\nComments:\n- Does this help? nuxt.com/docs/guide/directory-structure/pages#example\n- This works; helped a lot! Scouring the web, this is the only deep-nesting-dynamic-routes sample I could find for Nuxt3. Downside: this can get annoying to navigate in an IDE file tree view. For a larger project I may disable Nuxt's file-based routing and revert to manually defined route files (as done previously in a large Nuxt2 app).\n- I love you so much! Thanks a lot 💚\n- May God bless the author's soul.\n- There is a video tutorial from basic page routing to advance dynamic nested routes youtube.com/watch?v=ccqIAvriVVo","metadata":{"transformedAt":"2026-08-18T18:33:07.876Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":52,"estimatedTokens":509}}544{"id":"stack-54992618","source":"stackoverflow","questionId":54992618,"title":"get route params in asyncData after router push","tags":["vuejs2","vue-router","nuxt.js"],"text":"Title: get route params in asyncData after router push\nTags: vuejs2, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get the route params in the asyncData method, it works if I go manually to the route, but if I use router Push method, it doesn't get any params.\n\nthis is my asynData method:\n\n```\nasync asyncData(ctx) {\n const { id } = ctx.app.router.currentRoute.params\n await ctx.store.dispatch('user/GET_USER', id)\n return {\n user: ctx.store.state.user.user\n }\n },\n```\n\nand this is how I navigate to the respective page:\n\n```\ngoToEdit(id) {\n this.$router.push({ path: `/users/${id}/edit` })\n}\n```\n\n========================================\n\nTop Answer:\nI'm doing it in a similar way but I retrieve params and almost everything from `context`.\n\n```\nasync asyncData(context) {\n const plans = await context.$axios.get(\"business/get-plans\", {\n params: {\n currency: context.query.currency\n }\n }).then((res) => {\n return res.data;\n });\n```\n\nTake a look to `context.$axios` and `context.query`.\n\n========================================\n\nCode:\n```text\nasync asyncData(ctx) {\n const { id } = ctx.app.router.currentRoute.params\n await ctx.store.dispatch('user/GET_USER', id)\n return {\n user: ctx.store.state.user.user\n }\n },\n```\n\n```text\ngoToEdit(id) {\n this.$router.push({ path: `/users/${id}/edit` })\n}\n```\n\n```text\nasync asyncData({ route }) {\n const { id } = route.params\n await ctx.store.dispatch('user/GET_USER', id)\n return {\n user: ctx.store.state.user.user\n }\n},\n```\n\n```text\nasync asyncData(context) {\n const plans = await context.$axios.get(\"business/get-plans\", {\n params: {\n currency: context.query.currency\n }\n }).then((res) => {\n return res.data;\n });\n```\n\n```text\ncontext\n```\n\n```text\ncontext.$axios\n```\n\n```text\ncontext.query\n```\n\n========================================\n\nComments:\n- What do you get if you `console.log(ctx)` can you see the params?\n- it returns the context with the params of the previous route.","metadata":{"transformedAt":"2026-08-18T18:33:07.876Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":102,"estimatedTokens":513}}545{"id":"stack-67539820","source":"stackoverflow","questionId":67539820,"title":"HeadlessUI/vue: TypeError vue.defineComponent is not a function","tags":["typescript","vue.js","vuejs2","nuxt.js","tailwind-css"],"text":"Title: HeadlessUI/vue: TypeError vue.defineComponent is not a function\nTags: typescript, vue.js, vuejs2, nuxt.js, tailwind-css\nSource: Stack Overflow\n\nQuestion:\nI try to install `@headlessui/vue` in my `nuxt` project.\n\nWhen I try to use it like:\n\n```\n\n \n \n Item\n \n \n\nimport Vue from 'vue'\nimport { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/vue'\n\nexport default Vue.extend({\n components: { Menu, MenuButton, MenuItems, MenuItem },\n data () {\n return {\n isScrolling: false\n }\n },\n....\n```\n\nI get a type error while compiling\n\n```\nTypeError\nvue.defineComponent is not a function\n```\n\n========================================\n\nCode:\n```html\n<template>\n <Menu>\n <MenuItems>\n <MenuItem>Item</MenuItem>\n </MenuItems>\n </Menu>\n</template>\n\n<script lang=\"ts\">\nimport Vue from 'vue'\nimport { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/vue'\n\nexport default Vue.extend({\n components: { Menu, MenuButton, MenuItems, MenuItem },\n data () {\n return {\n isScrolling: false\n }\n },\n....\n```\n\n```text\nTypeError\nvue.defineComponent is not a function\n```\n\n```text\n@headlessui/vue\n```\n\n```text\nnuxt\n```\n\n========================================\n\nComments:\n- The library stated that it only supports vue3 while nuxt is still using vue 2.6.12 npmjs.com/package/@headlessui/vue\n- Hi, this has been around for a while, but I'm still getting this error with Nuxt. Is there a way to fix? I'm using chartjs vue wrapper with Nuxt and getting this error\n- @CornelVerster this is unrelated to HeadlessUI. I've answered you on your own question.","metadata":{"transformedAt":"2026-08-18T18:33:07.876Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":82,"estimatedTokens":393}}546{"id":"stack-63441665","source":"stackoverflow","questionId":63441665,"title":"How to access plugin from nuxt.js store?","tags":["javascript","vue.js","vuex","nuxt.js","gtag.js"],"text":"Title: How to access plugin from nuxt.js store?\nTags: javascript, vue.js, vuex, nuxt.js, gtag.js\nSource: Stack Overflow\n\nQuestion:\nI have this gtag (analytics plugin) that I can access on my components but never on my store.\nI would appreciate any opinions. Thanks\n\nplugins/vue-gtag.js\n\n```\nimport Vue from \"vue\"\nimport VueGtag from \"vue-gtag\"\n\nexport default ({ app }, inject) => {\n Vue.use(VueGtag, {\n config: {\n id: process.env.ga_stream_id\n }\n })\n}\n```\n\nstore/gaUserProperty.js\n\n```\nimport Vue from \"vue\"\nimport { User } from \"~/models/user/User\"\n\nexport const states = () => ({})\n\nconst getterObjects = {}\nconst mutationObjects = {}\nObject.keys(states).forEach(key => {\n getterObjects[key] = state => state[key]\n mutationObjects[key] = (state, value) => (state[key] = value)\n})\n\nexport const state = () => states\n\nexport const getters = { ...getterObjects }\n\nexport const mutations = { ...mutationObjects }\n\nexport const actions = {\n async sendUserProperties({ dispatch, commit }) {\n let res = await this.$UserApi.getUser()\n if (!(res instanceof User)) {\n } else {\n // I can access this on my components and pages but for some reason not here....\n console.log(this.$gtag)\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nYou can access the Vue instance through `this._vm` in the Vuex store, so you would just need to do:\n\n```\nconsole.log(this._vm.$gtag)\n```\n\nThat should do the trick.\n\n========================================\n\nCode:\n```text\nimport Vue from \"vue\"\nimport VueGtag from \"vue-gtag\"\n\nexport default ({ app }, inject) => {\n Vue.use(VueGtag, {\n config: {\n id: process.env.ga_stream_id\n }\n })\n}\n```\n\n```text\nimport Vue from \"vue\"\nimport { User } from \"~/models/user/User\"\n\nexport const states = () => ({})\n\nconst getterObjects = {}\nconst mutationObjects = {}\nObject.keys(states).forEach(key => {\n getterObjects[key] = state => state[key]\n mutationObjects[key] = (state, value) => (state[key] = value)\n})\n\nexport const state = () => states\n\nexport const getters = { ...getterObjects }\n\nexport const mutations = { ...mutationObjects }\n\nexport const actions = {\n async sendUserProperties({ dispatch, commit }) {\n let res = await this.$UserApi.getUser()\n if (!(res instanceof User)) {\n } else {\n // I can access this on my components and pages but for some reason not here....\n console.log(this.$gtag)\n }\n }\n}\n```\n\n```text\nconst Instance = new Vue({...whatever});\n\n// only export what you need in other parts of the app\nexport const { $gtag, $store, $t, $http } = Instance;\n\n// or export the entire Instance\nexport default Instance;\n```\n\n```text\nimport Instance from '@/main';\n// or: \nimport { $gtag } from '@/main';\n\n// use Instance.$gtag or $gtag, depending on what you imported.\n```\n\n```text\nmain.(ts|js)\n```\n\n```text\nthis._vm\n```\n\n```text\nv2\n```\n\n```text\nv3\n```\n\n```text\n_\n```\n\n```js\nconsole.log(this._vm.$gtag)\n```\n\n```text\nthis._vm\n```\n\n========================================\n\nComments:\n- It worked fine but the fact that it is not in the documentation worries me.\n- are there any other way to do it ?\n- @obliviousfella it's a Vue.js internal property so it's not actually documented but it works as an element of the Vue.js core functionality. I'm aware of the observations made in other answers but I'm also an advocate of the KISS principle, but anyways I guess it's a matter choosing which solution fits better for your particular need.\n- Can you tell the equivalent of main.js in nuxt? I can't find one :<\n- `import Vue from \"vue\" import VueGtag from \"vue-gtag\" Vue.use(VueGtag, { config: { id: process.env.ga_stream_id } }) export default (ctx, inject) => { ctx.$gtag = Vue.$gtag inject(\"gtag\", Vue.$gtag) }`\n- While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review","metadata":{"transformedAt":"2026-08-18T18:33:07.876Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":169,"estimatedTokens":978}}547{"id":"stack-71930369","source":"stackoverflow","questionId":71930369,"title":"Different behavior of lifecycle hooks between Vue and Nuxt","tags":["vue.js","nuxt.js"],"text":"Title: Different behavior of lifecycle hooks between Vue and Nuxt\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have two pages foo and bar, I print a message to the console when each of the hooks works. In vue it's one order, in nuxt it's another\n\n**Vue:**\n\nenter /foo\n\n```\nbeforeCreate\ncreated\nbeforeMount\nmounted\n```\n\nswitch /foo to /bar\n\n```\nbeforeCreate\ncreated\nbeforeMount\nbeforeDestroy\ndestroyed\nmounted\n```\n\n**Nuxt:**\n\nenter /foo\n\n```\nbeforeCreate\ncreated\nbeforeMount \nmounted\n```\n\nswitch /foo to /bar\n\n```\nbeforeDestroy\ndestroyed\nbeforeCreate\ncreated\nbeforeMount\nmounted\n```\n\nWhen there is a transition to /foo, then in vue/nuxt the hooks fire in the same order, but if you switch from route to route, then the order will change. Why is this happening? Maybe I’m doing something wrong?\n\nSandbox Vue \n\nSandbox Nuxt\n\n========================================\n\nCode:\n```text\nbeforeCreate\ncreated\nbeforeMount\nmounted\n```\n\n```text\nbeforeCreate\ncreated\nbeforeMount\nbeforeDestroy\ndestroyed\nmounted\n```\n\n```text\nbeforeCreate\ncreated\nbeforeMount \nmounted\n```\n\n```text\nbeforeDestroy\ndestroyed\nbeforeCreate\ncreated\nbeforeMount\nmounted\n```\n\n```js\nexport default {\n transition: {\n mode: 'out-in'\n }\n}\n```\n\n```js\nexport default {\n transition: {\n mode: 'in-out'\n }\n}\n```\n\n========================================\n\nComments:\n- This is probably because of the `mode` set by default by Nuxt? This is probably not the default one in Vue. Also, maybe check the Nuxt lifecycle, not sure if it can help anyhow.\n- @kissu, thanks, problem solved after changing transition.mode to in-out","metadata":{"transformedAt":"2026-08-18T18:33:07.876Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":113,"estimatedTokens":398}}548{"id":"stack-72175266","source":"stackoverflow","questionId":72175266,"title":"Computed is not defined","tags":["vue.js","debugging","vuejs2","nuxt.js","vue-composition-api"],"text":"Title: Computed is not defined\nTags: vue.js, debugging, vuejs2, nuxt.js, vue-composition-api\nSource: Stack Overflow\n\nQuestion:\nI've got a error where computed is not defined, I can't seem to find how to solve this, even after placing it in `computed: {}`\n\n```\n\n \n\nimport { defineComponent } from \"@nuxtjs/composition-api\";\n\nimport DOMPurify from \"isomorphic-dompurify\";\n\nexport default defineComponent({\n name: \"HTMLContent\",\n sanitizedContent: computed(() => DOMPurify.sanitize(props.content)),\n props: {\n tag: {\n type: String,\n default: \"div\",\n },\n content: {\n type: String,\n default: \"\",\n },\n },\n});\n\n```\n\n========================================\n\nTop Answer:\nDid you try to import it:\n\n```\nimport { computed } from \"vue\";\n```\n\nand:\n\n```\nconst sanitizedContent = computed(() => DOMPurify.sanitize(props.content))\n```\n\n========================================\n\nCode:\n```html\n<template>\n <component :is=\"tag\" v-html=\"sanitizedContent\" />\n</template>\n<script>\nimport { defineComponent } from \"@nuxtjs/composition-api\";\n\nimport DOMPurify from \"isomorphic-dompurify\";\n\nexport default defineComponent({\n name: \"HTMLContent\",\n sanitizedContent: computed(() => DOMPurify.sanitize(props.content)),\n props: {\n tag: {\n type: String,\n default: \"div\",\n },\n content: {\n type: String,\n default: \"\",\n },\n },\n});\n</script>\n```\n\n```text\ncomputed: {}\n```\n\n```html\n<template>\n <component :is=\"tag\" v-html=\"sanitizedContent\" />\n</template>\n<script>\nimport { computed, defineComponent } from \"@nuxtjs/composition-api\";\nimport DOMPurify from \"isomorphic-dompurify\";\n\nexport default defineComponent({\n name: \"HTMLContent\",\n props: {\n tag: {\n type: String,\n default: \"div\",\n },\n content: {\n type: String,\n default: \"\",\n },\n },\n setup(props) {\n return {\n sanitizedContent: computed(() => DOMPurify.sanitize(props.content)),\n }\n }\n});\n</script>\n```\n\n```text\ncomputed\n```\n\n```text\n\"@nuxtjs/composition-api\"\n```\n\n```text\nsetup\n```\n\n```text\nimport { computed } from \"vue\";\n```\n\n```text\nconst sanitizedContent = computed(() => DOMPurify.sanitize(props.content))\n```\n\n========================================\n\nComments:\n- Does not seem to be the solution since it returns: TypeError Object(...) is not a function ...\n- @Craws hey mate, I updated my answer, take a look again pls\n- Thanks mate! Where would one place the const? If I reference it in the and place the const under setup() { .. It has a no refference in the IDE and a Object(...) is not a function error on runtime","metadata":{"transformedAt":"2026-08-18T18:33:07.877Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":135,"estimatedTokens":634}}549{"id":"stack-59722165","source":"stackoverflow","questionId":59722165,"title":"How to use external scoped scss in Vue","tags":["vue.js","sass","nuxt.js"],"text":"Title: How to use external scoped scss in Vue\nTags: vue.js, sass, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a project on `Vue-nuxt`. I want to use external `SCSS` scoped to only that component.\n\n```\n\n \n \n\n### {{ heading }}\n\n {{ para }}\n\n \n\n \n\n import './../assets/css/card.scss'\n \n export default {\n props: {\n heading: String,\n para: String\n }\n }\n\n```\n\nHow can I do that?\n\n========================================\n\nCode:\n```js\n<template>\n <div class=\"card\">\n <h3>{{ heading }}</h3>\n <p>{{ para }}</p>\n </div>\n</template>\n \n<script>\n import './../assets/css/card.scss'\n \n export default {\n props: {\n heading: String,\n para: String\n }\n }\n</script>\n```\n\n```text\nVue-nuxt\n```\n\n```text\nSCSS\n```\n\n```text\n<style lang=\"scss\" scoped>\n@import \"sample.scss\";\n</style>\n```\n\n========================================\n\nComments:\n- you can't import inside style tag?\n- of course you can. Its the place to write scss code and import scss files\n- @anny123 github.com/vuejs-templates/webpack/issues/… looks like you can import in the style tag. Does it not work for you?\n- @Tanner ^Above comment\n- @import for css/scss within the style tags\n- I had this issue where I wanted to import a scss style but it wasn't working: the problem was I was adding some dynamic html via string for a certain piece. I had a class on the element inside the string, but it was ignored. To fix it, I made the same class in the component where this was going on and made a :deep .myclass { @import \"style\" } rule where the nested import statement began to work. I didn't know the rules could be also nested like so.","metadata":{"transformedAt":"2026-08-18T18:33:07.877Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":79,"estimatedTokens":414}}550{"id":"stack-71558358","source":"stackoverflow","questionId":71558358,"title":"Nuxt application local development server constantly reloading","tags":["vue.js","nuxt.js"],"text":"Title: Nuxt application local development server constantly reloading\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a Nuxt ^2.15.8 application which is constantly reloading after I run `yarn dev`.\n\nThe console will show a message like `↻ Updated 1647868577626`, and then the application is rebuilt, as if I just run `yarn dev`. This happens constantly over and over, without me doing any changes in the code.\n\nI googled a bit, and found applications like gitkraken might be modifying the content of the .git folder and that could trigger a reload.\n\nSo I keep gitkraken closed.\n\nI also added these lines to my `nuxt.config.js` file:\n\n```\nwatchers: {\n webpack: {\n ignored: [\n '**/*.{md,log,prettierignore,prettierrc,stylelintignore,npmrc,gitignore}',\n '**/.git/**',\n ],\n },\n},\n```\n\nThat doesn't fix the issue though\n\nMy main question is: what would the line `↻ Updated 1647868577626` mean, and what could be causing it? I get the feeling that if I want to solve my problem, I need to answer that question.\n\nEdit: this is my full `nuxt.config.js` file\n\n```\nimport fs from 'fs'\nimport path from 'path'\n\n// TODO Migrate from dotenv to runtime config https://nuxtjs.org/tutorials/moving-from-nuxtjs-dotenv-to-runtime-config/\nimport { config } from 'dotenv'\n\nconfig()\n\n// eslint-disable-next-line import/first\nimport { exportSitePayload, getSitePayload } from './scripts/prepare-for-build'\n// eslint-disable-next-line import/first\n\nprocess.env.NUXT_TARGET_MODE\n = process.env.NUXT_TARGET_MODE || (process.env.NETLIFY ? 'static' : 'server')\n\nconst isProd\n = /prod/i.test(process.env.NODE_ENV)\n || process.env.NETLIFY\n || (process.env.HEROKU && process.env.PP_ENV === 'production')\nconst isStaging\n = !isProd\n && (/stag/i.test(process.env.NODE_ENV) || (process.env.HEROKU && process.env.PP_ENV === 'staging'))\nconst isDev = !(isProd || isStaging)\n\nexport default async function() {\n await exportSitePayload({\n ...(process.env.STATIC_HOST ? { staticHost: process.env.STATIC_HOST } : {}),\n ...(process.env.HEROKU ? { all: true } : {}),\n })\n return {\n ssr: process.env.SSR !== 'false',\n target: process.env.NUXT_TARGET_MODE,\n components: [\n { path: '~/components/', pathPrefix: false },\n { path: '~/components', pathPrefix: true, level: 1 },\n ],\n env: {\n SANITY_PROJECT_ID: process.env.SANITY_PROJECT_ID,\n SANITY_PROJECT_DATASET: process.env.SANITY_PROJECT_DATASET,\n },\n publicRuntimeConfig: {\n apiBaseURL: process.env.API_BASE_URL,\n forceAPIBaseURL: process.env.FORCE_API_BASE_URL,\n ppEnv: process.env.PP_ENV,\n archivedMode: process.env.ARCHIVED_MODE,\n archivedModeLiveLink: process.env.ARCHIVED_MODE_LIVE_LINK,\n attendeeAPILinkedInCallback: process.env.ACCOUNT_ENDPOINT_LINKEDIN_CALLBACK,\n attendeeAPILogout: process.env.ACCOUNT_ENDPOINT_LOGOUT,\n attendeeAPIVerifyLogincode: process.env.ACCOUNT_ENDPOINT_VERIFY_LOGINCODE,\n attendeeAPIMagicLinkRequest: process.env.ACCOUNT_ENDPOINT_MAGIC_LINK_REQUEST,\n attendeeAPIRegister: process.env.ACCOUNT_ENDPOINT_REGISTER,\n attendeeAPIUserInfo: process.env.ACCOUNT_ENDPOINT_USER_INFO,\n devDisableCache: process.env.DEV_DISABLE_CACHE,\n eventAPIDetails: process.env.EVENT_ENDPOINT_DETAILS,\n eventAPIBadge: process.env.EVENT_ENDPOINT_BADGE,\n liveEventAPIStage: process.env.LIVE_EVENT_ENDPOINT_STAGE,\n liveEventAPIChat: process.env.LIVE_EVENT_ENDPOINT_CHAT,\n orderAPICustomer: process.env.ORDER_ENDPOINT_CUSTOMER,\n orderAPICart: process.env.ORDER_ENDPOINT_CART,\n orderAPIInfo: process.env.ORDER_ENDPOINT_INFO,\n orderAPIInvoice: process.env.ORDER_ENDPOINT_INVOICE,\n paymentAPIMethods: process.env.PAYMENT_API_METHODS,\n productAPIInfo: process.env.PRODUCT_ENDPOINT_INFO,\n staticHost: process.env.STATIC_HOST,\n streamChatAPIKey: process.env.STREAM_CHAT_API_KEY,\n streamChatAPPId: process.env.STREAM_CHAT_APP_ID,\n ticketAPIDetails: process.env.TICKET_ENDPOINT_DETAILS,\n ticketAPIList: process.env.TICKET_ENDPOINT_LIST,\n userAPIOrders: process.env.USER_ENDPOINT_ORDERS,\n videoAPIDetails: process.env.VIDEO_API_ENDPOINT_DETAILS,\n videoAPILists: process.env.VIDEO_API_ENDPOINT_LISTS,\n videoAPIUploadInfo: process.env.VIDEO_API_ENDPOINT_UPLOAD_INFO,\n isProd,\n isStaging,\n isDev,\n },\n /*\n ** Headers of the page\n */\n head: {\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n {\n hid: 'viewport',\n name: 'viewport',\n content: 'width=device-width, initial-scale=1',\n },\n ],\n link: [\n { rel: 'stylesheet', href: 'https://use.typekit.net/fag0imi.css' },\n { rel: 'stylesheet', href: '/theme.css' },\n { rel: 'stylesheet', href: '/static_theme.css' },\n ],\n },\n /*\n ** Customize the progress-bar color\n */\n loading: { color: 'var(--color-primary-500)' },\n /*\n ** Global CSS\n */\n css: [],\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n '~/plugins/vuelidate.js',\n '~/plugins/filters.js',\n '~/plugins/lazyload.js',\n '~/plugins/reactive-provide.js',\n '~/plugins/vue-form-wizard',\n '~/plugins/vue-phone-number-input',\n '~/plugins/vue-selectize',\n '~/plugins/sanity-block-vue-component.js',\n '~/plugins/youtube.client.js',\n '~/plugins/v-tooltip.js',\n '~/plugins/axios.js',\n { src: 'plugins/vue-typer.client.js', ssr: false },\n ],\n /*\n ** Nuxt.js dev-modules\n */\n buildModules: [\n '@nuxt/postcss8',\n // https://typescript.nuxtjs.org/\n '@nuxt/typescript-build',\n // https://composition-api.nuxtjs.org/getting-started/setup\n '@nuxtjs/composition-api/module',\n // Doc: https://github.com/nuxt-community/eslint-module\n '@nuxtjs/eslint-module',\n // Doc: https://github.com/nuxt-community/nuxt-tailwindcss\n '@nuxtjs/tailwindcss',\n '@nuxtjs/dotenv',\n ],\n /*\n ** Nuxt.js modules\n */\n modules: [\n '@nuxtjs/axios',\n [\n '@nuxtjs/pwa',\n {\n manifest: false,\n icon: false,\n workbox: {\n runtimeCaching: [\n {\n urlPattern: 'https://a.storyblok.com/.*',\n handler: 'CacheFirst',\n },\n {\n urlPattern: 'https://img2.storyblok.com/.*',\n handler: 'CacheFirst',\n },\n {\n urlPattern: 'https://cdn.sanity.io/.*',\n handler: 'CacheFirst',\n },\n ],\n },\n },\n ],\n [\n 'storyblok-nuxt',\n {\n accessToken: process.env.STORYBLOK_ACCESS_TOKEN,\n cacheProvider: 'memory',\n },\n ],\n 'nuxt-webfontloader',\n 'portal-vue/nuxt',\n '@nuxtjs/proxy',\n '@nuxtjs/sentry',\n ],\n\n ...(isProd || isStaging\n ? {\n sentry: {\n dsn: process.env.SENTRY_DNS, // Enter your project's DSN here\n // Additional Module Options go here\n // https://sentry.nuxtjs.org/sentry/options\n tracing: {\n tracesSampleRate: isProd ? 0.2 : 1.0,\n vueOptions: {\n tracing: true,\n tracingOptions: {\n hooks: ['mount', 'update'],\n timeout: 2000,\n trackComponents: true,\n },\n },\n browserOptions: {},\n },\n config: {\n // Add native Sentry config here\n // https://docs.sentry.io/platforms/javascript/guides/vue/configuration/options/\n environment: isProd ? 'production' : 'staging',\n debug: !isProd,\n },\n },\n }\n : {}),\n\n ...(!/prod/i.test(process.env.NODE_ENV) && !process.env.NETLIFY\n ? {\n proxy: {\n '/.netlify/functions': {\n target: process.env.API_ORIGIN,\n },\n },\n }\n : {}),\n\n ...(/prod/i.test(process.env.NODE_ENV) || process.env.NETLIFY || process.env.HEROKU\n ? {}\n : {\n server: {\n https: {\n key: fs.readFileSync(path.resolve(__dirname, '.tls/key.pem')),\n cert: fs.readFileSync(path.resolve(__dirname, '.tls/cert.pem')),\n },\n },\n }),\n\n axios: {\n credentials: true,\n baseURL: process.env.API_BASE_URL,\n },\n auth: {\n cookie: {\n cookie: {\n name: 'frontend_love_account_state',\n },\n token: {\n required: false,\n type: false,\n },\n user: {\n property: '',\n },\n endpoints: {\n login: {\n url: process.env.ACCOUNT_ENDPOINT_MAGIC_LINK_REQUEST,\n method: 'post',\n },\n logout: { url: process.env.ACCOUNT_ENDPOINT_LOGOUT, method: 'post' },\n user: { url: process.env.ACCOUNT_ENDPOINT_USER_INFO, method: 'get' },\n },\n },\n loginCode: {\n scheme: 'local',\n token: {\n required: false,\n type: false,\n },\n endpoints: {\n login: {\n url: process.env.ACCOUNT_ENDPOINT_VERIFY_LOGINCODE,\n method: 'post',\n },\n user: { url: process.env.ACCOUNT_ENDPOINT_USER_INFO, method: 'get' },\n },\n user: {\n property: false,\n autoFetch: false,\n },\n },\n plugins: ['~/plugins/auth.js'],\n },\n /*\n ** nuxt-webfontloader Options\n */\n webfontloader: {\n google: {\n families: ['Merriweather:300,400,700', 'Rubik:300,400,500', 'Odibee+Sans'],\n },\n },\n /*\n ** Build configuration\n */\n build: {\n quiet: false,\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n config.resolve.alias.vue = 'vue/dist/vue.common'\n if (ctx.isDev)\n config.devtool = ctx.isClient ? 'source-map' : 'inline-source-map'\n },\n postcss: {\n plugins: {\n 'postcss-import': {},\n 'tailwindcss/nesting': {},\n 'tailwindcss': {},\n 'autoprefixer': {},\n },\n },\n transpile: ['@passionatepeople/sanity-utils', 'vue-pincode-input'],\n },\n generate: {\n interval: 200,\n routes: async() => {\n if (!process.env.STATIC_HOST) {\n // eslint-disable-next-line no-console\n console.error('No STATIC_HOST variable specified!')\n process.exit(1)\n }\n await getSitePayload(process.env.STATIC_HOST)\n const { pages } = require('./dist/data.json')\n // eslint-disable-next-line no-console\n console.log('Explicit routes to generate:')\n // eslint-disable-next-line no-console\n pages.forEach(({ route }) => console.log(` - ${route}`))\n return pages\n },\n fallback: true,\n },\n purgeCSS: {\n paths: [\n 'components/**/*.vue',\n 'layouts/**/*.vue',\n 'pages/**/*.vue',\n 'plugins/**/*.js',\n 'dist/*.json',\n ],\n whitelistPatterns: [/bg-/, /text-/, /from-/, /to-/, /border-/, /lyt-/, /w-/, /grid-cols-/],\n extractors: [\n {\n extractor(content) {\n return content.match(/[\\w-.:!/]+(?<!:)/g)\n },\n extensions: ['html', 'vue', 'js', 'json'],\n },\n ],\n },\n /*\n ** Storybook module configuration\n ** See https://storybook.nuxtjs.org/options/\n */\n storybook: {\n addons: ['@storybook/addon-controls/register', '@storybook/addon-viewport/register'],\n },\n watchers: {\n webpack: {\n ignored: [\n '**/*.{md,log,prettierignore,prettierrc,stylelintignore,npmrc,gitignore}',\n '**/.git/**',\n ],\n },\n },\n }\n}\n```\n\n========================================\n\nCode:\n```js\nwatchers: {\n webpack: {\n ignored: [\n '**/*.{md,log,prettierignore,prettierrc,stylelintignore,npmrc,gitignore}',\n '**/.git/**',\n ],\n },\n},\n```\n\n```js\nimport fs from 'fs'\nimport path from 'path'\n\n// TODO Migrate from dotenv to runtime config https://nuxtjs.org/tutorials/moving-from-nuxtjs-dotenv-to-runtime-config/\nimport { config } from 'dotenv'\n\nconfig()\n\n// eslint-disable-next-line import/first\nimport { exportSitePayload, getSitePayload } from './scripts/prepare-for-build'\n// eslint-disable-next-line import/first\n\nprocess.env.NUXT_TARGET_MODE\n = process.env.NUXT_TARGET_MODE || (process.env.NETLIFY ? 'static' : 'server')\n\nconst isProd\n = /prod/i.test(process.env.NODE_ENV)\n || process.env.NETLIFY\n || (process.env.HEROKU && process.env.PP_ENV === 'production')\nconst isStaging\n = !isProd\n && (/stag/i.test(process.env.NODE_ENV) || (process.env.HEROKU && process.env.PP_ENV === 'staging'))\nconst isDev = !(isProd || isStaging)\n\nexport default async function() {\n await exportSitePayload({\n ...(process.env.STATIC_HOST ? { staticHost: process.env.STATIC_HOST } : {}),\n ...(process.env.HEROKU ? { all: true } : {}),\n })\n return {\n ssr: process.env.SSR !== 'false',\n target: process.env.NUXT_TARGET_MODE,\n components: [\n { path: '~/components/', pathPrefix: false },\n { path: '~/components', pathPrefix: true, level: 1 },\n ],\n env: {\n SANITY_PROJECT_ID: process.env.SANITY_PROJECT_ID,\n SANITY_PROJECT_DATASET: process.env.SANITY_PROJECT_DATASET,\n },\n publicRuntimeConfig: {\n apiBaseURL: process.env.API_BASE_URL,\n forceAPIBaseURL: process.env.FORCE_API_BASE_URL,\n ppEnv: process.env.PP_ENV,\n archivedMode: process.env.ARCHIVED_MODE,\n archivedModeLiveLink: process.env.ARCHIVED_MODE_LIVE_LINK,\n attendeeAPILinkedInCallback: process.env.ACCOUNT_ENDPOINT_LINKEDIN_CALLBACK,\n attendeeAPILogout: process.env.ACCOUNT_ENDPOINT_LOGOUT,\n attendeeAPIVerifyLogincode: process.env.ACCOUNT_ENDPOINT_VERIFY_LOGINCODE,\n attendeeAPIMagicLinkRequest: process.env.ACCOUNT_ENDPOINT_MAGIC_LINK_REQUEST,\n attendeeAPIRegister: process.env.ACCOUNT_ENDPOINT_REGISTER,\n attendeeAPIUserInfo: process.env.ACCOUNT_ENDPOINT_USER_INFO,\n devDisableCache: process.env.DEV_DISABLE_CACHE,\n eventAPIDetails: process.env.EVENT_ENDPOINT_DETAILS,\n eventAPIBadge: process.env.EVENT_ENDPOINT_BADGE,\n liveEventAPIStage: process.env.LIVE_EVENT_ENDPOINT_STAGE,\n liveEventAPIChat: process.env.LIVE_EVENT_ENDPOINT_CHAT,\n orderAPICustomer: process.env.ORDER_ENDPOINT_CUSTOMER,\n orderAPICart: process.env.ORDER_ENDPOINT_CART,\n orderAPIInfo: process.env.ORDER_ENDPOINT_INFO,\n orderAPIInvoice: process.env.ORDER_ENDPOINT_INVOICE,\n paymentAPIMethods: process.env.PAYMENT_API_METHODS,\n productAPIInfo: process.env.PRODUCT_ENDPOINT_INFO,\n staticHost: process.env.STATIC_HOST,\n streamChatAPIKey: process.env.STREAM_CHAT_API_KEY,\n streamChatAPPId: process.env.STREAM_CHAT_APP_ID,\n ticketAPIDetails: process.env.TICKET_ENDPOINT_DETAILS,\n ticketAPIList: process.env.TICKET_ENDPOINT_LIST,\n userAPIOrders: process.env.USER_ENDPOINT_ORDERS,\n videoAPIDetails: process.env.VIDEO_API_ENDPOINT_DETAILS,\n videoAPILists: process.env.VIDEO_API_ENDPOINT_LISTS,\n videoAPIUploadInfo: process.env.VIDEO_API_ENDPOINT_UPLOAD_INFO,\n isProd,\n isStaging,\n isDev,\n },\n /*\n ** Headers of the page\n */\n head: {\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n {\n hid: 'viewport',\n name: 'viewport',\n content: 'width=device-width, initial-scale=1',\n },\n ],\n link: [\n { rel: 'stylesheet', href: 'https://use.typekit.net/fag0imi.css' },\n { rel: 'stylesheet', href: '/theme.css' },\n { rel: 'stylesheet', href: '/static_theme.css' },\n ],\n },\n /*\n ** Customize the progress-bar color\n */\n loading: { color: 'var(--color-primary-500)' },\n /*\n ** Global CSS\n */\n css: [],\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n '~/plugins/vuelidate.js',\n '~/plugins/filters.js',\n '~/plugins/lazyload.js',\n '~/plugins/reactive-provide.js',\n '~/plugins/vue-form-wizard',\n '~/plugins/vue-phone-number-input',\n '~/plugins/vue-selectize',\n '~/plugins/sanity-block-vue-component.js',\n '~/plugins/youtube.client.js',\n '~/plugins/v-tooltip.js',\n '~/plugins/axios.js',\n { src: 'plugins/vue-typer.client.js', ssr: false },\n ],\n /*\n ** Nuxt.js dev-modules\n */\n buildModules: [\n '@nuxt/postcss8',\n // https://typescript.nuxtjs.org/\n '@nuxt/typescript-build',\n // https://composition-api.nuxtjs.org/getting-started/setup\n '@nuxtjs/composition-api/module',\n // Doc: https://github.com/nuxt-community/eslint-module\n '@nuxtjs/eslint-module',\n // Doc: https://github.com/nuxt-community/nuxt-tailwindcss\n '@nuxtjs/tailwindcss',\n '@nuxtjs/dotenv',\n ],\n /*\n ** Nuxt.js modules\n */\n modules: [\n '@nuxtjs/axios',\n [\n '@nuxtjs/pwa',\n {\n manifest: false,\n icon: false,\n workbox: {\n runtimeCaching: [\n {\n urlPattern: 'https://a.storyblok.com/.*',\n handler: 'CacheFirst',\n },\n {\n urlPattern: 'https://img2.storyblok.com/.*',\n handler: 'CacheFirst',\n },\n {\n urlPattern: 'https://cdn.sanity.io/.*',\n handler: 'CacheFirst',\n },\n ],\n },\n },\n ],\n [\n 'storyblok-nuxt',\n {\n accessToken: process.env.STORYBLOK_ACCESS_TOKEN,\n cacheProvider: 'memory',\n },\n ],\n 'nuxt-webfontloader',\n 'portal-vue/nuxt',\n '@nuxtjs/proxy',\n '@nuxtjs/sentry',\n ],\n\n ...(isProd || isStaging\n ? {\n sentry: {\n dsn: process.env.SENTRY_DNS, // Enter your project's DSN here\n // Additional Module Options go here\n // https://sentry.nuxtjs.org/sentry/options\n tracing: {\n tracesSampleRate: isProd ? 0.2 : 1.0,\n vueOptions: {\n tracing: true,\n tracingOptions: {\n hooks: ['mount', 'update'],\n timeout: 2000,\n trackComponents: true,\n },\n },\n browserOptions: {},\n },\n config: {\n // Add native Sentry config here\n // https://docs.sentry.io/platforms/javascript/guides/vue/configuration/options/\n environment: isProd ? 'production' : 'staging',\n debug: !isProd,\n },\n },\n }\n : {}),\n\n ...(!/prod/i.test(process.env.NODE_ENV) && !process.env.NETLIFY\n ? {\n proxy: {\n '/.netlify/functions': {\n target: process.env.API_ORIGIN,\n },\n },\n }\n : {}),\n\n ...(/prod/i.test(process.env.NODE_ENV) || process.env.NETLIFY || process.env.HEROKU\n ? {}\n : {\n server: {\n https: {\n key: fs.readFileSync(path.resolve(__dirname, '.tls/key.pem')),\n cert: fs.readFileSync(path.resolve(__dirname, '.tls/cert.pem')),\n },\n },\n }),\n\n axios: {\n credentials: true,\n baseURL: process.env.API_BASE_URL,\n },\n auth: {\n cookie: {\n cookie: {\n name: 'frontend_love_account_state',\n },\n token: {\n required: false,\n type: false,\n },\n user: {\n property: '',\n },\n endpoints: {\n login: {\n url: process.env.ACCOUNT_ENDPOINT_MAGIC_LINK_REQUEST,\n method: 'post',\n },\n logout: { url: process.env.ACCOUNT_ENDPOINT_LOGOUT, method: 'post' },\n user: { url: process.env.ACCOUNT_ENDPOINT_USER_INFO, method: 'get' },\n },\n },\n loginCode: {\n scheme: 'local',\n token: {\n required: false,\n type: false,\n },\n endpoints: {\n login: {\n url: process.env.ACCOUNT_ENDPOINT_VERIFY_LOGINCODE,\n method: 'post',\n },\n user: { url: process.env.ACCOUNT_ENDPOINT_USER_INFO, method: 'get' },\n },\n user: {\n property: false,\n autoFetch: false,\n },\n },\n plugins: ['~/plugins/auth.js'],\n },\n /*\n ** nuxt-webfontloader Options\n */\n webfontloader: {\n google: {\n families: ['Merriweather:300,400,700', 'Rubik:300,400,500', 'Odibee+Sans'],\n },\n },\n /*\n ** Build configuration\n */\n build: {\n quiet: false,\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n config.resolve.alias.vue = 'vue/dist/vue.common'\n if (ctx.isDev)\n config.devtool = ctx.isClient ? 'source-map' : 'inline-source-map'\n },\n postcss: {\n plugins: {\n 'postcss-import': {},\n 'tailwindcss/nesting': {},\n 'tailwindcss': {},\n 'autoprefixer': {},\n },\n },\n transpile: ['@passionatepeople/sanity-utils', 'vue-pincode-input'],\n },\n generate: {\n interval: 200,\n routes: async() => {\n if (!process.env.STATIC_HOST) {\n // eslint-disable-next-line no-console\n console.error('No STATIC_HOST variable specified!')\n process.exit(1)\n }\n await getSitePayload(process.env.STATIC_HOST)\n const { pages } = require('./dist/data.json')\n // eslint-disable-next-line no-console\n console.log('Explicit routes to generate:')\n // eslint-disable-next-line no-console\n pages.forEach(({ route }) => console.log(` - ${route}`))\n return pages\n },\n fallback: true,\n },\n purgeCSS: {\n paths: [\n 'components/**/*.vue',\n 'layouts/**/*.vue',\n 'pages/**/*.vue',\n 'plugins/**/*.js',\n 'dist/*.json',\n ],\n whitelistPatterns: [/bg-/, /text-/, /from-/, /to-/, /border-/, /lyt-/, /w-/, /grid-cols-/],\n extractors: [\n {\n extractor(content) {\n return content.match(/[\\w-.:!/]+(?<!:)/g)\n },\n extensions: ['html', 'vue', 'js', 'json'],\n },\n ],\n },\n /*\n ** Storybook module configuration\n ** See https://storybook.nuxtjs.org/options/\n */\n storybook: {\n addons: ['@storybook/addon-controls/register', '@storybook/addon-viewport/register'],\n },\n watchers: {\n webpack: {\n ignored: [\n '**/*.{md,log,prettierignore,prettierrc,stylelintignore,npmrc,gitignore}',\n '**/.git/**',\n ],\n },\n },\n }\n}\n```\n\n```text\nyarn dev\n```\n\n```text\n↻ Updated 1647868577626\n```\n\n```text\nyarn dev\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n↻ Updated 1647868577626\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n1.x.x\n```\n\n```text\n3.x.x\n```\n\n```text\ngit bisect\n```\n\n```text\nyarn dev\n```\n\n========================================\n\nComments:\n- Quite a simple debugging, download the project into a new directory, extract your project there (from the `.zip`) and try to run it again. That way, no git involved. Be sure that this is not working from the service worker, trying that into a private window of some other browser (like Firefox) may help. Create a new static page with nothing in it, whitelist it from the auth module and see if this happens again. Trying to reach this page should also remove any kind of middleware/plugins/side effect-y code that you may not have spotted (yet). Finally, ask a colleague if the same is happening.","metadata":{"transformedAt":"2026-08-18T18:33:07.877Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":804,"estimatedTokens":5423}}551{"id":"stack-69161159","source":"stackoverflow","questionId":69161159,"title":"Using @use \"sass:math\" in a Vue component","tags":["vue.js","sass","nuxt.js"],"text":"Title: Using @use \"sass:math\" in a Vue component\nTags: vue.js, sass, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn a Nuxt 2 project i have created a button component with the following style:\n\n```\n\n .my-button {\n // lots of cool styles and stuff here\n $height: 28px;\n height: $height;\n border-radius: $height / 2;\n }\n \n```\n\nThe problem is the `border-radius: $height / 2;` line gives this warning:\n\n```\n╷\n182 │ border-radius: $height / 2;\n │ ^^^^^^^^^^^\n ╵\n components/MyButton.vue 182:20 button-size()\n components/MyButton.vue 186:5 root stylesheet\n\n: Using / for division is deprecated and will be removed in Dart Sass \n2.0.0.\n\nRecommendation: math.div($height, 2)\n```\n\nIt also links to this page describing the deprecation.\n\nHowever if i add `@use \"sass:math\"` to the top of my style tag like so:\n\n```\n\n @use \"sass:math\";\n //Cool styles and stuff\n $height: 28px;\n height: $height;\n border-radius: math.div($height, 2);\n \n```\n\nI get this error:\n\n```\n[Vue warn]: Error in render: \"Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): 12:13:59\nSassError: @use rules must be written before any other rules.\n ╷\n102 │ @use \"sass:math\";\n │ ^^^^^^^^^^^^^^^^\n ╵\n components/MyButton.vue 102:1 root stylesheet\"\n```\n\nI think i need to add the import of `@use \"sass:math\"` somewhere in `nuxt.config.js` file to load it in all components or similar, but i am not able to figure out where.\n\nThe css related blocks in my nuxt.config.js currently looks like:\n\n```\nbuild: {\n postcss: {\n plugins: {\n 'postcss-easing-gradients': {},\n },\n },\n },\n styleResources: {\n scss: [\n '~/assets/global-inject.scss',\n ],\n },\n css: [\n '~/assets/base.scss',\n '~/assets/reset.scss',\n ],\n```\n\n========================================\n\nTop Answer:\n### Updated answer\n\nWhat if you try this in your `nuxt.config.js` file?\n\n```\n{\n build: {\n loaders: {\n scss: {\n additionalData: `\n @use \"@/styles/colors.scss\" as *;\n @use \"@/styles/overrides.scss\" as *;\n `,\n },\n },\n ...\n}\n```\n\nOr you can maybe try one of the numerous solutions here: https://github.com/nuxt-community/style-resources-module/issues/143\n\nPlenty of people do have this issue but I don't really have a project under my belt to see what is buggy. Playing with versions and adding some config to the nuxt config is probably the way to fix it yeah.\n\nAlso, if it's a warning it's not blocking so far or does it break your app somehow?\n\n### Old answer\n\nMy answer here can probably help you: https://stackoverflow.com/a/68648204/8816585\n\nIt is a matter of upgrading to the latest version and to fix those warnings.\n\n========================================\n\nCode:\n```css\n<style lang=\"scss\">\n .my-button {\n // lots of cool styles and stuff here\n $height: 28px;\n height: $height;\n border-radius: $height / 2;\n }\n </style>\n```\n\n```text\n╷\n182 │ border-radius: $height / 2;\n │ ^^^^^^^^^^^\n ╵\n components/MyButton.vue 182:20 button-size()\n components/MyButton.vue 186:5 root stylesheet\n\n: Using / for division is deprecated and will be removed in Dart Sass \n2.0.0.\n\nRecommendation: math.div($height, 2)\n```\n\n```css\n<style lang=\"scss\">\n @use \"sass:math\";\n //Cool styles and stuff\n $height: 28px;\n height: $height;\n border-radius: math.div($height, 2);\n </style>\n```\n\n```text\n[Vue warn]: Error in render: \"Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): 12:13:59\nSassError: @use rules must be written before any other rules.\n ╷\n102 │ @use \"sass:math\";\n │ ^^^^^^^^^^^^^^^^\n ╵\n components/MyButton.vue 102:1 root stylesheet\"\n```\n\n```js\nbuild: {\n postcss: {\n plugins: {\n 'postcss-easing-gradients': {},\n },\n },\n },\n styleResources: {\n scss: [\n '~/assets/global-inject.scss',\n ],\n },\n css: [\n '~/assets/base.scss',\n '~/assets/reset.scss',\n ],\n```\n\n```text\nborder-radius: $height / 2;\n```\n\n```text\n@use \"sass:math\"\n```\n\n```text\n@use \"sass:math\"\n```\n\n```text\nnuxt.config.js\n```\n\n```js\nstyleResources: {\n scss: [\n '~/assets/global-inject.scss',\n ],\n hoistUseStatements: true,\n },\n```\n\n```text\nhoistUseStatements\n```\n\n```text\nstyleResources\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n@use \"sass:math\";\n```\n\n```text\nglobal-inject.scss\n```\n\n```js\n{\n build: {\n loaders: {\n scss: {\n additionalData: `\n @use \"@/styles/colors.scss\" as *;\n @use \"@/styles/overrides.scss\" as *;\n `,\n },\n },\n ...\n}\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- Well your answer explains the problem, my question is more related to how i solve it. Specifically in Vue components in a Nuxt setup. I have fixed the warnings coming from `.scss`-files, but not managed to fix them in my components.\n- @Lars you're talking about the `Using / for division is deprecated and will be removed in Dart Sass 2.0.0` issue or the `@use rules must be written before any other rules` one?\n- `@use rules must be written before any other rules` is the \"main\" issue. The rest of the question was primarily for describing how i got there.","metadata":{"transformedAt":"2026-08-18T18:33:07.877Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":254,"estimatedTokens":1285}}552{"id":"stack-66470258","source":"stackoverflow","questionId":66470258,"title":"500 Internal Server Error when uploading to an AWS S3 bucket from Nuxt","tags":["vue.js","amazon-s3","nuxt.js","amazon-cognito","http-status-code-500"],"text":"Title: 500 Internal Server Error when uploading to an AWS S3 bucket from Nuxt\nTags: vue.js, amazon-s3, nuxt.js, amazon-cognito, http-status-code-500\nSource: Stack Overflow\n\nQuestion:\nI am trying to upload a file to AWS S3 using aws-sdk v3 from a Nuxt app's Vue Component.\n\nHere's how I upload it.\n\n```\n\nexport default {\n...\nmethods: {\nonSubmit(event) {\n event.preventDefault()\n this.addPhoto()\n},\naddPhoto() {\n // Load the required clients and packages\n const { CognitoIdentityClient } = require('@aws-sdk/client-cognito-identity')\n const { fromCognitoIdentityPool } = require('@aws-sdk/credential-provider-cognito-identity')\n const {\n S3Client,\n PutObjectCommand,\n ListObjectsCommand,\n DeleteObjectCommand,\n } = require('@aws-sdk/client-s3')\n\n const REGION = 'us-east-1' // REGION\n const albumBucketName = 'samyojya-1'\n const IdentityPoolId = 'XXXXXXX'\n\n const s3 = new S3Client({\n region: REGION,\n credentials: {\n accessKeyId: this.$config.CLIENT_ID,\n secretAccessKey: this.$config.CLIENT_SECRET,\n sessionToken: localStorage.getItem('accessToken'),\n },\n })\n\n var file = this.formFields[0].fieldName\n var fileName = this.formFields[0].fieldName.name\n var photoKey = 'user-dp/' + fileName\n var s3Response = s3.send(\n new PutObjectCommand({\n Bucket: albumBucketName,\n Key: photoKey,\n Body: file,\n }),\n )\n s3Response\n .then((response) => {\n console.log('Successfully uploaded photo.' + JSON.stringify(response))\n })\n .catch((error) => {\n console.log(\n 'There was an error uploading your photo: Error stacktrace' + JSON.stringify(error.message),\n )\n const { requestId, cfId, extendedRequestId } = error.$metadata\n console.log({ requestId, cfId, extendedRequestId })\n })\n},\n\n...\n\n}\n\n```\n\nThe issue now is that the browser complains about CORS.\n\nhttps://i.sstatic.net/8IV3N.png\n\nThis is my CORS configuration on AWS S3\n\nhttps://i.sstatic.net/GCKq6.png\n\n- I'm suspecting something while creating the upload request using SDK. (I'm open to use an API that is better than what I'm using).\n\n- Nuxt setting that allows CORS.\n\n- Something else on S3 CORS config at permissions\nNetwork tab on chrome dev tools shows Internal Server Error (500) for prefetch. (Don't know why we see 2 entries here)\nhttps://i.sstatic.net/WPUtx.png\nhttps://i.sstatic.net/UIJaY.png\nAppreciate any pointers on how to debug this.\n\n========================================\n\nTop Answer:\nI was having the same issue today. The S3 logs were saying it returned a 200 code response, but Chrome was seeing a 500 response. In Safari, the error showed up as:\n\n```\nreceived 'us-west-1'; expected 'eu-west-1'\n```\n\nAdding `region: 'eu-west-1'` (i.e. the region where the bucked was created)to the parameters when creating the S3 service solved the issue for me.\n\nhttps://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-region.html#setting-region-constructor\n\n========================================\n\nCode:\n```js\n<script>\nexport default {\n...\nmethods: {\nonSubmit(event) {\n event.preventDefault()\n this.addPhoto()\n},\naddPhoto() {\n // Load the required clients and packages\n const { CognitoIdentityClient } = require('@aws-sdk/client-cognito-identity')\n const { fromCognitoIdentityPool } = require('@aws-sdk/credential-provider-cognito-identity')\n const {\n S3Client,\n PutObjectCommand,\n ListObjectsCommand,\n DeleteObjectCommand,\n } = require('@aws-sdk/client-s3')\n\n const REGION = 'us-east-1' // REGION\n const albumBucketName = 'samyojya-1'\n const IdentityPoolId = 'XXXXXXX'\n\n const s3 = new S3Client({\n region: REGION,\n credentials: {\n accessKeyId: this.$config.CLIENT_ID,\n secretAccessKey: this.$config.CLIENT_SECRET,\n sessionToken: localStorage.getItem('accessToken'),\n },\n })\n\n var file = this.formFields[0].fieldName\n var fileName = this.formFields[0].fieldName.name\n var photoKey = 'user-dp/' + fileName\n var s3Response = s3.send(\n new PutObjectCommand({\n Bucket: albumBucketName,\n Key: photoKey,\n Body: file,\n }),\n )\n s3Response\n .then((response) => {\n console.log('Successfully uploaded photo.' + JSON.stringify(response))\n })\n .catch((error) => {\n console.log(\n 'There was an error uploading your photo: Error stacktrace' + JSON.stringify(error.message),\n )\n const { requestId, cfId, extendedRequestId } = error.$metadata\n console.log({ requestId, cfId, extendedRequestId })\n })\n},\n\n...\n\n}\n</script>\n```\n\n```text\nAccess-Control-Allow-Origin\n```\n\n```text\nreceived 'us-west-1'; expected 'eu-west-1'\n```\n\n```text\nregion: 'eu-west-1'\n```\n\n```text\n{\n\"Version\": \"2008-10-17\",\n\"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"AWS\": \"*\"\n },\n \"Action\": [\n \"s3:GetObjectAcl\",\n \"s3:GetObject\",\n \"s3:PutObject\",\n \"s3:PutObjectAcl\",\n \"s3:ListMultipartUploadParts\"\n ],\n \"Resource\": \"arn:aws:s3:::YOUR_BUCKET_NAME/*\",\n \"Condition\": {\n \"StringLike\": {\n \"aws:Referer\": \"https://example/*\"\n }\n }\n }\n]}\n```\n\n```text\nconst s3 = new aws.S3({\n apiVersion: 'latest',\n accessKeyId: process.env.AWS_ACCESS_KEY_ID_CUSTOM,\n secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY_CUSTOM,\n region: 'us-west-1',\n})\n```\n\n========================================\n\nComments:\n- See stackoverflow.com/a/45356752/441757\n- You are right about the backend part @kissu. The backend here is aws s3. aws-sdk's s3 client calls s3 server. s3 server needs to return the header as configured in the v3 bucket permissions - CORS policy. Weird! :-/\n- So yeah, go to your backend dashboard and edit it to allow for the required header !\n- I got you now. I reset the \"AllowedHeaders\" parameter to 'Access-Control-Allow-Origin' in s3 bucket permissions CORS policy and tried upload. It doesn't work.\n- I enabled server access logs on s3 bucket. Will see if something interesting shows up there. It looks like it takes some time to collect and pass on the logs.\n- This is a good suggestion, I feel. I will give it a shot. My only challenge here is to find out the \"Logins\" provider object for Cognito User pool Client in the Cognito Identity Object.\n- Please feel free to message me back if you figure it out. I am still struggling with it so it would be nice to get some insight if u figure it out. Thanks!\n- Thanks for sharing this. I just noticed that my s3 bucket was indeed pointing to a different region. Now my error changed from 500 to 403. That's still a progress I would say. Waiting for access logs to appear to debug further. Will revert.\n- Here's what I see on the s3 access logs... \"a1bc55fcae7ba9acea6e082e6a6df67be958670c5a007dfa28aa6f0470f‌​9e19e samyojya-1 [06/May/2021:10:46:44 +0000] 49.206.4.117 - KSM4CMAWAYZC7CY2 REST.OPTIONS.PREFLIGHT - \"OPTIONS / HTTP/1.1\" 403 AccessForbidden 514 - 19 - \"dev.samyojya.com:3000\" \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36\" - c5uqa8Cs0mCqUYp5G5uBRWwGyLov5g6mBcEB7RPp3krNmQywg4wTI+xLp+ld‌​O2HwvifksZ6PAio= - ECDHE-RSA-AES128-GCM-SHA256 - samyojya-1.s3.ap-south-1.amazonaws.com TLSv1.2\"\n- I tried changing the bucket policy. Seeing the same error. @Gabriel. aws.S3 is looking like v2 - the older version. I am using v3.","metadata":{"transformedAt":"2026-08-18T18:33:07.877Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":227,"estimatedTokens":1823}}553{"id":"stack-59810929","source":"stackoverflow","questionId":59810929,"title":"Testing setup for Nuxt + Vuex + Vuetify with Jest","tags":["javascript","vue.js","jestjs","vuetify.js","nuxt.js"],"text":"Title: Testing setup for Nuxt + Vuex + Vuetify with Jest\nTags: javascript, vue.js, jestjs, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI spent one day solving undocumented issues regarding testing setup for Nuxt + Vuex + Vuetify with Jest.\n\nI had issues like:\n\n`Unknown custom element: - When running jest unit tests`\n\n`Cannot read property 'register' of undefined`\n\n`[Vuetify] Multiple instances of Vue detected`\n\n========================================\n\nCode:\n```text\nUnknown custom element: <nuxt-link> - When running jest unit tests\n```\n\n```text\nCannot read property 'register' of undefined\n```\n\n```text\n[Vuetify] Multiple instances of Vue detected\n```\n\n```text\n// ./jest.config.js\n\nmodule.exports = {\n // ... other stuff\n setupFilesAfterEnv: ['./test/jest.setup.js']\n}\n```\n\n```text\n// ./test/jest.setup.js\n\nimport Vue from 'vue'\nimport Vuetify from 'vuetify'\nimport VueTestUtils from '@vue/test-utils'\n\nVue.use(Vuetify)\n\n// Mock Nuxt components\nVueTestUtils.config.stubs['nuxt'] = '<div />'\nVueTestUtils.config.stubs['nuxt-link'] = '<a><slot /></a>'\nVueTestUtils.config.stubs['no-ssr'] = '<span><slot /></span>'\n```\n\n```text\n// ./test/Header.test.js\n\nimport { mount, createLocalVue } from '@vue/test-utils'\nimport Vuetify from 'vuetify'\nimport Vuex from 'vuex'\n\nimport Header from '~/components/layout/Header'\n\nconst localVue = createLocalVue()\nlocalVue.use(Vuex)\n\nlet wrapper\n\nbeforeEach(() => {\n let vuetify = new Vuetify()\n\n wrapper = mount(Header, {\n store: new Vuex.Store({\n state: { products: [] }\n }),\n localVue,\n vuetify\n })\n})\n\nafterEach(() => {\n wrapper.destroy()\n})\n\ndescribe('Header', () => {\n test('is fully functional', () => {\n expect(wrapper.element).toMatchSnapshot()\n })\n})\n```\n\n========================================\n\nComments:\n- Just a heads up that stubbing with strings throws a console error: `[vue-test-utils]: Using a string for stubs is deprecated and will be removed in the next major version.`","metadata":{"transformedAt":"2026-08-18T18:33:07.877Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":95,"estimatedTokens":503}}554{"id":"stack-75801726","source":"stackoverflow","questionId":75801726,"title":"Adding local JS files to Nuxt 3","tags":["vue.js","nuxt.js","nuxt3.js"],"text":"Title: Adding local JS files to Nuxt 3\nTags: vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to add some local js files available in my `assets/js` folder, but to no success.\n\nThe error I get is: `http://localhost:3001/assets/js/app.js net::ERR_ABORTED 404 (Page not found: /assets/js/app.js)`\n\nThe way I try to do it is by adding it in `nuxt.config.js`:\n\n```\napp: {\n head: {\n script: [\n {'src': 'assets/js/plugins.init.js', body: true},\n {'src': 'assets/js/app.js', body: true}\n ],\n },\n},\n```\n\nand I tried adding it in the page as well:\n\n```\nuseHead({\nscript: [\n{\n src: `assets/js/app.js`,\n body: true,\n defer: true\n},\n{\n src: `assets/js/plugins.init.js`,\n body: true,\n defer: true\n},\n],\n})\n```\n\nWhat am I doing wrong? and how can I solve this issue?\n\n========================================\n\nCode:\n```text\napp: {\n head: {\n script: [\n {'src': 'assets/js/plugins.init.js', body: true},\n {'src': 'assets/js/app.js', body: true}\n ],\n },\n},\n```\n\n```text\nuseHead({\nscript: [\n{\n src: `assets/js/app.js`,\n body: true,\n defer: true\n},\n{\n src: `assets/js/plugins.init.js`,\n body: true,\n defer: true\n},\n],\n})\n```\n\n```text\nassets/js\n```\n\n```text\nhttp://localhost:3001/assets/js/app.js net::ERR_ABORTED 404 (Page not found: /assets/js/app.js)\n```\n\n```text\nnuxt.config.js\n```\n\n```js\nuseHead({\nscript: [\n {\n src: `/app.js`,\n tagPosition: 'bodyClose'\n defer: true\n },\n ],\n})\n```\n\n```js\napp: {\n head: {\n script: [\n {'src': '/plugins.init.js', tagPosition: 'bodyClose'},\n {'src': '/app.js', tagPosition: 'bodyClose'}\n ],\n },\n},\n```\n\n```text\npublic\n```\n\n```text\nstatic\n```\n\n```text\ntagPosition\n```\n\n```text\npages\n```\n\n```text\nnuxt.config.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.877Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":128,"estimatedTokens":429}}555{"id":"stack-57484558","source":"stackoverflow","questionId":57484558,"title":"Is it possible to call a component method in nuxt from a page?","tags":["vue.js","nuxt.js"],"text":"Title: Is it possible to call a component method in nuxt from a page?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm starting to work with Vue.js and I'm using Nuxt.js. \nI've created a component (a snackbar) and inside this component I created a method \"showSnackbar\" that works passing 2 parameters: color and text.\nSo when I call showSnackbar(color,text), it appears.\n\nBut, I want to call this method from a page. Because I want to use this snackbar in some pages and I don't want to write the same code all the time, so that's the reason why I decided to create a component. But I can't call from a page the method inside this component.\n\nAnd that's why I wonder if is it that possible to call a component method from a page (where of course I import the component)\n\n========================================\n\nCode:\n```text\nimport Vue from \"vue\";\nimport snackbar from \"~/plugins/snackbar/snackbar\";\n\nVue.use(snackbar);\n```\n\n```text\n...\n /*\n ** Plugins to load before mounting the App\n ** Doc: https://nuxtjs.org/guide/plugins\n */\n plugins: [\"~/plugins/snackbar/index.js\"],\n ...\n```\n\n```text\nimport snackbar from \"~/plugins/snackbar/snackbar.vue\";\n\nconst Plugin = {\n install(Vue, options = {}) {\n /**\n * Makes sure that plugin can be installed only once\n */\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n /**\n * Create event bus\n */\n\n this.event = new Vue();\n\n /**\n * Plugin methods\n */\n Vue.prototype.$snackbar = {\n show(options = {}) {\n Plugin.event.$emit(\"show\", options, true);\n }\n };\n\n /**\n * Registration of <snackbar/> component\n */\n Vue.component(\"snackbar\", snackbar);\n }\n};\n\nexport default Plugin;\n```\n\n```text\n<template>\n <div>\n <transition name=\"snackbar\">\n <div v-if=\"show\" :class=\"['snackbar', 'box-shadow', type]\">\n <slot>{{ options.text }}</slot>\n </div>\n </transition>\n\n <pre>options: {{ options }}</pre>\n <pre>show: {{ show }}</pre>\n <pre>type: {{ type }}</pre>\n </div>\n</template>\n\n<script>\nimport snackbar from \"~/plugins/snackbar/snackbar\";\n\nexport default {\n data: () => ({\n options: {\n text: \"\",\n type: \"\"\n },\n show: false,\n type: \"\",\n timer: 0\n }),\n beforeMount() {\n snackbar.event.$on(\"show\", options => {\n this.options = options;\n this.type = options.type;\n this.show = true;\n this.close(this.options.closeWait || 3000);\n });\n },\n methods: {\n close(timeout) {\n clearTimeout(this.timer);\n this.timer = setTimeout(() => {\n this.show = false;\n }, timeout);\n }\n }\n};\n</script>\n\n<style>\n.snackbar {\n min-width: 300px;\n margin-left: -150px;\n background-color: #F48024;\n color: #fff;\n text-align: center;\n border-radius: 5px;\n padding: 16px;\n position: fixed;\n z-index: 1;\n left: 50%;\n bottom: 30px;\n}\n\n.snackbar.success {\n background-color: rgb(71, 244, 36);\n}\n\n.snackbar.danger {\n background-color: rgb(244, 36, 47);\n}\n\n.snackbar-enter-active {\n animation: snackbar-in 0.8s;\n}\n.snackbar-leave-active {\n animation: snackbar-in 0.8s reverse;\n}\n@keyframes snackbar-in {\n 0% {\n transform: scale(0);\n }\n 50% {\n transform: scale(1.2);\n }\n 100% {\n transform: scale(1);\n }\n}\n\n.box-shadow {\n -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3),\n 0 0 40px rgba(0, 0, 0, 0.1) inset;\n -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3),\n 0 0 40px rgba(0, 0, 0, 0.1) inset;\n box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;\n}\n</style>\n```\n\n```text\nthis.$snackbar.show({\n text: \"Hello, snackbar!\",\n type: \"success\"\n});\n```\n\n```text\n<snackbar/>\n```\n\n```text\nthis.$snackbar.open({someOptions: '...'})\n```\n\n```text\n./plugins/snackbar\n```\n\n```text\n./plugins/snackbar/index.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n./plugins/snackbar/snackbar.js\n```\n\n```text\n./plugins/snackbar/snackbar.vue\n```\n\n```text\n<snackbar/>\n```\n\n========================================\n\nComments:\n- And the magic happens! Thank you for your answer, very useful. It's worked perfectly and something new that I learned\n- np, glad it helped","metadata":{"transformedAt":"2026-08-18T18:33:07.877Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":213,"estimatedTokens":1031}}556{"id":"stack-54702012","source":"stackoverflow","questionId":54702012,"title":"How to use dynamic CSS files with Nuxt?","tags":["javascript","css","vue-router","nuxt.js"],"text":"Title: How to use dynamic CSS files with Nuxt?\nTags: javascript, css, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm working in a project that have different users with their logos.\nBased on the API call I want to load a different CSS with different colour palette.\n\nNow I have a `css` folder inside `assets` folder with `main.js` (with my custom font styles, etc) and another files in there for the custom color palette: `-palette.css`.\n\nIn my `nuxt.config` I'm calling the CSS colour like that:\n\n```\ncss: [\n '~/assets/style/app.styl',\n '~/assets/css/main.css',\n '~/assets/css/orange-palette.css'\n ],\n```\n\nIs there any way to bind the CSS file depending on the URL path/API call instead of putting the path there?\n\nI'm not sure if I can use it on templates as well, binding the CSS files in there. Is it possible?\n\nThanks\n\n========================================\n\nTop Answer:\nYou can use \"head\" in page component. https://codesandbox.io/s/xr55o4yqmq\n\n```\n\nexport default {\n head: {\n link: [\n {\n rel: \"stylesheet\",\n href: \"/about.css\"\n }\n ]\n }\n};\n\n```\n\n========================================\n\nCode:\n```text\ncss: [\n '~/assets/style/app.styl',\n '~/assets/css/main.css',\n '~/assets/css/orange-palette.css'\n ],\n```\n\n```text\ncss\n```\n\n```text\nassets\n```\n\n```text\nmain.js\n```\n\n```text\n<color-name>-palette.css\n```\n\n```text\nnuxt.config\n```\n\n```text\n<template>\n <section>\n <h1>Index</h1>\n <button @click=\"swap\">swap</button>\n <p v-text=\"cur\" />\n </section>\n</template>\n\n<script>\nexport default {\n head() {\n return {\n link: [\n {\n rel: \"stylesheet\",\n href: `/${this.cur}.css`\n }\n ]\n };\n },\n data() {\n return {\n cur: \"light\"\n };\n },\n methods: {\n swap() {\n if (this.cur === \"light\") {\n this.cur = \"dark\";\n } else {\n this.cur = \"light\";\n }\n }\n }\n};\n</script>\n```\n\n```text\nhead()\n```\n\n```text\nhead: {}\n```\n\n```text\n<script>\nexport default {\n head: {\n link: [\n {\n rel: \"stylesheet\",\n href: \"/about.css\"\n }\n ]\n }\n};\n</script>\n```\n\n========================================\n\nComments:\n- Cool, I can put all my css files on head in the pages but how I can call the correct one based on the client API call/URL? =/","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":143,"estimatedTokens":565}}557{"id":"stack-71944877","source":"stackoverflow","questionId":71944877,"title":"How to send form data in POST request in Nuxtjs 3","tags":["vue.js","post","axios","nuxt.js","nuxt3.js"],"text":"Title: How to send form data in POST request in Nuxtjs 3\nTags: vue.js, post, axios, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nAm working on a static website but I need to contact form which is suppose to send form data to an email, Am using nuxtjs 3, have tried using *useFetch()*, am also trying to use *axios*.\n\nHere is what I have\n\n**Contact Vue Template**\n\n```\n\n \n \n \n \n \n \n \n \n \n \n \n Mail\n hi@paddi.ng\n \n\n \n Location\n Lagos, Nigeria\n \n \n \n OR\n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n Send Message\n \n \n\n \n \n \n \n \n\n```\n\n**Contact Script**\n\n```\n\n interface formData {\n full_name: string,\n email: string,\n phone_no: string,\n service: string,\n message: string,\n }\n\n let formStatus: {} = {\n loading: false,\n success: false,\n error: false,\n }\n\n let formData: formData = {\n full_name: \"\",\n email: \"\",\n phone_no: \"\",\n service: \"\",\n message: \"\",\n };\n\n async function submitForm() {\n\n // console.log(data);\n // console.log(JSON.stringify(formData));\n // this.formStatus.loading = true,\n // await this.$axios.$post(\"/api/contact\", {\n // full_name: this.full_name,\n // email: this.email,\n // phone_name: this.phone_name,\n // service: this.service,\n // message: this.message\n // }).then(response => {\n // this.success = true\n // this.errored =false\n // }).catch(error => {\n // this.errored = true\n // }).finally(() => {\n // this.loading = false\n // });\n }\n\n // return {\n // formData: formData\n // }\n\n```\n\nMain Question is How to send form data in POST request in Nuxtjs 3.\n\n========================================\n\nCode:\n```text\n<template>\n <section id=\"ng-ctt\" class=\"ng-ctt\">\n <div class=\"ng-ct\">\n <div class=\"ng-fx\">\n <div class=\"ng-fx6-m\">\n <figure class=\"ng-ctt-img\">\n <img src=\"~/assets/media/illustrations/contact.svg\" alt=\"ctt img\" class=\"ng-img\">\n </figure>\n </div>\n <div class=\"ng-fx6-m\">\n <div class=\"ng-fxc\">\n <div class=\"ng-ctt-text\">\n <span class=\"ng-title\">Mail</span>\n <NuxtLink to=\"mailto:hi@paddi.ng\" class=\"ng-link\">hi@paddi.ng</NuxtLink>\n </div>\n\n <div class=\"ng-ctt-text\">\n <span class=\"ng-title\">Location</span>\n <span class=\"ng-text\">Lagos, Nigeria</span>\n </div>\n \n <div class=\"ng-ctt-text\">\n <span class=\"ng-ctt-text-or\">OR</span>\n </div>\n\n <form @submit.prevent=\"submitForm\" id=\"ng-fm\" class=\"ng-fm\">\n <div class=\"ng-fm-row\">\n <input type=\"text\" v-model=\"formData.full_name\" class=\"ng-inp\" placeholder=\"Full Name\">\n </div>\n <div class=\"ng-fm-row\">\n <input type=\"text\" v-model=\"formData.email\" class=\"ng-inp\" placeholder=\"Email\">\n </div>\n <div class=\"ng-fm-row\">\n <input type=\"text\" v-model=\"formData.phone_no\" class=\"ng-inp\" placeholder=\"Phone Number\">\n </div>\n <div class=\"ng-fm-row\">\n <input type=\"text\" v-model=\"formData.service\" class=\"ng-inp\" placeholder=\"Service\">\n </div>\n <div class=\"ng-fm-row\">\n <textarea name=\"\" v-model=\"formData.message\" class=\"ng-inp\" placeholder=\"Message\"></textarea>\n </div>\n <div class=\"ng-fm-row\">\n <button class=\"ng-bt-pri\" type=\"submit\">Send Message</button>\n </div>\n </form>\n\n </div>\n </div>\n </div>\n </div>\n </section>\n</template>\n```\n\n```text\n<script lang=\"ts\" setup>\n interface formData {\n full_name: string,\n email: string,\n phone_no: string,\n service: string,\n message: string,\n }\n\n let formStatus: {} = {\n loading: false,\n success: false,\n error: false,\n }\n\n let formData: formData = {\n full_name: \"\",\n email: \"\",\n phone_no: \"\",\n service: \"\",\n message: \"\",\n };\n\n async function submitForm() {\n\n // console.log(data);\n // console.log(JSON.stringify(formData));\n // this.formStatus.loading = true,\n // await this.$axios.$post(\"/api/contact\", {\n // full_name: this.full_name,\n // email: this.email,\n // phone_name: this.phone_name,\n // service: this.service,\n // message: this.message\n // }).then(response => {\n // this.success = true\n // this.errored =false\n // }).catch(error => {\n // this.errored = true\n // }).finally(() => {\n // this.loading = false\n // });\n }\n\n // return {\n // formData: formData\n // }\n\n</script>\n```\n\n```js\nmethods: {\n formSubmit() {\n\n this.formRequest().then( (result) => {\n console.log(result)\n }).catch( (error) => {\n console.error('Contact form could not be send', error)\n });\n },\n\n async formRequest() {\n\n return await $fetch( <your-form-endpoint>, { \n headers: {\n \"Content-Type\": \"multipart/form-data\",\n },\n method: 'POST',\n body: {\n 'message': <your-form-data>,\n 'name': <your-form-data>\n }\n } );\n }\n}\n```\n\n```text\n$fetch\n```\n\n```text\nContent-Type\n```\n\n```text\nmultipart/form-data\n```\n\n========================================\n\nComments:\n- `formData` should be part of the vue component. add `data () { return { formData } }` - v2.vuejs.org/v2/api/?redirect=true#data\n- Thank God, someone knows what they are doing. Thank you! Axios seemed much cleaner than this - I don't know why they have dropped it in Nuxt3\n- @Crimbo yeah in RC state nuxt `useFetch`composable seems pretty buggy and may have some breaking changes version to version. you have to read the update logs carefully. hope nuxt3 goes production soon to avoid these","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":276,"estimatedTokens":1430}}558{"id":"stack-62789608","source":"stackoverflow","questionId":62789608,"title":"How do I access localStorage in store of NuxtJs?","tags":["javascript","vue.js","vuex","nuxt.js"],"text":"Title: How do I access localStorage in store of NuxtJs?\nTags: javascript, vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get a value from localStorage to determine the value of a variable in store. I remember trying something similar with vuejs about a year ago and it seemed to work. I also have no issues with this on Reactjs. But for some reason i keep getting this error when doing the same in Nuxt\n\nhttps://i.sstatic.net/xNFjf.png\n\nhttps://i.sstatic.net/g491J.png\n\nthis is my user.js file\n\n```\nexport const state = () => ({\n isLoggedIn: !!localStorage.getItem('userDetails')\n})\n\nexport const mutations = {\n login(state) {\n state.isLoggedIn = true;\n },\n logout(state) {\n window.localStorage.clear()\n state.isLoggedIn = false;\n }\n}\n```\n\nam i approaching this problem wrong? or is this not supposed to work? Any help is appreciated.\n\n========================================\n\nTop Answer:\nWhen you use SSR you don't have access to the browser storage.\n\nTo do a workaround, you can dispatch an action on the mounted component hook.\n\n```\nmounted() {\n\n if(!process.client) return;\n const savedData = localStorage.getItem(\"userDetails\");\n if(savedData){\n this.$store.commit('myMutation',savedData)\n}\n}\n```\n\n========================================\n\nCode:\n```text\nexport const state = () => ({\n isLoggedIn: !!localStorage.getItem('userDetails')\n})\n\nexport const mutations = {\n login(state) {\n state.isLoggedIn = true;\n },\n logout(state) {\n window.localStorage.clear()\n state.isLoggedIn = false;\n }\n}\n```\n\n```text\nisLoggedIn: process.server ? '' : !!localStorage.getItem('userDetails')\n```\n\n```text\nprocess.server\n```\n\n```text\nmounted() {\n\n if(!process.client) return;\n const savedData = localStorage.getItem(\"userDetails\");\n if(savedData){\n this.$store.commit('myMutation',savedData)\n}\n}\n```\n\n```text\nuseCookie\n```\n\n========================================\n\nComments:\n- Are you doing ssr?\n- I believe so. Do I have to recreate the app as PWA for this to work? but then i'd be giving up the ssr. Is there another workaround? or recreating as PWA is the only way around this.\n- @Roj I added a new answer to get around the SSR problem\n- no error this time. It seems the problem has to do with ssr. I'll probably have to redo the whole project and disable ssr. Thanks anyway.\n- @Roj no error means you had access to the localstorage. well you can go to `nuxt.config.js` and rename `mode: \"universal\"` to `mode: \"spa\"` if you want to disable ssr and only go with client side\n- this is not the issue\n- thanks I'll try this. is there a way to commit on my mutation on the base app itself?\n- well you should wrap it in an if statement `if(process.client) {}`\n- Roj, you can do in the same way, in the mounted() hook. @ifaruki, yes, mine was just a way to indicate the path to go, but you right. I edited my answer\n- that wasnt that what i meant. it will throw an error again `localStorage` is not defined. you need to wrap everything in `if(process.client)`\n- what about in nuxt v 2.15 ?\n- page removed unfortunately\n- nuxt.com/docs/api/composables/use-cookie","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":107,"estimatedTokens":772}}559{"id":"stack-59935393","source":"stackoverflow","questionId":59935393,"title":"Apollo Server as Nuxt serverMiddleware","tags":["express","websocket","nuxt.js","apollo","subscription"],"text":"Title: Apollo Server as Nuxt serverMiddleware\nTags: express, websocket, nuxt.js, apollo, subscription\nSource: Stack Overflow\n\nQuestion:\nI've managed to have a express + Apollo Backend as a serverMiddleware in Nuxtjs.\nEverything works fine(auth, cache, datasources, queries, mutations) but now I'm trying to get subscriptions(websockets) running and its giving me a hard time.\n\nI tried this example https://www.apollographql.com/docs/apollo-server/data/subscriptions/#subscriptions-with-additional-middleware but even letting the httpServer listening didn't work.\n\nThis is my API file which I require through the nuxt.config.js with `'~/api/index'` :\n\n```\nmodule.exports = async () => {\n const app = require('express')()\n const server = await require(\"./apollo\")() // apollo-server-express w/ typeDefs and resolvers\n\n // apply Apollo to Express\n server.applyMiddleware({ app });\n console.log(`🚀 ApolloServer ready at ${server.graphqlPath}`);\n\n const httpServer = http.createServer(app);\n server.installSubscriptionHandlers(httpServer);\n console.log(`🚀 ApolloSubscriptions ready at ${server.subscriptionsPath}`);\n\n return {\n path: '/api',\n handler: httpServer\n }\n}\n```\n\nNow my playground is giving me this error: `\"Could not connect to websocket endpoint ws://192.168.150.98:3000/api/graphql. Please check if the endpoint url is correct.\"`\n\nTypeDefs:\n\n```\ntype Subscription {\n postAdded: Post\n}\ntype Post {\n author: String\n comment: String\n}\ntype Query {\n posts: [Post]\n}\ntype Mutation {\n addPost(author: String, comment: String): Post\n}\n```\n\nResolvers:\n\n```\nQuery: {\n posts(root, args, context) {\n return Posts;\n }\n}\nMutation: {\n addPost(root, args, context) {\n pubsub.publish(POST_ADDED, { postAdded: args });\n return Posts.add(args);\n }\n},\nSubscription: {\n postAdded: {\n // Additional event labels can be passed to asyncIterator creation\n subscribe: () => pubsub.asyncIterator([POST_ADDED]),\n },\n}\n```\n\nFirst question here, thank u in advance! :)\n\n========================================\n\nTop Answer:\nit can also be a little easier\n\n1.\n\n```\nyarn add apollo-server-express\n```\n\nor\n\n```\nnpm install apollo-server-express\n```\n\n- create file ./server/index.js\n\n```\nimport { ApolloServer, gql } from 'apollo-server-express'\n\n // Construct a schema, using GraphQL schema language\nconst typeDefs = gql`\n type Query {\n hello: String\n }\n`\n\n// Provide resolver functions for your schema fields\nconst resolvers = {\n Query: {\n hello: () => 'Hello world!',\n },\n}\n\nconst server = new ApolloServer({ typeDefs, resolvers })\n\nexport default server\n```\n\n- add in your nuxt.config.js\n\n```\nimport server from './server'\n\nexport default {\n// ... your nuxt config stuff\n// ...\n hooks: {\n render: {\n async before({\n nuxt: {\n server: { app },\n },\n }) {\n await server.applyMiddleware({ app, path: '/api' })\n console.log(`🚀 ApolloServer ready at /api`)\n },\n },\n }\n}\n```\n\n========================================\n\nCode:\n```js\nmodule.exports = async () => {\n const app = require('express')()\n const server = await require(\"./apollo\")() // apollo-server-express w/ typeDefs and resolvers\n\n // apply Apollo to Express\n server.applyMiddleware({ app });\n console.log(`🚀 ApolloServer ready at ${server.graphqlPath}`);\n\n const httpServer = http.createServer(app);\n server.installSubscriptionHandlers(httpServer);\n console.log(`🚀 ApolloSubscriptions ready at ${server.subscriptionsPath}`);\n\n return {\n path: '/api',\n handler: httpServer\n }\n}\n```\n\n```text\ntype Subscription {\n postAdded: Post\n}\ntype Post {\n author: String\n comment: String\n}\ntype Query {\n posts: [Post]\n}\ntype Mutation {\n addPost(author: String, comment: String): Post\n}\n```\n\n```js\nQuery: {\n posts(root, args, context) {\n return Posts;\n }\n}\nMutation: {\n addPost(root, args, context) {\n pubsub.publish(POST_ADDED, { postAdded: args });\n return Posts.add(args);\n }\n},\nSubscription: {\n postAdded: {\n // Additional event labels can be passed to asyncIterator creation\n subscribe: () => pubsub.asyncIterator([POST_ADDED]),\n },\n}\n```\n\n```text\n'~/api/index'\n```\n\n```text\n\"Could not connect to websocket endpoint ws://192.168.150.98:3000/api/graphql. Please check if the endpoint url is correct.\"\n```\n\n```js\nimport http from 'http'\n\nexport default function () {\n this.nuxt.hook('render:before', async () => {\n const server = require(\"./apollo\")()\n \n // apply Apollo to Express\n server.applyMiddleware({ app: this.nuxt.renderer.app });\n console.log(`🚀 ApolloServer ready at ${server.graphqlPath}`);\n \n const httpServer = http.createServer(this.nuxt.renderer.app);\n \n // apply SubscriptionHandlers to httpServer\n server.installSubscriptionHandlers(httpServer);\n console.log(`🚀 ApolloSubscriptions ready at ${server.subscriptionsPath}`);\n\n // overwrite nuxt.server.listen()\n this.nuxt.server.listen = (port, host) => new Promise(resolve => httpServer.listen(port || 3000, host || 'localhost', resolve))\n \n // close this httpServer on 'close' event\n this.nuxt.hook('close', () => new Promise(httpServer.close))\n })\n}\n```\n\n```js\nconst consola = require('consola')\nconst Hapi = require('@hapi/hapi')\nconst HapiNuxt = require('@nuxtjs/hapi')\n\nasync function start () {\n const server = require('./apollo/index')()\n const app = new Hapi.Server({\n host: process.env.HOST || '127.0.0.1',\n port: process.env.PORT || 3000\n })\n\n await app.register({\n plugin: HapiNuxt\n })\n \n app.route(await require('./routes')())\n \n await server.applyMiddleware({\n app,\n path: '/graphql'\n });\n console.log(`🚀 ApolloServer ready at ${server.graphqlPath}`);\n await server.installSubscriptionHandlers(app.listener)\n console.log(`🚀 ApolloSubscriptions ready at ${server.subscriptionsPath}`);\n\n await app.start()\n\n consola.ready({\n message: `Server running at: ${app.info.uri}`,\n badge: true\n })\n}\nprocess.on('unhandledRejection', error => consola.error(error))\nstart().catch(error => console.log(error))\n```\n\n```text\nnpx create-nuxt-app\n```\n\n```text\nyarn add apollo-server-express\n```\n\n```text\nnpm install apollo-server-express\n```\n\n```js\nimport { ApolloServer, gql } from 'apollo-server-express'\n\n // Construct a schema, using GraphQL schema language\nconst typeDefs = gql`\n type Query {\n hello: String\n }\n`\n\n// Provide resolver functions for your schema fields\nconst resolvers = {\n Query: {\n hello: () => 'Hello world!',\n },\n}\n\nconst server = new ApolloServer({ typeDefs, resolvers })\n\nexport default server\n```\n\n```js\nimport server from './server'\n\nexport default {\n// ... your nuxt config stuff\n// ...\n hooks: {\n render: {\n async before({\n nuxt: {\n server: { app },\n },\n }) {\n await server.applyMiddleware({ app, path: '/api' })\n console.log(`🚀 ApolloServer ready at /api`)\n },\n },\n }\n}\n```\n\n```text\nconst { ApolloServer, gql } = require('apollo-server-express')\nconst express = require('express')\n\nconst typeDefs = gql`\n type Query {\n hello: String\n }\n`\n\nconst resolvers = {\n Query: {\n hello: () => 'Hello world!',\n },\n}\n\nconst server = new ApolloServer({ typeDefs, resolvers })\nconst app = express()\n\napp.use(express.json())\napp.use(express.urlencoded({ extended: true }))\napp.use(server.getMiddleware())\n\nmodule.exports = app\n```\n\n```text\n{\n // other nuxt config ...\n serverMiddleware: [{ path: '/api', handler: '~/api/index.js' }],\n}\n```\n\n```text\ngetMiddleware()\n```\n\n```text\n./api/index.js\n```\n\n```text\n./nuxt.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":369,"estimatedTokens":1862}}560{"id":"stack-61270764","source":"stackoverflow","questionId":61270764,"title":"How to make Vuetify App bar scrollable horizontally","tags":["vue.js","vuetify.js","nuxt.js"],"text":"Title: How to make Vuetify App bar scrollable horizontally\nTags: vue.js, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm struggling with Vuetify App bar to make it scrollable horizontally.\n\nIs it possible to make it scrollable or collapsable in any way?\nI'm using Nuxt/Vuetify to build a platform.\nthis is the image of web view\n\nThis is the image of mobile view\n\n========================================\n\nTop Answer:\nNo option by Vuetify API. Any way you could use the idea/concept you find her (Basic CSS not related to vue/vuetify):\nhttps://www.w3schools.com/howto/howto_css_menu_horizontal_scroll.asp -or- https://iamsteve.me/blog/entry/horizontal-scrolling-responsive-menu\n\n```\nstyle=\"overflow-x:auto; white-space: nowrap;\"\n```\n\n**Example:**\n\n\r\n\r\n\n```\nnew Vue({\r\n el: '#app',\r\n vuetify: new Vuetify(),\r\n \r\n})\n```\n\n\r\n\n```\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n mdi-heart\r\n \r\n \r\n mdi-domain\r\n \r\n \r\n mdi-message\r\n \r\n \r\n mdi-magnify\r\n \r\n \r\n mdi-email\r\n \r\n \r\n mdi-call-split\r\n \r\n \r\n mdi-magnify\r\n \r\n \r\n mdi-call-split\r\n \r\n mdi-magnify\r\n \r\n \r\n mdi-heart\r\n \r\n \r\n mdi-domain\r\n \r\n \r\n mdi-message\r\n \r\n \r\n mdi-magnify\r\n \r\n \r\n mdi-domain\r\n \r\n \r\n mdi-message\r\n \r\n \r\n mdi-magnify\r\n \r\n \r\n\r\n \r\n \r\n \r\n\r\n\r\n\r\n\n```\n\n\r\n\r\n\r\n\nUse Media-Q if you want to disable this idea on desktop.\n\n========================================\n\nCode:\n```text\n<v-app id=\"inspire\" flex>\n <v-app-bar\n absolute\n color=\"cyan accent-3\">\n <div class=\"d-flex flex-row align-center col-12\">\n <div class=\"col-8 col-md-8\">\n <v-slide-group show-arrows v-model=\"model\">\n <v-slide-item v-slot:default=\"{ active, toggle }\"\n key=\"a\">\n <v-btn icon @click=\"toggle\">\n <v-icon>mdi-account-group</v-icon>\n </v-btn>\n </v-slide-item>\n <v-slide-item v-slot:default=\"{ active, toggle }\" key=\"b\">\n <v-btn icon @click=\"toggle\">\n <v-icon>mdi-shield</v-icon>\n </v-btn>\n </v-slide-item>\n <v-slide-item v-slot:default=\"{ active, toggle }\" key=\"c\">\n <v-btn icon @click=\"toggle\">\n <v-icon>mdi-school</v-icon>\n </v-btn>\n </v-slide-item>\n <v-slide-item v-slot:default=\"{ active, toggle }\" key=\"d\">\n <v-btn icon @click=\"toggle\">\n <v-icon>mdi-book-open</v-icon>\n </v-btn>\n </v-slide-item>\n <v-slide-item v-slot:default=\"{ active, toggle }\" key=\"e\">\n <v-btn icon @click=\"toggle\">\n <v-icon>mdi-grid</v-icon>\n </v-btn>\n </v-slide-item>\n <v-slide-item v-slot:default=\"{ active, toggle }\" key=\"f\">\n <v-btn icon @click=\"toggle\">\n <v-icon>mdi-link</v-icon>\n </v-btn>\n </v-slide-item>\n </v-slide-group>\n </div>\n <v-spacer></v-spacer>\n <v-btn icon>\n <v-icon>mdi-face</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-door</v-icon>\n </v-btn>\n </div>\n </v-app-bar>\n <v-content>\n <v-container class=\"mt-10\">\n <v-row>\n <v-col>\n You have clicked on {{model}} link\n </v-col>\n </v-row>\n </v-container>\n </v-content>\n </v-app>\n```\n\n```text\nstyle=\"overflow-x:auto; white-space: nowrap;\"\n```\n\n```js\nnew Vue({\n el: '#app',\n vuetify: new Vuetify(),\n \n})\n```\n\n```html\n<link href=\"https://cdn.jsdelivr.net/npm/vuetify@2.2.22/dist/vuetify.min.css\" rel=\"stylesheet\"/>\n<link href=\"https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css\" rel=\"stylesheet\"/>\n\n\n<div id=\"app\">\n <v-app id=\"inspire\">\n <div>\n <v-app-bar\n color=\"deep-purple accent-4\"\n dense\n dark\n >\n <v-app-bar-nav-icon></v-app-bar-nav-icon>\n <v-spacer></v-spacer>\n <div style=\"overflow-x:auto; white-space: nowrap;\">\n <v-btn icon>\n <v-icon>mdi-heart</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-domain</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-message</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-magnify</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-email</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-call-split</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-magnify</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-call-split</v-icon>\n </v-btn> <v-btn icon>\n <v-icon>mdi-magnify</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-heart</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-domain</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-message</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-magnify</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-domain</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-message</v-icon>\n </v-btn>\n <v-btn icon>\n <v-icon>mdi-magnify</v-icon>\n </v-btn>\n </div>\n\n </v-app-bar>\n </div>\n </v-app>\n</div>\n\n<script src=\"https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/vuetify@2.2.22/dist/vuetify.min.js\"></script>\n```\n\n========================================\n\nComments:\n- Read the documentation for toolbars: vuetifyjs.com/en/components/toolbars/#toolbars. There is a prop called collapse which might help you.\n- Thanks for the reply. I want it without the scroller.\n- w3schools.com/howto/howto_css_hide_scrollbars.asp\n- then I cant scroll if we hide scroll bar\n- This is why on desktop the scroll bar should be visible hh. For custom design scrollbar use css. For scroll by drag use js. This is the answer to your q anyway.\n- This will be similar to what I want. we only need to hide the arrow button left and right. and make the slide group a little bit wider","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":274,"estimatedTokens":1489}}561{"id":"stack-75428668","source":"stackoverflow","questionId":75428668,"title":"Page Title Set By Content Module Does Not Change Back After Navigation","tags":["nuxt.js","nuxt3.js","nuxt-content"],"text":"Title: Page Title Set By Content Module Does Not Change Back After Navigation\nTags: nuxt.js, nuxt3.js, nuxt-content\nSource: Stack Overflow\n\nQuestion:\nI am using Nuxt 3 and Nuxt Content for my site. I set a default page title inside the `nuxt.config.ts` file (see Documentation: SEO and Meta), and the Content module sets the title on every page that uses it. However, returning to any other page does not reset the page title. It keeps the value from the last MarkDown file and does not change back to the global page title. Navigating to another MarkDown page changes the title, but it never changes back from the last value set by the module.\n\nI also tried setting the title through the useHead composable instead of the runtime configuration, but with the same result.\n\nAm I doing something wrong, and if so, how can I solve this? Or is this a known bug?\n\n========================================\n\nTop Answer:\nAs muell said, the title is being overidden. I have this issue using ``, ``, and `` as part of Nuxt Content. By looking at the Automation section of the documentation on `useContentHead`, I found a solution by adding the following to the nuxt.config.js\n\n```\nexport default defineNuxtConfig({\n content: {\n contentHead: false\n }\n})\n```\n\nThen, in app.vue I did useSeoMeta like so:\n\n```\n\nuseSeoMeta({\n title: 'your title goes here',\n ogTitle: 'your title goes here',\n description: 'your description here',\n ogDescription: 'your description here',\n})\n\n```\n\nThis seems to disable all the modifications to title by the content.\nHope this helps!\n\n========================================\n\nCode:\n```text\nnuxt.config.ts\n```\n\n```text\nuseHead()\n```\n\n```text\nuseHead()\n```\n\n```text\nuseHead()\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\napp.vue\n```\n\n```js\nexport default defineNuxtRouteMiddleware(() => {\n useSeoMeta({\n title: \"My default title\",\n description: \"My default description\"\n })\n})\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nmiddleware/resetMeta.global.ts\n```\n\n```text\nuseHead()\n```\n\n```text\nexport default defineNuxtConfig({\n content: {\n contentHead: false\n }\n})\n```\n\n```text\n<script setup lang=\"ts\">\nuseSeoMeta({\n title: 'your title goes here',\n ogTitle: 'your title goes here',\n description: 'your description here',\n ogDescription: 'your description here',\n})\n</script>\n```\n\n```text\n<ContentList>\n```\n\n```text\n<ContentDoc>\n```\n\n```text\n<ContentRenderer>\n```\n\n```text\nuseContentHead\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":122,"estimatedTokens":603}}562{"id":"stack-51251172","source":"stackoverflow","questionId":51251172,"title":"Nuxt.js + Bootstrap-Vue - Individual components and directives loading","tags":["vue.js","bootstrap-4","nuxt.js","bootstrap-vue"],"text":"Title: Nuxt.js + Bootstrap-Vue - Individual components and directives loading\nTags: vue.js, bootstrap-4, nuxt.js, bootstrap-vue\nSource: Stack Overflow\n\nQuestion:\nI'm working on integrating Bootstrap-Vue library into my Nuxt.js based project. I read through official documentation to get started but although importing bt-vue as a single module works fine, I would like to be able to import individual components and directives to reduce resulting file size and make my setup as afficient as possible. Documentation only provides a solution for a regular Vue.js project on this topic, but how can I write a plugin that would enable me to do the same with Nuxt?\n\nI started with creating a `bt-vue.ts` plugin like so:\n\n```\nimport Vue from 'vue'\nimport { Card } from 'bootstrap-vue/es/components';\n\nVue.use(Card);\n```\n\nI've imported this file into nuxt.config.js plugins section\n\n```\nplugins: [\n...\n'@/plugins/bt-vue'\n...\n]\n```\n\nbut when I try to compile my project I recieve this error:\n\n```\nnode_modules\\bootstrap-vue\\es\\components\\index.js:1\n (function (exports, require, module, __filename, __dirname) { import Alert from './alert';\n ^^^^^^\n\n SyntaxError: Unexpected token import\n at createScript (vm.js:80:10)\n at Object.runInThisContext (vm.js:139:10)\n at Module._compile (module.js:616:28)\n at Object.Module._extensions..js (module.js:663:10)\n at Module.load (module.js:565:32)\n at tryModuleLoad (module.js:505:12)\n at Function.Module._load (module.js:497:3)\n at Module.require (module.js:596:17)\n at require (internal/module.js:11:18)\n at r (C:\\Projects\\Wonder\\frontend-nuxt\\node_modules\\vue-server-renderer\\build.js:8330:16)\n at Object.bootstrap-vue/es/components (server-bundle.js:5771:18)\n at __webpack_require__ (webpack/bootstrap:25:0)\n at Module../plugins/bt-vue/index.ts (plugins/bt-vue/index.ts:1:0)\n at __webpack_require__ (webpack/bootstrap:25:0)\n at Module../.nuxt/index.js (.nuxt/index.js:1:0)\n at __webpack_require__ (webpack/bootstrap:25:0)\n```\n\n========================================\n\nTop Answer:\nAfter a lot of research and some fixes to bt-vue lib I've found a solution to this challenge.\nThis solution is intended for **Nuxt 2** and **won't work** with Nuxt 1:\nFirst you will need to create a plugin:\n\n\r\n\r\n\n```\nimport Vue from 'vue'\r\nimport Collapse from 'bootstrap-vue/es/components/collapse'\r\nimport Dropdown from 'bootstrap-vue/es/components/dropdown'\r\n\r\nVue.use(Collapse)\r\nVue.use(Dropdown)\n```\n\n\r\n\r\n\r\n\nWe will import only those components that we want to use. More info on that can be found in bt-vue docs under **Component groups and Directives as Vue plugins**\n\n**WARNING:** I suggest to stay away from such import syntax:\n\n`import { Modal } from 'bootstrap-vue/es/components';`\n\nsince it will import everything inside `components` directive anyway and pollute your final bundle with additional JS code since it won't be tree-shaked properly(webpack bug) and this can brake the whole purpose of such setup, so use explicit imports as stated above. \n\nthen connect it in nuxt.config.js:\n\n\r\n\r\n\n```\nexport default {\r\n build: {\r\n transpile: ['bootstrap-vue']\r\n },\r\n plugins: ['@/plugins/bt-vue']\r\n}\n```\n\n\r\n\r\n\r\n\nAs you can see there is no need to include a module since we are writing a plugin ourselves thus no problems with SSR! And we are using new Nuxt 2 `transpile` property to build our es6 bt-vue modules. Don't forget to include a reference to css since it comes separately. In my setup I just import SASS files from regular bootstrap package directly in my index.scss file and include it inside nuxt.config.js as usual.\n\n\r\n\r\n\n```\ncss: [\r\n '@/assets/scss/index.scss'\r\n ]\n```\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\nimport { Card } from 'bootstrap-vue/es/components';\n\nVue.use(Card);\n```\n\n```text\nplugins: [\n...\n'@/plugins/bt-vue'\n...\n]\n```\n\n```text\nnode_modules\\bootstrap-vue\\es\\components\\index.js:1\n (function (exports, require, module, __filename, __dirname) { import Alert from './alert';\n ^^^^^^\n\n SyntaxError: Unexpected token import\n at createScript (vm.js:80:10)\n at Object.runInThisContext (vm.js:139:10)\n at Module._compile (module.js:616:28)\n at Object.Module._extensions..js (module.js:663:10)\n at Module.load (module.js:565:32)\n at tryModuleLoad (module.js:505:12)\n at Function.Module._load (module.js:497:3)\n at Module.require (module.js:596:17)\n at require (internal/module.js:11:18)\n at r (C:\\Projects\\Wonder\\frontend-nuxt\\node_modules\\vue-server-renderer\\build.js:8330:16)\n at Object.bootstrap-vue/es/components (server-bundle.js:5771:18)\n at __webpack_require__ (webpack/bootstrap:25:0)\n at Module../plugins/bt-vue/index.ts (plugins/bt-vue/index.ts:1:0)\n at __webpack_require__ (webpack/bootstrap:25:0)\n at Module../.nuxt/index.js (.nuxt/index.js:1:0)\n at __webpack_require__ (webpack/bootstrap:25:0)\n```\n\n```text\nbt-vue.ts\n```\n\n```js\nmodules: ['bootstrap-vue/nuxt'],\nbootstrapVue: {\n bootstrapCSS: false, // here you can disable automatic bootstrapCSS in case you are loading it yourself using sass\n bootstrapVueCSS: false, // CSS that is specific to bootstrapVue components can also be disabled. That way you won't load css for modules that you don't use\n componentPlugins: ['Collapse', 'Dropdown'], // Here you can specify which components you want to load and use\n directivePlugins: [] // Here you can specify which directives you want to load and use. Look into official docs to get a list of what's available\n }\n```\n\n```scss\n@import \"~bootstrap-vue/src/variables\";\n// All bt-vue styles can be imported with this reference\n//@import \"~bootstrap-vue/src/components/index\";\n\n// Importing only styles for components we currently use\n@import \"~bootstrap-vue/src/components/dropdown/index\";\n```\n\n```js\nimport Vue from 'vue'\nimport Collapse from 'bootstrap-vue/es/components/collapse'\nimport Dropdown from 'bootstrap-vue/es/components/dropdown'\n\nVue.use(Collapse)\nVue.use(Dropdown)\n```\n\n```js\nexport default {\n build: {\n transpile: ['bootstrap-vue']\n },\n plugins: ['@/plugins/bt-vue']\n}\n```\n\n```js\ncss: [\n '@/assets/scss/index.scss'\n ]\n```\n\n```text\nimport { Modal } from 'bootstrap-vue/es/components';\n```\n\n```text\ncomponents\n```\n\n```text\ntranspile\n```\n\n========================================\n\nComments:\n- Can you try this solution from clarcdo: adding dom-classes to externals ---- const nodeExternals = require('webpack-node-externals') module.exports = { build: { extend(config, ctx) { if (ctx.isServer) { config.externals = [ nodeExternals({ whitelist: [/^dom-classes/] }) ] } } } }\n- What is dom-classes? Should I create a separate module for this? Is it possible to use with Webpack 4? Maybe I can use extendBuild function?\n- Small reminder that you need `import Vue from 'vue'` at the start of the plugin import\n- It's there, isn't it?\n- The latest BootstrapVue nuxt plugin now allows importing of individual components and directives.","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":221,"estimatedTokens":1719}}563{"id":"stack-52407433","source":"stackoverflow","questionId":52407433,"title":"How to add middleware to a group of routes in Nuxt","tags":["nuxt.js"],"text":"Title: How to add middleware to a group of routes in Nuxt\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nAccording to the docs: The middleware will be executed in series in this order:\n\n- nuxt.config.js\n\n- Matched layouts\n\n- Matched pages\n\nNow I was wondering how I can add middleware to a group of pages in a slug like this:\n\n```\npages/\n--| _slug/\n-----| comments.vue\n-----| index.vue\n```\n\nSome options I think there are:\n\n1) I could add the middleware to every individual page in the directory but that's not dry.\n\n2) Another solution would be to add the middleware to the `nuxt.config.js` with a conditional on the route, but that doesn't feel like the right place for that code either, besides that it would run on any other route too.\n\n3) I could maybe use nested routes with a template containing only a single `` element, but I'm not sure about the side effects: Can I still use page-component properties? Does that nest everything in another DOM element?.\n\nAny help is appreciated.\n\n========================================\n\nCode:\n```text\npages/\n--| _slug/\n-----| comments.vue\n-----| index.vue\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n<nuxt-child>\n```\n\n```text\npages/\n--| _slug/\n-----| comments.vue\n-----| index.vue\n--| _slug.vue\n```\n\n```text\n<template>\n <nuxt-child/>\n</template>\n\n<script>\nexport default {\n middleware: 'myslugmiddleware',\n}\n</script>\n```\n\n```text\n_slug.vue\n```\n\n```text\n_slug/\n```\n\n```text\n_slug.vue\n```\n\n========================================\n\nComments:\n- how do I redirect an index.vue to _slug.vue if my index.vue is located right inside pages\n- You have to add a param named `slug` (without the underscore) in the link: router.vuejs.org/guide/essentials/navigation.html","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":87,"estimatedTokens":427}}564{"id":"stack-57497145","source":"stackoverflow","questionId":57497145,"title":"How to set v-sheet/v-container size to match screen with v-app-bar in Vuetify 2.0.5?","tags":["vuetify.js","nuxt.js"],"text":"Title: How to set v-sheet/v-container size to match screen with v-app-bar in Vuetify 2.0.5?\nTags: vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use the \"Prominent w/ scroll shrink and image\" v-app-bar on my nuxt site.\n\nThe code from Vuetify is:\n\n```\n\n \n [...]\n \n \n \n \n \n \n \n```\n\nIf I understand this correctly, then the content of the page must be in the v-container, where I have my nuxt root element. That works fine so far. The v-sheet or v-container doesn't fill the whole page. If I try to set it to 100%/100vh to fill the space on small smartphone screens as well as on large PC monitors, then either the app-bar is no longer scrollable, or the whole page is no longer scrollable, or the content in the v-container goes far below the edge of the screen, even though you have scrolled all the way down.\n\nI hope I just overlook one stupid little thing. If not, then I will probably have to use the normal \"toolbar\" of Vuetify, even if the app bar is so much nicer.\n\nBest Regards,\n\nJakob\n\n========================================\n\nCode:\n```text\n<v-card class=\"overflow-hidden\">\n <v-app-bar\n absolute\n color=\"#fcb69f\"\n dark\n shrink-on-scroll\n src=\"https://picsum.photos/1920/1080?random\"\n scroll-target=\"#scrolling-techniques-2\"\n >\n [...]\n </v-app-bar>\n <v-sheet\n id=\"scrolling-techniques-2\"\n class=\"overflow-y-auto\"\n max-height=\"600\"\n >\n <v-container style=\"height: 1000px;\">\n <nuxt />\n </v-container>\n </v-sheet>\n </v-card>\n```\n\n```text\n<v-app-bar\n fixed\n color=\"#fcb69f\"\n dark\n shrink-on-scroll\n src=\"https://picsum.photos/1920/1080?random\"\n>\n```\n\n```text\n<v-sheet>\n```\n\n```text\n<v-container>\n```\n\n```text\nscroll-target=\"#scrolling-techniques-2\"\n```\n\n```text\nv-app-bar\n```\n\n```text\nabsolute\n```\n\n```text\nfixed\n```\n\n========================================\n\nComments:\n- Have you tried getting rid of the v-card element? Pretty sure they only do that in their examples to provide some kind of background\n- @CathyHa Yes and than I can't scroll anymore...\n- Have a solution?","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":97,"estimatedTokens":522}}565{"id":"stack-59533016","source":"stackoverflow","questionId":59533016,"title":"Adding a dark mode toggle to vuetify app v2.0 on nuxt.js","tags":["javascript","vue.js","vuetify.js","nuxt.js"],"text":"Title: Adding a dark mode toggle to vuetify app v2.0 on nuxt.js\nTags: javascript, vue.js, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using nuxt.js vuetify template, nuxt.config.js already has a object (mentioned below) which defines dark mode for the app. \n\n```\nvuetify: {\n customVariables: ['~/assets/variables.scss'],\n theme: {\n dark: true,\n themes: {\n dark: {\n primary: colors.blue.darken2,\n accent: colors.grey.darken3,\n secondary: colors.amber.darken3,\n info: colors.teal.lighten1,\n warning: colors.amber.base,\n error: colors.deepOrange.accent4,\n success: colors.green.accent3\n }\n }\n }\n },\n```\n\nHow do I add this as a feature, as a button to toggle from light version to dark? Vuetify has documentation for theme customization, but no proper way which explains how to do this within the app.\n\n========================================\n\nTop Answer:\nNice and fastest way I found to add a switch button for dark/light mode:\n\n```\n\n```\n\nNothing else needed.\n\n========================================\n\nCode:\n```text\nvuetify: {\n customVariables: ['~/assets/variables.scss'],\n theme: {\n dark: true,\n themes: {\n dark: {\n primary: colors.blue.darken2,\n accent: colors.grey.darken3,\n secondary: colors.amber.darken3,\n info: colors.teal.lighten1,\n warning: colors.amber.base,\n error: colors.deepOrange.accent4,\n success: colors.green.accent3\n }\n }\n }\n },\n```\n\n```text\n<v-btn @click=\"$vuetify.theme.dark=!$vuetify.theme.dark\">Toggle Theme</v-btn>\n```\n\n```text\ntoggleTheme() {\n this.$vuetify.theme.dark=!this.$vuetify.theme.dark;\n localStorage.setItem(\"useDarkTheme\", this.$vuetify.theme.dark.toString())\n}\n```\n\n```text\nmounted() {\n const theme = localStorage.getItem(\"useDarkTheme\");\n if (theme) {\n if (theme == \"true\") {\n this.$vuetify.theme.dark = true;\n } else this.$vuetify.theme.dark = false;\n }\n}\n```\n\n```text\nv-btn\n```\n\n```text\n$vuetify.theme.dark\n```\n\n```text\n<v-btn\n icon\n :color=\"$vuetify.theme.dark ? 'yellow' : 'dark'\"\n @click=\"$vuetify.theme.dark = !$vuetify.theme.dark\"\n>\n```\n\n========================================\n\nComments:\n- Also, check out this example for reference: vuetifyjs.com/en/features/theme/#example\n- how to store dark mode status in localStorage, and get it on app start?\n- @FarshidRezaei check out my edit. That's how I did it\n- \"mounted\" function where is placed? which file or component?\n- wherever you want the initial check for the theme to happen. If you have a login page and you want that to be dark already, then it would be that login page","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":109,"estimatedTokens":656}}566{"id":"stack-57458197","source":"stackoverflow","questionId":57458197,"title":"How to generate txt & xml files in nuxt SSR?","tags":["vue.js","nuxt.js"],"text":"Title: How to generate txt & xml files in nuxt SSR?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIs there any way of generating a Google : `ads.txt` file every time i build my **SSR** project? \n\nThere is a module called: `sitemap-module` from `nuxt-community`, it is used to generate a `sitemap` xml file, and that file can be accessed by http://domain.tls/sitemap.xml. and i want something like that.\n\nSo currently i'am achieving this by building the project, then manually put `ads.txt` it in : `/var/www/site/.nuxt/dist/client/`, \n\n**The problem with this is that everytime i rebuild the project i loose `/var/www/site/.nuxt/dist/client/` folder then i have to add `ads.txt` file again.**\n\nI would like to know how i can hook up my code to tell nuxt to generate `ads.txt` file and put it in `/var/www/site/.nuxt/dist/client/`\n\n*Not sure if it makes sense, but i hope someone will understand.*\n\n========================================\n\nTop Answer:\nHaven't found any way of solving this in `nuxt`, so i decided to redirect all https://domain.tld/ads.txt in Nginx configuration.\n\n*/etc/nginx/sites-available/default.conf*\n\n```\n#redirect all txt request\nlocation ~* ^.+.(txt)$ {\n root /var/www/other.files/;\n}\n```\n\nSo i think i'll stick to it.\n\n========================================\n\nCode:\n```text\nads.txt\n```\n\n```text\nsitemap-module\n```\n\n```text\nnuxt-community\n```\n\n```text\nsitemap\n```\n\n```text\nads.txt\n```\n\n```text\n/var/www/site/.nuxt/dist/client/\n```\n\n```text\n/var/www/site/.nuxt/dist/client/\n```\n\n```text\nads.txt\n```\n\n```text\nads.txt\n```\n\n```text\n/var/www/site/.nuxt/dist/client/\n```\n\n```text\nstatic\n```\n\n```text\nexample.com/{filename.extension}\n```\n\n```text\npublic\n```\n\n```text\nsrc\n```\n\n```text\n#redirect all txt request\nlocation ~* ^.+.(txt)$ {\n root /var/www/other.files/;\n}\n```\n\n```text\nnuxt\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":102,"estimatedTokens":455}}567{"id":"stack-79160285","source":"stackoverflow","questionId":79160285,"title":"Imports in Nuxt with @ or ~, which is better?","tags":["javascript","nuxt.js","nuxt3.js"],"text":"Title: Imports in Nuxt with @ or ~, which is better?\nTags: javascript, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nIn Nuxt 3, imports can reference the project root using either `~` or `@`, for example:\n\n```\nimport SubHeader from \"@/components/SubHeader.vue\"\n```\n\nvs\n\n```\nimport SubHeader from \"~/components/SubHeader.vue\"\n```\n\nIs there a functional difference between these? Is one preferred over the other?\n\n========================================\n\nCode:\n```text\nimport SubHeader from \"@/components/SubHeader.vue\"\n```\n\n```text\nimport SubHeader from \"~/components/SubHeader.vue\"\n```\n\n```text\n~\n```\n\n```text\n@\n```\n\n```text\n@\n```\n\n```text\n~\n```\n\n```text\n~\n```\n\n```text\n@\n```\n\n```text\n~\n```\n\n========================================\n\nComments:\n- None. Use relative path. They are the only valid specifiers per ecmascript specification. Everything else will make you regret it later.\n- @EricMORAND invalid answer in this context + quite a big shift as a whole too. Also, nowadays it's properly resolved.\n- @kissu that's why it is not an answer, but a comment. Also, no, it is not properly resolved. It violates the specification of the language.","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":64,"estimatedTokens":288}}568{"id":"stack-70145557","source":"stackoverflow","questionId":70145557,"title":"What is the closest equivalent in Nuxt 3 to an \"Anonymous Middleware\" from Nuxt 2?","tags":["vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: What is the closest equivalent in Nuxt 3 to an \"Anonymous Middleware\" from Nuxt 2?\nTags: vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am learning about Nuxt 3 at the moment and currently focus on things that I knew how to handle in Nuxt 2 and for which I did not yet find a (similar, simple) solution in Nuxt 3.\n\nOne of those things are **anonymous middlewares**.\nHow can I build those in Nuxt 3 / what is the closest thing in Nuxt 3 that can be used to get the same functionallity?\nDo I really have to call an API endpoint?\nThis seems so overkill compared to Nuxt 2.\n\n========================================\n\nComments:\n- Hey, I'm keeping the tag with `nuxtjs3` only to have a single source and not split the community around several tags (pretty much like for Vue3). I'll give it a better abstract I guess, so that it looks more \"interesting\".\n- @kissu Both tags are currently very small, why not merging them? One could also mention this on meta to get help.\n- Yeah, we need to do that, but it requires 5 points in the tag itself to submit a synonym. Also, sharing it on Meta could be a really good idea indeed!","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":18,"estimatedTokens":287}}569{"id":"stack-70111637","source":"stackoverflow","questionId":70111637,"title":"Nuxt plugin property does not exist on type 'CombinedVueInstance","tags":["typescript","vue.js","nuxt.js"],"text":"Title: Nuxt plugin property does not exist on type 'CombinedVueInstance\nTags: typescript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI've created a plugin and want to use it inside one of my components.\nThe code from the plugin located under `~/plugins/socket.client.ts`:\n\n```\nimport { io } from 'socket.io-client'\nimport { Plugin } from '@nuxt/types'\n\nconst socketIOPlugin: Plugin = (_, inject) => {\n const socketUrl: string | undefined = process.env.socket_url\n\n if (!socketUrl || socketUrl.length It is registered inside the nuxt.config.js.\n`plugins: ['~/plugins/socket.client']`\n\nAnd I use it inside my component like this:\n\n```\nimport Vue from 'vue'\n\nexport default Vue.extend({\n mounted() {\n this.$socket.on(\"example:hello\", (data: any) => {\n console.log(data);\n });\n },\n})\n```\n\nHowever, when I start nuxt, I get the following error:\n`Property '$socket' does not exist on type 'CombinedVueInstance>>'.`\n\nI've already tried adding a vue-shim.d.ts file, but still nothing changes.\n\n```\ndeclare module \"*.vue\" {\n import Vue from 'vue'\n export default Vue\n}\n\ndeclare module \"vue/types/vue\" {\n import { Socket } from \"socket.io-client\";\n interface Vue {\n $socket: Socket;\n }\n}\n```\n\nI can't seem to find a way to solve this. Can anyone please help me?\n\n========================================\n\nTop Answer:\n`declare module \"vue/types/vue\"` is a module augmentation - for augmentation to work correctly, it needs to be placed inside the TS file that contains at least **one** top-level import/export (more details here)\n\nSo my suggestion is to move that code from `vue-shim.d.ts` directly to `socket.client.ts`\n\n========================================\n\nCode:\n```text\nimport { io } from 'socket.io-client'\nimport { Plugin } from '@nuxt/types'\n\nconst socketIOPlugin: Plugin = (_, inject) => {\n const socketUrl: string | undefined = process.env.socket_url\n\n if (!socketUrl || socketUrl.length <= 0) {\n throw new Error('socketUrl is undefined.')\n }\n\n const socket = io(socketUrl)\n inject('socket', socket)\n}\n\nexport default socketIOPlugin\n```\n\n```text\nimport Vue from 'vue'\n\nexport default Vue.extend({\n mounted() {\n this.$socket.on(\"example:hello\", (data: any) => {\n console.log(data);\n });\n },\n})\n```\n\n```text\ndeclare module \"*.vue\" {\n import Vue from 'vue'\n export default Vue\n}\n\ndeclare module \"vue/types/vue\" {\n import { Socket } from \"socket.io-client\";\n interface Vue {\n $socket: Socket;\n }\n}\n```\n\n```text\n~/plugins/socket.client.ts\n```\n\n```text\nplugins: ['~/plugins/socket.client']\n```\n\n```text\nProperty '$socket' does not exist on type 'CombinedVueInstance<Vue, unknown, unknown, unknown, Readonly<Record<never, any>>>'.\n```\n\n```text\nimport { Plugin } from '@nuxt/types'\nimport { io, Socket } from 'socket.io-client'\n\nfunction getSocketConnection(): Socket {\n const socketUrl: string | undefined = process.env.socket_url\n\n if (!socketUrl || socketUrl.length <= 0) {\n throw new Error('socketUrl is undefined.')\n }\n\n return io(socketUrl)\n}\n\nconst socketIOPlugin: Plugin = (_, inject) => {\n inject('socket', getSocketConnection())\n}\n\nexport default socketIOPlugin\nexport const socket = getSocketConnection()\n```\n\n```text\nimport { accessorType } from '~/store'\nimport { socket } from '~/plugins/socket.client'\n\ndeclare module 'vuex/types/index' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Store<S> {\n $socket: typeof socket\n }\n}\n\ndeclare module 'vue/types/vue' {\n interface Vue {\n $accessor: typeof accessorType\n }\n}\n\ndeclare module '@nuxt/types' {\n interface NuxtAppOptions {\n $accessor: typeof accessorType\n }\n}\n```\n\n```text\nimport type { ActionTree, GetterTree, MutationTree } from 'vuex'\nimport { getAccessorType } from 'typed-vuex'\n\nexport const state = () => ({\n posts: [] as any[],\n})\n\nexport type RootState = ReturnType<typeof state>\n\nexport const getters: GetterTree<RootState, RootState> = {\n posts: (state) => state.posts,\n}\n\nexport const mutations: MutationTree<RootState> = {\n SET_POSTS: (state: RootState, posts: any[]) => (state.posts = posts),\n}\n\nexport const actions: ActionTree<RootState, RootState> = {\n fetchPosts({ commit }) {\n this.$socket.emit('example:getPosts')\n this.$socket.once('example:posts', (data: any) => {\n commit('SET_POSTS', data)\n })\n },\n}\n\nexport const accessorType = getAccessorType({\n state,\n getters,\n mutations,\n actions,\n modules: {},\n})\n```\n\n```text\n<script lang='ts'>\nimport { Component, Vue } from 'nuxt-property-decorator'\n\n@Component\nexport default class Index extends Vue {\n get posts() {\n return this.$accessor.posts\n }\n\n fetchPosts() {\n this.$accessor.fetchPosts()\n }\n}\n</script>\n```\n\n```text\n~/plugins/socket.client.ts\n```\n\n```text\nvue-shim.d.ts\n```\n\n```text\nindex.d.ts\n```\n\n```text\n~/store/index.ts\n```\n\n```text\n~/pages/index.vue\n```\n\n```text\ndeclare module \"vue/types/vue\"\n```\n\n```text\nvue-shim.d.ts\n```\n\n```text\nsocket.client.ts\n```\n\n========================================\n\nComments:\n- I've placed the declare module part above my const socketIOPlugin... code, however I still get the same error message.","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":254,"estimatedTokens":1272}}570{"id":"stack-58937910","source":"stackoverflow","questionId":58937910,"title":"How to upload a generated folder content into S3 using CodeBuild?","tags":["amazon-web-services","amazon-s3","nuxt.js","aws-codepipeline","aws-codebuild"],"text":"Title: How to upload a generated folder content into S3 using CodeBuild?\nTags: amazon-web-services, amazon-s3, nuxt.js, aws-codepipeline, aws-codebuild\nSource: Stack Overflow\n\nQuestion:\nI am trying to configure a CodePipeline on AWS that it takes my Nuxt website on Github, run the command `npm run generate` to generate the static website then upload the `dist` folder on an S3 bucket.\n\nHere what my `buildspec.yml` it looks like:\n\n```\nversion: 0.2\n\nphases:\n install:\n commands:\n - npm install\n build:\n commands:\n - npm run generate\n post_build:\n commands:\n - aws s3 sync dist $S3_BUCKET\n```\n\nThe error I get is: `The user-provided path dist does not exist.` Is anyone know how to correct this? I read a lot about artefacts but I never use them before…\n\nThanks in advance,\n\n========================================\n\nCode:\n```sh\nversion: 0.2\n\nphases:\n install:\n commands:\n - npm install\n build:\n commands:\n - npm run generate\n post_build:\n commands:\n - aws s3 sync dist $S3_BUCKET\n```\n\n```text\nnpm run generate\n```\n\n```text\ndist\n```\n\n```text\nbuildspec.yml\n```\n\n```text\nThe user-provided path dist does not exist.\n```\n\n```text\nversion: 0.2\n\nphases:\n install:\n commands:\n - npm install\n build:\n commands:\n - npm run generate\nartifacts:\n files:\n - '**/*'\n base-directory: 'dist'\n```\n\n========================================\n\nComments:\n- Thanks for your answer! So I just have to add `- aws s3 sync dist $S3_BUCKET` under artifacts section?\n- @SébastienSerre No, there is no need to use that command. I have updated my answer please go through it.\n- Thanks! Is working great now :) My mistake was to pass by CodePipeline, I have redeployed everything using only CodeBuild as you describe and everything works","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":84,"estimatedTokens":440}}571{"id":"stack-61593418","source":"stackoverflow","questionId":61593418,"title":"SSR Nuxt.js with integreted REST API backend","tags":["node.js","express","vue.js","nuxt.js"],"text":"Title: SSR Nuxt.js with integreted REST API backend\nTags: node.js, express, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm developing an SSR Nuxt.js app with an integrated REST API server. \n\nTo do this, I've added my `/api` endpoint inside Nuxt `server.js` code as following\n\n```\nconst express = require('express')\nconst consola = require('consola')\nconst { Nuxt, Builder } = require('nuxt')\n\nconst app = express()\n\n// Import and Set Nuxt.js options\nconst config = require('../nuxt.config.js')\nconfig.dev = process.env.NODE_ENV !== 'production'\n\n// MY REST API ENDPOINT (It's the right approach?)\nconst routesApi = require('./api/routes')\napp.use('/api', routesApi)\n\nasync function start() {\n // Init Nuxt.js\n const nuxt = new Nuxt(config)\n\n const { host, port } = nuxt.options.server\n\n await nuxt.ready()\n // Build only in dev mode\n if (config.dev) {\n const builder = new Builder(nuxt)\n await builder.build()\n }\n\n // Give nuxt middleware to express\n app.use(nuxt.render)\n\n // Listen the server\n app.listen(port, host)\n consola.ready({\n message: `Server listening on http://${host}:${port}`,\n badge: true\n })\n}\nstart()\n```\n\nI didn't found examples related to this approach. \n\nI need some help to understand if it's the right way. \n\nThank you for your support.\n\n========================================\n\nCode:\n```js\nconst express = require('express')\nconst consola = require('consola')\nconst { Nuxt, Builder } = require('nuxt')\n\nconst app = express()\n\n// Import and Set Nuxt.js options\nconst config = require('../nuxt.config.js')\nconfig.dev = process.env.NODE_ENV !== 'production'\n\n// MY REST API ENDPOINT (It's the right approach?)\nconst routesApi = require('./api/routes')\napp.use('/api', routesApi)\n\nasync function start() {\n // Init Nuxt.js\n const nuxt = new Nuxt(config)\n\n const { host, port } = nuxt.options.server\n\n await nuxt.ready()\n // Build only in dev mode\n if (config.dev) {\n const builder = new Builder(nuxt)\n await builder.build()\n }\n\n // Give nuxt middleware to express\n app.use(nuxt.render)\n\n // Listen the server\n app.listen(port, host)\n consola.ready({\n message: `Server listening on http://${host}:${port}`,\n badge: true\n })\n}\nstart()\n```\n\n```text\n/api\n```\n\n```text\nserver.js\n```\n\n```js\n// nuxt.config.js\nexport default {\n...\n serverMiddleware: [\n '/api': '~/api/index.js'\n ],\n...\n}\n```\n\n```js\n// api/index.js\nexport default function (req, res, next) {\n ... // Well, here comes nothing\n next()\n}\n```\n\n```text\nserverMiddleware\n```\n\n```text\n/api\n```\n\n========================================\n\nComments:\n- i wrote an blog article how to setup an rest api with nuxt blogxon.com/articles/basic-express-nuxt-api","metadata":{"transformedAt":"2026-08-18T18:33:07.878Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":139,"estimatedTokens":666}}572{"id":"stack-58553013","source":"stackoverflow","questionId":58553013,"title":"What is the benefit of using no-prefetch on nuxt-link?","tags":["nuxt.js"],"text":"Title: What is the benefit of using no-prefetch on nuxt-link?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI understand the benefit of using `nuxt-link` over `a` is that it increases responsiveness of my website because of prefetching. Now reading nuxt-link component page in nuxtjs.org, I see that there is a way to take out the prefetching by using `no-prefetch`.\n\nI have difficulty understanding why you would want to use `nuxt-link` if this is the case? Wouldn't you want to use something else? Why would you still use `nuxt-link`?\n\n========================================\n\nTop Answer:\nYou don't need to use it, if you don't needed. Simple.\n\nI'm not sure what do you mean about `you want to use something else`.\n\n`nuxt-link` just a wrapper of `router-link`, with some adjustment. So, if you don't need prefetch, `nuxt-link` just `router-link`.\n\nWhat's the benefit of using `nuxt-link` (`router-link`) instead of just plain `a` tag?\n\n`nuxt-link` has a lot off stuff, for example if you need to generate link with named routes.\n\nLet's imagine if you have generated routes something like this:\n\n```\n{\n path: \"/users/:userId?/posts/:id?/:slug?\",\n component: _33r1e47x,\n name: \"users-id-posts-id-slug\"\n}\n```\n\nYou just need to write\n\n```\n\n```\n\ninstead of\n\n```\n`/users/${userId}/posts/${id}/${slug}`\n```\n\n========================================\n\nCode:\n```text\nnuxt-link\n```\n\n```text\na\n```\n\n```text\nno-prefetch\n```\n\n```text\nnuxt-link\n```\n\n```text\nnuxt-link\n```\n\n```text\n<nuxt-link />\n```\n\n```text\nnuxt-link\n```\n\n```text\n{\n path: \"/users/:userId?/posts/:id?/:slug?\",\n component: _33r1e47x,\n name: \"users-id-posts-id-slug\"\n}\n```\n\n```text\n<nuxt-link :to=\"{ name: 'users-id-posts-id-slug', params: { userId, id, slug }}\"></nuxt-link>\n```\n\n```text\n<a :href=\"`/users/${userId}/posts/${id}/${slug}`\"></a>\n```\n\n```text\nyou want to use something else\n```\n\n```text\nnuxt-link\n```\n\n```text\nrouter-link\n```\n\n```text\nnuxt-link\n```\n\n```text\nrouter-link\n```\n\n```text\nnuxt-link\n```\n\n```text\nrouter-link\n```\n\n```text\na\n```\n\n```text\nnuxt-link\n```\n\n========================================\n\nComments:\n- If I do not know if there is a benefit, I do not know if I need to use it or do not need to use it. I am here to learn what is the benefit to make informed decision. Thank you very much for your answer.\n- I created a copy of this project github.com/misskey-dev/misskey-hub-next, but I add dropdowns when i open the dropdown i got ofecth get calls 404 e.g. ofetch.37386b05.mjs:222 GET localhost:3001/api/_content/… 404 (Document not found!), im researchig abo this cause/error, the clients see the logs but i dont now how disable this functionality that is creatin the problem, the menus work good, just this problem\n- Great description. Thank you very much for explanation! Does that mean, then, I should never use Anchor tag any more other than may be going to outside website?","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":133,"estimatedTokens":718}}573{"id":"stack-53236783","source":"stackoverflow","questionId":53236783,"title":"why nuxt.js global css on config is not working?","tags":["nuxt.js"],"text":"Title: why nuxt.js global css on config is not working?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI try to put css files on assets \nassest/css/style.css\nand call it to my nuxt.config.js\nbut it is not working i need to use global css not scoped css\n\ncan someone help me?\n\nwhen i add css\nin the nuxt.config.js\n\n```\n/*\n ** Global CSS\n */\n css: [\n '~assets/css/style.css'\n ],\n```\n\nits not working ? \nnuxt version 2\n\n========================================\n\nTop Answer:\nSimply restart the server. Adding the code to the module should not be necessary.\n\n========================================\n\nCode:\n```text\n/*\n ** Global CSS\n */\n css: [\n '~assets/css/style.css'\n ],\n```\n\n```text\ncss: [\n '@/assets/css/reset.css',\n '@/assets/css/main.scss',\n],\nmodules: [\n [\n 'nuxt-sass-resources-loader',\n ['./assets/css/main.scss'],\n ['./assets/css/reset.css']\n ]\n],\n```\n\n========================================\n\nComments:\n- Hi, welcome to stack overflow. Please refer the How to Ask link for more details on how to ask a question and update your question accordingly.\n- it should work, provide full not working code otherwise\n- Have you tried turning it off and on again? Seriously, changes in nuxt.config.js aren't applied unless you restart nuxt. Make some ridiculously obvious change in your CSS that you simply can't miss, like setting the background of the body to `#0000ff !important` or something, just so you can be certain it's not just some other stylesheet you're loading that overrides your own CSS.\n- After modifying the `nuxt.config`, a server restart (`Ctrl + C`, `npm run dev`) is always necessary.","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":65,"estimatedTokens":405}}574{"id":"stack-55414766","source":"stackoverflow","questionId":55414766,"title":"TypeError: Cannot add module namespace property '_nuxtConfigFile' to nuxt.config.js with NUXT 2.4.5","tags":["javascript","nuxt.js"],"text":"Title: TypeError: Cannot add module namespace property '_nuxtConfigFile' to nuxt.config.js with NUXT 2.4.5\nTags: javascript, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am upgrading to Nuxt 2.4.5 and getting below error\n`TypeError: Cannot add module namespace property '_nuxtConfigFile' to nuxt.config.js`\n\n========================================\n\nTop Answer:\nReplace module.exports = {} from ***nuxt.config.js*** to export default { }\n\n========================================\n\nCode:\n```text\nTypeError: Cannot add module namespace property '_nuxtConfigFile' to nuxt.config.js\n```\n\n========================================\n\nComments:\n- just got the same error :)\n- which version I'm trying to upgrade nuxt 2.3.4 -> nuxt 2.4.5\n- i'm upgrading from 2.2.* to 2.5.1\n- Also switching nuxt version from 2.4.5 to 2.5.1 and vice versa didn't make a difference\n- caused by esm update. dont mix es6 and commonjs in nuxt.config\n- caused by esm update. dont mix es6 and commonjs in nuxt.config\n- Thanks, it's work :) 2 things to do: • require -> import • module.export -> export default\n- Getting this `WARNING: We noticed you're using the useBuiltIns option without declaring a core-js version. Currently, we assume version 2.x when no version is passed. Since this default version will likely change in future versions of Babel, we recommend explicitly setting the core-js version you are using via the corejs option.You should also be sure that the version you pass to the corejs option matches the version specified in your package.json's dependencies section. If it doesn't, you need to run one of the following commands:npm install --save core-js@2 npm install --save core-js@3`\n- @Aldarund using nuxt@2.4.5 getting above warning message for `core-js`\n- @HardikShah its totally different thing and nowhere near related to this SO question\n- @Aldarund Yes, I know. Just if you have also face same or any solution. do you have any solution?!\n- I am still mixing both import and require, but the `export default {}` was enough to get it work.","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":35,"estimatedTokens":509}}575{"id":"stack-72249530","source":"stackoverflow","questionId":72249530,"title":"Connection checker for Nuxt3 ($nuxt.isOffline)","tags":["vue.js","nuxt.js","nuxt3.js"],"text":"Title: Connection checker for Nuxt3 ($nuxt.isOffline)\nTags: vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nIn Nuxt2 there were connection checkers\n\nhttps://nuxtjs.org/docs/concepts/context-helpers/#connection-checker\n\nYou could do the following `this.$nuxt.isOffline`\n\nIs there a way to do this with Nuxt3?\n\nI tried looking at `useNuxt()` to see of there was some info in there but do not see anything.\n\nMy question was also asked on Github discussions: https://github.com/nuxt/framework/discussions/4996\n\n========================================\n\nCode:\n```text\nthis.$nuxt.isOffline\n```\n\n```text\nuseNuxt()\n```\n\n```html\n<script setup>\nimport { useOnline } from '@vueuse/core'\n\nconst online = useOnline()\n</script>\n\n<template>\n <p>Is my website online? {{ online }}</p>\n</template>\n```\n\n```text\nyarn add @vueuse/core\n```\n\n```text\nuseOnline()\n```\n\n========================================\n\nComments:\n- Also for reference here is the discussion on the Nuxt Github page where the same approach is suggested github.com/nuxt/framework/discussions/4996","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":52,"estimatedTokens":265}}576{"id":"stack-66317718","source":"stackoverflow","questionId":66317718,"title":"NuxtJS change query params and reload page","tags":["vue.js","vue-router","server-side-rendering","nuxt.js"],"text":"Title: NuxtJS change query params and reload page\nTags: vue.js, vue-router, server-side-rendering, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a route in my NuxtJS application that accept query parameters. I'm trying to implement a logic that allow the user to change the query parameters and reload the page.\n\nI tried:\n\n```\n// this does not work because I'm already in \"mypage\" and \"push\" does not reload the same page\nthis.$router.push(`/mypage?param1=${value1}¶m2=${value2}`)\n\n// same result as above\nthis.$router.push({ path: '/mypage', query: {param1: value1, param2: value2}})\n\n// this is able to change the query parameters but on reload they are reverted to the originals\nthis.$router.replace({ query: {param1: value1, param2: value2} })\nwindow.location.reload()\n\n// This reload the page but the query parameters are reverted as well\nthis.$router.go(`/mypage?param1=${value1}¶m2=${value2}`)\n```\n\nAny suggestions?\n\n========================================\n\nTop Answer:\n### This is only a workaround:\n\nthanks to this: https://github.com/vuejs/vue-router/issues/1182#issuecomment-405326772\n\nI was able to work around the issue by using javascript:\n\n```\nwindow.history.pushState({},'',`/mypage?param1=${value1}¶m2=${value2}`)\nwindow.location.reload()\n```\n\nof course this is not an optimal solution but it gets the work done until someone come out with a more proper solution here. thanks.\n\n========================================\n\nCode:\n```js\n// this does not work because I'm already in \"mypage\" and \"push\" does not reload the same page\nthis.$router.push(`/mypage?param1=${value1}¶m2=${value2}`)\n\n// same result as above\nthis.$router.push({ path: '/mypage', query: {param1: value1, param2: value2}})\n\n// this is able to change the query parameters but on reload they are reverted to the originals\nthis.$router.replace({ query: {param1: value1, param2: value2} })\nwindow.location.reload()\n\n// This reload the page but the query parameters are reverted as well\nthis.$router.go(`/mypage?param1=${value1}¶m2=${value2}`)\n```\n\n```text\nthis.$router.push({ path: '/mypage', query: {param1: value1, param2: value2}})\n```\n\n```text\nwatch: {\n '$route.query'() {\n // do something\n }\n },\n```\n\n```js\nwindow.history.pushState({},'',`/mypage?param1=${value1}¶m2=${value2}`)\nwindow.location.reload()\n```\n\n```text\nwindow.history.pushState({},'',`/mypage?param1=${value1}¶m2=${value2}`)\n```\n\n```text\nthis.$router.push({path: this.$route.path, query: { param1: 'param1', param2: 'param2' }})\n```\n\n```text\n// before\n\nthis.$router.replace({ query: {param1: value1, param2: value2} })\nwindow.location.reload()\n\n// after\n\nthis.$router.replace({ query: {param1: value1, param2: value2} }).then(() => {\n this.$nuxt.refresh();\n});\n```\n\n```text\nexport default {\n watchQuery: ['page']\n}\n```\n\n========================================\n\nComments:\n- What's the purpose of using `reload`?\n- to refresh the page after having changed the query parameters but it doesn't work\n- But Vue is reactive, the changes should be expected to happen without a refresh. It's not a good practice\n- Thanks for your answer, what would I put in the watcher if I want to reload the page with the new parameters?\n- You can always reload the page with this.$router.go(0), but as I said in the answer, you really shouldn't do this because NuxtJs is reactive. In 99% of cases, you can solve the problem in some other way (methods, vuex, etc.).","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":112,"estimatedTokens":860}}577{"id":"stack-54844974","source":"stackoverflow","questionId":54844974,"title":"Nuxt Bulma app can't access SCSS variables","tags":["vue.js","sass","nuxt.js","bulma"],"text":"Title: Nuxt Bulma app can't access SCSS variables\nTags: vue.js, sass, nuxt.js, bulma\nSource: Stack Overflow\n\nQuestion:\nI've created a `Nuxt` app with Bulma included and would like to access/override the Bulma variables in my `.vue` files. I've followed the instructions here which seem to match what I found in several other locations but I'm still getting an error when trying to access the `$primary` variable in my `.vue` file.\n\nHere's my `assets/css/main.scss` file:\n\n```\n@import \"~bulma/sass/utilities/_all.sass\";\n@import \"~bulma/bulma\";\n```\n\nMy `nuxt.config.js` modules section:\n\n```\nmodules: [\n ['nuxt-sass-resources-loader', './assets/css/main.scss']\n],\n```\n\nAnd my `.vue` file:\n\n```\n\n \n \n About\n \n \n\nexport default {\n};\n\n.my-title {\n color: $primary;\n}\n\n```\n\nHere's the error message in the terminal:\n\n```\nModule build failed (from ./node_modules/sass-loader/lib/loader.js): friendly-errors 11:51:52\n\n color: $primary;\n ^\n Undefined variable: \"$primary\".\n in /Data/dev/GIT/Homepage/source/pages/about/index.vue (line 16, column 12)\n friendly-errors 11:51:52\n @ ./node_modules/vue-style-loader??ref--9-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--9-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--9-oneOf-1-2!./node_modules/sass-loader/lib/loader.js??ref--9-oneOf-1-3!./node_modules/vue-loader/lib??vue-loader-options!./pages/about/index.vue?vue&type=style&index=0&lang=scss& 4:14-384 14:3-18:5 15:22-392\n @ ./pages/about/index.vue?vue&type=style&index=0&lang=scss&\n @ ./pages/about/index.vue\n @ ./.nuxt/router.js\n @ ./.nuxt/index.js\n @ ./.nuxt/client.js\n @ multi eventsource-polyfill webpack-hot-middleware/client?reload=true&timeout=30000&ansiColors=&overlayStyles=&name=client&path=/__webpack_hmr/client ./.nuxt/client.js\n```\n\nCan anyone see what I'm doing wrong?\n\n**UPDATE:** I've narrowed it down to the `nuxt.config.js` modules setup by importing the `.scss` directly in the `.vue` file. This works which tell me the imports in the `main.scss` the file is working fine.\n\n========================================\n\nTop Answer:\nThis config options provides to load any scss/sass file that specified by you before other files via webpack. You can interfere webpack config via these options that provide by nuxt. To experience more sass loader configuration you can check webpack sass loader section.\n\n Don't forget install node-sass and sass-loader to use sass/scss file\n in your app as mentioned by nuxt documentation.\n\n```\n// nuxt.config.js\n\nbuild: {\n loaders: {\n sass: {\n prependData: \"@import '~bulma/sass/utilities/_all.sass;\",\n }\n }\n }\n```\n\n========================================\n\nCode:\n```text\n@import \"~bulma/sass/utilities/_all.sass\";\n@import \"~bulma/bulma\";\n```\n\n```text\nmodules: [\n ['nuxt-sass-resources-loader', './assets/css/main.scss']\n],\n```\n\n```html\n<template>\n <section class=\"container\">\n <div class=\"my-title\">\n About\n </div>\n </section>\n</template>\n\n<script>\nexport default {\n};\n</script>\n\n<style lang=\"scss\">\n.my-title {\n color: $primary;\n}\n</style>\n```\n\n```text\nModule build failed (from ./node_modules/sass-loader/lib/loader.js): friendly-errors 11:51:52\n\n color: $primary;\n ^\n Undefined variable: \"$primary\".\n in /Data/dev/GIT/Homepage/source/pages/about/index.vue (line 16, column 12)\n friendly-errors 11:51:52\n @ ./node_modules/vue-style-loader??ref--9-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--9-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--9-oneOf-1-2!./node_modules/sass-loader/lib/loader.js??ref--9-oneOf-1-3!./node_modules/vue-loader/lib??vue-loader-options!./pages/about/index.vue?vue&type=style&index=0&lang=scss& 4:14-384 14:3-18:5 15:22-392\n @ ./pages/about/index.vue?vue&type=style&index=0&lang=scss&\n @ ./pages/about/index.vue\n @ ./.nuxt/router.js\n @ ./.nuxt/index.js\n @ ./.nuxt/client.js\n @ multi eventsource-polyfill webpack-hot-middleware/client?reload=true&timeout=30000&ansiColors=&overlayStyles=&name=client&path=/__webpack_hmr/client ./.nuxt/client.js\n```\n\n```text\nNuxt\n```\n\n```text\n.vue\n```\n\n```text\n$primary\n```\n\n```text\n.vue\n```\n\n```text\nassets/css/main.scss\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n.vue\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n.scss\n```\n\n```text\n.vue\n```\n\n```text\nmain.scss\n```\n\n```text\nmodules: [\n '@nuxtjs/style-resources'\n],\n\nstyleResources: {\n scss: [\n './assets/css/main.scss'\n ]\n},\n```\n\n```text\n// nuxt.config.js\n\nbuild: {\n loaders: {\n sass: {\n prependData: \"@import '~bulma/sass/utilities/_all.sass;\",\n }\n }\n }\n```\n\n========================================\n\nComments:\n- have you defined $primary in main.scss?\n- @Andrew1325 $primary is one of the variables defined by Bulma so I shouldn't need to define it. I actually did try defining it too with no change.\n- this only imports the common variables declared inside _initial-variables.scss in bulma, what about the variables defined inside each component?","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":210,"estimatedTokens":1381}}578{"id":"stack-60208823","source":"stackoverflow","questionId":60208823,"title":"how to remove /?fbclid=... in nuxt url","tags":["javascript","facebook","vue.js","nuxt.js"],"text":"Title: how to remove /?fbclid=... in nuxt url\nTags: javascript, facebook, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nhello there i like to remove the facebook analytic forced url parameter `/?fbclid=` `https://www.example.com/?fbclid=...`, from my host url, when redirected from facebook by clicking the url, the problem is the nuxt-link-exact-active class is not applied if redirected with this parameter.\nThanks\n\n========================================\n\nTop Answer:\nFor simple cases like `https://www.example.com/?fbclid=...` where **fbclid** is the first and only parameter, it can be done by a simple server configuration.\n\nSo for example put this in the `.htaccess` file:\n\n```\nRewriteEngine on\n\n RewriteRule . %{REQUEST_URI}? [R=301,L]\n\n```\n\nNote the `?` after `%{REQUEST_URI}`. It deletes the query string completely.\n\nIn other cases (where **fbclid** was appended to other parameters) this example does nothing - more complicated code is needed for that.\n\n========================================\n\nCode:\n```text\n/?fbclid=\n```\n\n```text\nhttps://www.example.com/?fbclid=...\n```\n\n```text\n<script>\n // ideally this is on top of page; works on bottom as well\n\n if(/^\\?fbclid=/.test(location.search))\n location.replace(location.href.replace(/\\?fbclid.+/, \"\"));\n\n </script>\n```\n\n```text\n<script>\n if(location.search) location.replace(location.href.replace(/\\?.+/, \"\"));\n </script>\n```\n\n```text\nhttps://www.example.com/?fbclid=...\n```\n\n```text\n?fbclid=...\n```\n\n```text\nfbclid\n```\n\n```text\nmethods: {\n removeFacebookHook() {\n var fbParam = 'fbclid';\n\n // Check if param exists\n if (location.search.indexOf(fbParam + '=') !== -1) {\n var replace = '';\n\n try {\n var url = new URL(location);\n url.searchParams.delete(fbParam);\n replace = url.href;\n\n // Check if locale exists\n if (window.location.href.indexOf(this.locale) > -1) {\n window.history.replaceState(null, null, \"/\" + this.locale);\n };\n\n } catch (ex) {\n var regExp = new RegExp('[?&]' + fbParam + '=.*$');\n replace = location.search.replace(regExp, '');\n replace = location.pathname + replace + location.hash;\n }\n\n history.replaceState(null, '', replace);\n }\n }\n}\n```\n\n```text\nRewriteEngine on\n<if \"%{QUERY_STRING} =~ /^fbclid=/\">\n RewriteRule . %{REQUEST_URI}? [R=301,L]\n</if>\n```\n\n```text\nhttps://www.example.com/?fbclid=...\n```\n\n```text\n.htaccess\n```\n\n```text\n?\n```\n\n```text\n%{REQUEST_URI}\n```\n\n```text\n//facebook Route Script for Query string\n function faceBookQuery() {\n addEventListener('fetch', event => {\n let url = new URL(event.request.url)\n\n if (url.searchParams.has('fbclid'))\n url.searchParams.delete('fbclid')\n\n event.respondWith(\n fetch(url, event.request)\n );\n });\n }\n```\n\n```text\nif(/^\\?fbclid=/.test(location.search))\n location.replace(location.href.replace(location.search, \"\"));\n```\n\n```text\n#section\n```\n\n```text\nhttps://www.example.com/file?fbclid=...#section\n```\n\n```text\nhttps://www.example.com/file\n```\n\n========================================\n\nComments:\n- and is `fbclid` *ISNT* the only parameter, the RegExp would be `/[\\?&]fbclid=[^&]+/` regexr.com/6j2s0\n- top answer great man!","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":157,"estimatedTokens":822}}579{"id":"stack-59093009","source":"stackoverflow","questionId":59093009,"title":"Why am I getting \"cannot find module\" I've already tried a lot of solutions","tags":["vue.js","nuxt.js"],"text":"Title: Why am I getting \"cannot find module\" I've already tried a lot of solutions\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nThis is the first time when i will install Nuxt Js after watching a lot of youtube tutorials and articles on Google, so i have already installed Node JS on my droplet based on Ubuntu 18.04 \nafter that i run `npm init -y` and `npm install nuxt --save` and `npx create-nuxt-app project` and get this error message : \n\n```\nmodule.js:549\n throw err;\n ^\n\nError: Cannot find module '/root/.npm/_npx/1934/lib/node_modules/create-nuxt-app/node_modules/ejs/postinstall.js'\n at Function.Module._resolveFilename (module.js:547:15)\n at Function.Module._load (module.js:474:25)\n at Function.Module.runMain (module.js:693:10)\n at startup (bootstrap_node.js:188:16)\n at bootstrap_node.js:609:3\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\nnpm ERR! ejs@2.7.4 postinstall: `node ./postinstall.js`\nnpm ERR! Exit status 1\nnpm ERR! \nnpm ERR! Failed at the ejs@2.7.4 postinstall script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /root/.npm/_logs/2019-11-28T16_17_41_163Z-debug.log\nInstall for create-nuxt-app@latest failed with code 1\n```\n\n========================================\n\nTop Answer:\nsimilar problem with different environment . I came across this problem but it for a vue app and I solved it by removing node_modules folder and removing **yarn.lock** or **package-lock.json** file\n\nnow run `npm i` ...\nit worked 👌\n\n========================================\n\nCode:\n```text\nmodule.js:549\n throw err;\n ^\n\nError: Cannot find module '/root/.npm/_npx/1934/lib/node_modules/create-nuxt-app/node_modules/ejs/postinstall.js'\n at Function.Module._resolveFilename (module.js:547:15)\n at Function.Module._load (module.js:474:25)\n at Function.Module.runMain (module.js:693:10)\n at startup (bootstrap_node.js:188:16)\n at bootstrap_node.js:609:3\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\nnpm ERR! ejs@2.7.4 postinstall: `node ./postinstall.js`\nnpm ERR! Exit status 1\nnpm ERR! \nnpm ERR! Failed at the ejs@2.7.4 postinstall script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /root/.npm/_logs/2019-11-28T16_17_41_163Z-debug.log\nInstall for create-nuxt-app@latest failed with code 1\n```\n\n```text\nnpm init -y\n```\n\n```text\nnpm install nuxt --save\n```\n\n```text\nnpx create-nuxt-app project\n```\n\n```text\nnpm i -g create-nuxt-app\nnpx create-nuxt-app nuxt002\nnpm run dev\n```\n\n```text\nnpm init -y\n```\n\n```text\nnpm install nuxt --save\n```\n\n```text\nnpx create-nuxt-app <project-name>\n```\n\n```text\nnpm init -y\n```\n\n```text\nnpm install nuxt --save\n```\n\n```text\nnpm i\n```\n\n========================================\n\nComments:\n- Don't use npm on the root user. Try to use npm with a regular user and see if that works.\n- But, why as a regular user? Any specific reason?\n- that's what i do, i create a folder called quick and i do cd quick, than i run npx create-nuxt-app quick and i get the same error\n- Can you run `npx -v` and `node -v` in your terminal and let me know the versions?\n- @Celsiuss' comment about using root user also seems like a good suggestion. Are you logged in as a root user?\n- npm -version : 3.5.2 npx -version : -bash: /usr/local/bin/npx: No such file or directory node -version : v8.10.0 i'm logged as root user\n- You don't have npx installed. Run `npm install -g npx` and then try creating the project\n- i have install npx and the latest node version just now 13.x with npx 6 and i still have the same issue\n- Okay, so I tried creating the project as a `root` user and got the same error. So, that's where the problem is. You should log-in as a normal user and then create the project.","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":121,"estimatedTokens":967}}580{"id":"stack-59422074","source":"stackoverflow","questionId":59422074,"title":"How to Map sub-State in nuxtjs","tags":["javascript","vue.js","vuex","nuxt.js"],"text":"Title: How to Map sub-State in nuxtjs\nTags: javascript, vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have created a state **~/store/modules/general/index.js**\n\nThere are **get_info** and **get_pages** Actions,\n\nstates **info** and **pages**,\n\nWhen i use \n\n```\n...mapActions({\ngetInfo: 'modules/general/get_info'\ngetPages: 'modules/general/get_pages'\n})\n```\n\nWorks fine,\nbut when i try to access it via \n\n```\n...mapState({\nInfo: 'modules/general/info'\nPages: 'modules/general/pages'\n})\n```\n\n**Return undefined**\n\nWhen i use \n\n```\n...mapState({\nmodules: 'modules'\n})\n```\n\nthis return all my substates plz help\n\n========================================\n\nTop Answer:\nThe following code should help you on your way to only get the state you actually wants, instead of all of the states on the store.\n\nFrom this approach, it means that you should have your `store` attached to Vue already, but i guess you already have from the code you're showing.\n\nYou might have to swap `'general'` with `'modules/general'`\n\n```\ncomputed: {\n ...mapState('general', {\n info: state => state.info\n })\n}\n```\n\n========================================\n\nCode:\n```text\n...mapActions({\ngetInfo: 'modules/general/get_info'\ngetPages: 'modules/general/get_pages'\n})\n```\n\n```text\n...mapState({\nInfo: 'modules/general/info'\nPages: 'modules/general/pages'\n})\n```\n\n```text\n...mapState({\nmodules: 'modules'\n})\n```\n\n```text\ncomputed: {\n ...mapState('modules/general/info', ['get_info']),\n ...mapState('modules/general/pages', ['get_pages']) \n}\n```\n\n```text\ncomputed: {\n ...mapState('modules/general', {\n info: state => state.info,\n pages: state => state.pages\n })\n},\n```\n\n```text\ncomputed: {\n ...mapState('general', {\n info: state => state.info\n })\n}\n```\n\n```text\nstore\n```\n\n```text\n'general'\n```\n\n```text\n'modules/general'\n```\n\n========================================\n\nComments:\n- computed: { ...mapState('modules/general', { Pages: (state) => state.pages, Info: (state) => state.info }) }, There is best way to get state thx for your help. And big thanks for refer it really useful","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":122,"estimatedTokens":520}}581{"id":"stack-59093211","source":"stackoverflow","questionId":59093211,"title":"Use Mixin in template with Nuxt","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Use Mixin in template with Nuxt\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to call the mixin function within the template. Vue documentation says mixin and the component are merged but i can't call the function.\n\n *getImage is not a function*\n\n**Mixin**\n\n```\nexport default {\n data() {\n return {\n l: 2,\n output: 'webp'\n }\n },\n methods: {\n getImage() {\n return 'www.example.url'\n }\n }\n}\n```\n\n**Component**\n\n```\n\n \n\nimport imageMixin from '~/mixins/image'\n\nexport default {\n name: 'New',\n mixin: { imageMixin }\n}\n\n```\n\n========================================\n\nCode:\n```text\nexport default {\n data() {\n return {\n l: 2,\n output: 'webp'\n }\n },\n methods: {\n getImage() {\n return 'www.example.url'\n }\n }\n}\n```\n\n```text\n<template>\n <v-img :src=\"getImage()\" />\n</template>\n\n<script>\nimport imageMixin from '~/mixins/image'\n\nexport default {\n name: 'New',\n mixin: { imageMixin }\n}\n</script>\n\n<style scoped></style>\n```\n\n```text\nmixin: { imageMixin }\n```\n\n```text\nmixins: [imageMixin]\n```\n\n========================================\n\nComments:\n- Thanks. Bad mistake.","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":90,"estimatedTokens":283}}582{"id":"stack-63115562","source":"stackoverflow","questionId":63115562,"title":"How to check the Nuxt.js version of an application?","tags":["nuxt.js"],"text":"Title: How to check the Nuxt.js version of an application?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nLet's say I just joined a new team. How can I quickly check the version of Nuxt the application is running?\n\n========================================\n\nTop Answer:\nOr simply via command line in the directory where your package.json is located:\n\nyarn: `yarn list | grep @nuxt/core`\n\nnpm: `npm ls | grep @nuxt/core`\n\nIf you run `npx nuxt dev` or `yarn nuxt dev` it also shows the current version.\n\n========================================\n\nCode:\n```text\npackage.json\n```\n\n```text\n@nuxt/core\n```\n\n```text\nyarn list | grep @nuxt/core\n```\n\n```text\nnpm ls | grep @nuxt/core\n```\n\n```text\nnpx nuxt dev\n```\n\n```text\nyarn nuxt dev\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":44,"estimatedTokens":183}}583{"id":"stack-65165605","source":"stackoverflow","questionId":65165605,"title":"How to test nuxt with jest?","tags":["vue.js","jestjs","nuxt.js"],"text":"Title: How to test nuxt with jest?\nTags: vue.js, jestjs, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm just learning Nuxt with jest.\nMy test.vue. just copied from https://nuxtjs.org/docs/2.x/features/data-fetching\n\n```\n\n \n \n\n### Mountains\n\n Fetching mountains...\n\n An error occurred :(\n\n \n \n\n### Nuxt Mountains\n\n \n \n- {{ mountain.title }}\n \n Refresh\n \n \n\nexport default {\n data () {\n return {\n mountains: [],\n }\n },\n async fetch () {\n this.products = await fetch(\n 'https://api.nuxtjs.dev/mountains'\n ).then(res => res.json())\n }\n}\n\n```\n\nMy test.spec.js\n\n```\nimport { mount } from '@vue/test-utils'\nimport Test from '@/components/test.vue'\n\ndescribe('Test', () => {\n test('is a Vue instance', () => {\n const wrapper = mount(Test)\n const title = wrapper.find('.page-title')\n expect(title.text()).toBe(\"Mountains\")\n })\n})\n```\n\nWhile I run the npm run test I got this error. How can I fix this issue?\n\n```\n[Vue warn]: Error in render: \"TypeError: Cannot read property 'pending' of undefined\"\n```\n\n========================================\n\nCode:\n```html\n<template>\n <div>\n <h1 class=\"page-title\">Mountains</h1>\n <p v-if=\"$fetchState.pending\">Fetching mountains...</p>\n <p v-else-if=\"$fetchState.error\">An error occurred :(</p>\n <div v-else>\n <h1>Nuxt Mountains</h1>\n <ul>\n <li v-for=\"mountain of mountains\">{{ mountain.title }}</li>\n </ul>\n <button @click=\"$fetch\">Refresh</button>\n </div>\n </div>\n</template>\n<script>\nexport default {\n data () {\n return {\n mountains: [],\n }\n },\n async fetch () {\n this.products = await fetch(\n 'https://api.nuxtjs.dev/mountains'\n ).then(res => res.json())\n }\n}\n</script>\n```\n\n```js\nimport { mount } from '@vue/test-utils'\nimport Test from '@/components/test.vue'\n\ndescribe('Test', () => {\n test('is a Vue instance', () => {\n const wrapper = mount(Test)\n const title = wrapper.find('.page-title')\n expect(title.text()).toBe(\"Mountains\")\n })\n})\n```\n\n```text\n[Vue warn]: Error in render: \"TypeError: Cannot read property 'pending' of undefined\"\n```\n\n```text\nmounted(Component, { mocks: { $fetchState: { pending: true, error: true, timestamp: Date.now() } } })\n```\n\n```text\nwrapper.vm.$options.fetch()\n```\n\n========================================\n\nComments:\n- As we are getting the reference from `$options` I had to adjust `this` to the right context, in my case what worked was `await wrapper.vm.$options.fetch.apply(wrapper.vm, [])`","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":131,"estimatedTokens":612}}584{"id":"stack-54652899","source":"stackoverflow","questionId":54652899,"title":"How to create Nuxt build with TypeScript support?","tags":["typescript","vue.js","nuxt.js"],"text":"Title: How to create Nuxt build with TypeScript support?\nTags: typescript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to build a nuxtjs app with command \"npm run build,\" which is executing \"nuxt build.\"\n\nHowever, the build fails and it looks like nuxt doesn't know how to compile Typescript code. But the funny thing is that the \"npm run dev\" command works without any problems and the app works. Just the production build is failing.\n\nI noticed that if I remove the lang=\"ts\" from the script tag in my single file components, the error is gone, but of course, the typescript code doesn't compile and other errors occur.\nI tried with various tsconfig.json configurations, but none is working.\nI have typescript and ts-loader modules included in dependencies in package.json file.\n\n```\n\"ts-loader\": \"^5.3.3\",\n\"typescript\": \"^3.3.3\",\n```\n\nThis is an example of the error message which I receive when I run \"npm run build\"\n\n```\nERROR in ./pages/index.vue?vue&type=script&lang=ts& (./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib??ref--0-2!./node_modules/ts-loader??ref--0-3!./node_modules/babel-loader/lib??ref--4-0!./node_modules/ts-loader??ref--4-1!./node_modules/vue-loader/lib??vue-loader-options!./pages/index.vue?vue&type=script&lang=ts&)\nModule build failed (from ./node_modules/thread-loader/dist/cjs.js):\nThread Loader (Worker 4)\nCannot read property 'errors' of undefined\n\n at successfulTypeScriptInstance (../node_modules/ts-loader/dist/instances.js:90:28)\n at Object.getTypeScriptInstance (../node_modules/ts-loader/dist/instances.js:34:12)\n at Object.loader (../node_modules/ts-loader/dist/index.js:17:41)\n @ ./pages/index.vue?vue&type=script&lang=ts& 1:0-404 1:420-423 1:425-826 1:425-826\n @ ./pages/index.vue\n @ ./.nuxt/router.js\n @ ./.nuxt/index.js\n @ ./.nuxt/client.js\n @ multi ./.nuxt/client.js\n```\n\nThis is my tsconfig.json\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"es5\",\n \"lib\": [\n \"dom\",\n \"es2015\"\n ],\n \"module\": \"es2015\",\n \"moduleResolution\": \"node\",\n \"experimentalDecorators\": true,\n \"noImplicitAny\": false,\n \"noImplicitThis\": false,\n \"strictNullChecks\": true,\n \"removeComments\": true,\n \"suppressImplicitAnyIndexErrors\": true,\n \"allowSyntheticDefaultImports\": true,\n \"allowJs\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"~/*\": [\n \"./*\"\n ]\n },\n \"noUnusedLocals\": true,\n \"resolveJsonModule\": true,\n \"esModuleInterop\": true\n }\n}\n```\n\nDoes anybody have any ideas how to make NuxtJs work with Typescript for production builds and not only for development?\n\nThanks\n\n========================================\n\nTop Answer:\nYou should use nuxt-ts\n\nSee some docs and example here\n\nhttps://nuxtjs.org/guide/typescript\n\nMore docs will come soon\n\n========================================\n\nCode:\n```text\n\"ts-loader\": \"^5.3.3\",\n\"typescript\": \"^3.3.3\",\n```\n\n```text\nERROR in ./pages/index.vue?vue&type=script&lang=ts& (./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib??ref--0-2!./node_modules/ts-loader??ref--0-3!./node_modules/babel-loader/lib??ref--4-0!./node_modules/ts-loader??ref--4-1!./node_modules/vue-loader/lib??vue-loader-options!./pages/index.vue?vue&type=script&lang=ts&)\nModule build failed (from ./node_modules/thread-loader/dist/cjs.js):\nThread Loader (Worker 4)\nCannot read property 'errors' of undefined\n\n at successfulTypeScriptInstance (../node_modules/ts-loader/dist/instances.js:90:28)\n at Object.getTypeScriptInstance (../node_modules/ts-loader/dist/instances.js:34:12)\n at Object.loader (../node_modules/ts-loader/dist/index.js:17:41)\n @ ./pages/index.vue?vue&type=script&lang=ts& 1:0-404 1:420-423 1:425-826 1:425-826\n @ ./pages/index.vue\n @ ./.nuxt/router.js\n @ ./.nuxt/index.js\n @ ./.nuxt/client.js\n @ multi ./.nuxt/client.js\n```\n\n```text\n{\n \"compilerOptions\": {\n \"target\": \"es5\",\n \"lib\": [\n \"dom\",\n \"es2015\"\n ],\n \"module\": \"es2015\",\n \"moduleResolution\": \"node\",\n \"experimentalDecorators\": true,\n \"noImplicitAny\": false,\n \"noImplicitThis\": false,\n \"strictNullChecks\": true,\n \"removeComments\": true,\n \"suppressImplicitAnyIndexErrors\": true,\n \"allowSyntheticDefaultImports\": true,\n \"allowJs\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"~/*\": [\n \"./*\"\n ]\n },\n \"noUnusedLocals\": true,\n \"resolveJsonModule\": true,\n \"esModuleInterop\": true\n }\n}\n```\n\n========================================\n\nComments:\n- Thanks, I will try it out if I don't find a solution with the basic Nuxt.js :)\n- @papazulu ye but it is basic nuxt just, it's new official way to use ts with nuxt\n- The important here for me was \"remove `typescript`\". Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":147,"estimatedTokens":1205}}585{"id":"stack-70751297","source":"stackoverflow","questionId":70751297,"title":"i18n : translate a sentence that one of words is bold","tags":["vue.js","internationalization","nuxt.js","vue-i18n"],"text":"Title: i18n : translate a sentence that one of words is bold\nTags: vue.js, internationalization, nuxt.js, vue-i18n\nSource: Stack Overflow\n\nQuestion:\nI want to **translate** this **sentence** in i18n\n\n```\nSelect **branch(s)** you want to send selected product\nafter selecting Branch Click on submit\n```\n\nAs you can see , one word in above sentence is in `` tag.\n\nI have this **solution** , But I am **not** sure is this is the best way to do or not.\n\n```\n$t('part1') **$t('part2')** $t('part3')\n```\n\nso ,do you know **better** way to **translate** this ??\n\n========================================\n\nTop Answer:\nJust a update regarding vue-i18n docs:\n\n```\n\n \n **{{ $t('subText') }}**\n \n \n```\n\n========================================\n\nCode:\n```text\nSelect <b>branch(s)</b> you want to send selected product\nafter selecting Branch Click on submit\n```\n\n```text\n$t('part1') <b>$t('part2')</b> $t('part3')\n```\n\n```text\n<b>\n```\n\n```js\nconst messages = {\n en: {\n info: 'Select {branchText} you want to send selected product after selecting Branch Click on submit.',\n subText: 'branch(s)',\n }\n}\n```\n\n```html\n<i18n path=\"info\" tag=\"p\">\n <template v-slot:branchText>\n <b>{{ $t('subText') }}</b>\n </template>\n</i18n>\n```\n\n```text\n$t('part1') <b>$t('part2')</b> $t('part3')\n```\n\n```text\ni18n\n```\n\n```text\n<i18n-t :keypath=\"info\" tag=\"p\">\n <template #branchText>\n <b>{{ $t('subText') }}</b>\n </template>\n </i18n-t>\n```\n\n========================================\n\nComments:\n- You can check this link: kazupon.github.io/vue-i18n/guide/…\n- ...although I agree that in this case where you are in complete control of HTML, using `v-html` would be just fine too\n- @MichalLevý I'd say, who knows: better safe than sorry. If it adds a layer of security (if your locale files are stored in a less safer place or exposed to your product team idk), it's fine to have it like this. Of course, you can also add a sanitizer on top of the `v-html` too.","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":90,"estimatedTokens":491}}586{"id":"stack-58236278","source":"stackoverflow","questionId":58236278,"title":"@Nuxt/Apollo How can i remove \"__typeName\" from gql query","tags":["vue.js","apollo","nuxt.js"],"text":"Title: @Nuxt/Apollo How can i remove \"__typeName\" from gql query\nTags: vue.js, apollo, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am working on nuxt/apollo package but there is no information about addTypeName property. Where should be set this property ? \nNote: All installations working about @nuxt/apollo. (imported as module etc.)\n\n**Version info :**\n\n```\n\"@nuxtjs/apollo\": \"^4.0.0-rc8\",\n```\n\n My apollo config in nuxt.config.js :\n\n```\napollo: {\n includeNodeModules: false,\n authenticationType: 'Basic',\n defaultOptions: {\n $query: {\n loadingKey: 'loading',\n fetchPolicy: 'cache-and-network'\n }\n },\n clientConfigs: {\n default: {\n httpEndpoint: 'DEFAULT_GRAPHQL_ENDPOINT',\n tokenName: 'apollo-token' // optional\n },\n financial: {\n httpEndpoint: 'NEWS_GRAPHQL_ENDPOINT',\n tokenName: 'apollo-token',\n addTypename: false --> **Is not working**\n }\n }\n }\n```\n\n My Index.vue page is :\n\n```\napollo: {\ndata: {\n query: gql`\n {\n newsJson(take: 1) {\n key\n *GENERATES __typeName when sending request to Graphql*\n }\n }\n `,\n client: 'financial'\n}\n}\n```\n\n My graphql query (via graphiql on web) :\n\n```\n{\n newsJson(take:1){\n key\n approve\n }\n}\n```\n\n And **Response** is :\n\n```\n{\n \"data\": {\n \"newsJson\": [\n {\n \"key\": 2071554,\n \"approve\": false\n }\n ]\n }\n}\n```\n\nWhen i sent request __typeName crashes me on graphql web side. How can i prevent adding **__typeName** property to request ? \n\nBest Regards, \n\nThanks\n\n========================================\n\nCode:\n```text\n\"@nuxtjs/apollo\": \"^4.0.0-rc8\",\n```\n\n```text\napollo: {\n includeNodeModules: false,\n authenticationType: 'Basic',\n defaultOptions: {\n $query: {\n loadingKey: 'loading',\n fetchPolicy: 'cache-and-network'\n }\n },\n clientConfigs: {\n default: {\n httpEndpoint: 'DEFAULT_GRAPHQL_ENDPOINT',\n tokenName: 'apollo-token' // optional\n },\n financial: {\n httpEndpoint: 'NEWS_GRAPHQL_ENDPOINT',\n tokenName: 'apollo-token',\n addTypename: false --> **Is not working**\n }\n }\n }\n```\n\n```text\napollo: {\ndata: {\n query: gql`\n {\n newsJson(take: 1) {\n key\n *GENERATES __typeName when sending request to Graphql*\n }\n }\n `,\n client: 'financial'\n}\n}\n```\n\n```text\n{\n newsJson(take:1){\n key\n approve\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"newsJson\": [\n {\n \"key\": 2071554,\n \"approve\": false\n }\n ]\n }\n}\n```\n\n```text\nclientConfigs: {\n default: {\n ...\n inMemoryCacheOptions: {\n addTypename: false,\n },\n },\n}\n```\n\n```text\nInMemoryCache\n```\n\n```text\naddTypename\n```\n\n```text\nfalse\n```\n\n```text\n__typename\n```\n\n```text\nid\n```\n\n```text\n_id\n```\n\n```text\n__typename\n```\n\n========================================\n\nComments:\n- It's not really clear what you mean by \"*_typeName crashes me on graphql web side\". The property added by Apollo is ***_typename**, not ***_typeName**. This is a standard meta field added by GraphQL. If you're attempting to request ***_typeName** (not **__typename**) in GraphiQL, then you will get an error because no such field exists.\n- There's no reason that the client appending the **__typename** field would cause any issues with your query. Omitting the field, on the other hand, can cause issues with your client.\n- @DanielRearden My gql function (graphql-tag) generates query that including _typeName (built-in) field and send to graphql endpoint. (I wasn't add this field manually.) This state causing issue on graphql endpoint. Example gql output to will send endpoint --> {newsJson(take:1){ key *_typeName* }}\n- graphql-tag only transforms a string into a GraphQL DocumentNode object. It does not add any fields to your request. If the request being sent to the server is ending up with `__typeName` instead of `__typename`, there's something else going on. Maybe you could provide a repo link to the full code or provide a sandbox with the bug reproduced.\n- I m working on sandbox\n- I updated my config but still same... i am going to edit my post.","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":207,"estimatedTokens":997}}587{"id":"stack-76527094","source":"stackoverflow","questionId":76527094,"title":"Nuxt 3 and Vue 3 onMounted call function useFetch function not getting data form APIs","tags":["javascript","vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: Nuxt 3 and Vue 3 onMounted call function useFetch function not getting data form APIs\nTags: javascript, vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nHi i am new in Nuxt and Vue. I am using Nuxt framework to get data form APIs. I want to get data from APIs when onMounted method call.\n\nI created saprate function to call api. That api get data with product id.\nIf i call API without onMounted method it is working fine but when i call function in OnMounted method it is not working. always get \"null\" value.\n\nCode given blew\n\n```\n\n const product = async (id) => {\n \n const { data, pending, error } = await useFetch(`https://fakestoreapi.com/products/${id}`);\n \n console.log(\"after this\" + id);\n console.log(data.value);\n \n }; \n\n onMounted(async () => { \n product(2); \n \n });\n\nOtuput in console\nafter this 2\nnull\n```\n\n========================================\n\nTop Answer:\nWent actually through the same error, and always using `nextTick` seemed wrong.\n\nThe real reasons behind this is the misuse of the `useFetch` which is reactive and shoud be used only in the root part of the setup script.\nIf you use `$fetch` the problem won't appear.\n\nhttps://github.com/nuxt/nuxt/issues/13471#issuecomment-1889647593\n\n========================================\n\nCode:\n```text\n<script setup>\n\n const product = async (id) => {\n \n const { data, pending, error } = await useFetch(`https://fakestoreapi.com/products/${id}`);\n \n console.log(\"after this\" + id);\n console.log(data.value);\n \n }; \n\n onMounted(async () => { \n product(2); \n \n });\n</script>\n\nOtuput in console\nafter this 2\nnull\n```\n\n```js\nimport { nextTick } from 'vue';\n\nonMounted(async () => {\n\n await nextTick();\n\n await getProduct(2);\n});\n```\n\n```text\nonMounted\n```\n\n```text\nnextTick\n```\n\n```text\nnextTick\n```\n\n```text\nuseFetch\n```\n\n```text\n$fetch\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":99,"estimatedTokens":470}}588{"id":"stack-63038216","source":"stackoverflow","questionId":63038216,"title":"Laravel Sanctum - Logged in user best practise","tags":["laravel","vue.js","vuex","nuxt.js","laravel-sanctum"],"text":"Title: Laravel Sanctum - Logged in user best practise\nTags: laravel, vue.js, vuex, nuxt.js, laravel-sanctum\nSource: Stack Overflow\n\nQuestion:\nI was wondering what is the best practise for checking that a user is still logged in client side.\n\nLet's say a user logs in. If it's successfull it will be saved in the state, something like this:\n\n```\naxios.post('/login').then(() => {\n this.state.loggedInUser = true\n});\n```\n\nNow if a user refreshes their browser, the state is lost, but the `laravel_session` and `XSRF-TOKEN` are still available and valid.\n\nWould it make sense to add middleware on every page reload to make a request to retrieve the current logged in user's information? Something like this?:\n\n```\nconst authMiddleware = () => {\n axios.get('/user').catch(() => console.error('user is not logged in!'));\n};\n```\n\n**EDIT**\n\nPlease be aware that I'm using Sanctum in SPA mode. So there's no tokens.\n\n========================================\n\nTop Answer:\nstore it in sessionStorage, and also initialize loggedInUser from sessionStorage as:\n\n```\nsessionStorage.getItem('loggedInUser') === 'true' || false\n```\n\n========================================\n\nCode:\n```text\naxios.post('/login').then(() => {\n this.state.loggedInUser = true\n});\n```\n\n```text\nconst authMiddleware = () => {\n axios.get('/user').catch(() => console.error('user is not logged in!'));\n};\n```\n\n```text\nlaravel_session\n```\n\n```text\nXSRF-TOKEN\n```\n\n```text\nimport { isLoggedIn } from \"./utils\";\nexport default {\n state: {\n isLoggedIn: false,\n user: {}\n },\n mutations: {\n setUser(state, payload) {\n state.user = payload;\n },\n setLoggedIn(state, payload) {\n state.isLoggedIn = payload;\n }\n },\n actions: {\n async loadUser({ commit, dispatch }) {\n if (isLoggedIn) {\n try {\n const user = (await axios.get(\"/user\")).data;\n commit(\"setUser\", user);\n commit(\"setLoggedIn\", true);\n } catch (error) {\n console.log(error)\n }\n }\n }\n }\n};\n```\n\n```text\nexport function isLoggedIn() {\n return localStorage.getItem(\"isLoggedIn\") == \"true\";\n}\n\nexport function logIn() {\n localStorage.setItem(\"isLoggedIn\", true);\n}\n```\n\n```text\n<script>\nimport { logIn } from \"../utils\";\n methods: {\n async login() {\n try {\n await axios.get(\"/sanctum/csrf-cookie\");\n await axios.post(\"/login\", {\n email: this.email,\n password: this.password\n });\n logIn();\n this.$store.dispatch(\"loadUser\");\n this.$router.push('/');\n } catch (error) {\n console.log(error);\n }\n }\n }\n</script>\n```\n\n```text\nconst app = new Vue({\n ...\n async beforeCreate() {\n this.$store.dispatch(\"loadUser\");\n }\n});\n```\n\n```text\nuser\n```\n\n```text\nisLoggedIn\n```\n\n```text\nlogIn()\n```\n\n```text\nloadUser\n```\n\n```text\nloadUser\n```\n\n```text\nsessionStorage.getItem('loggedInUser') === 'true' || false\n```\n\n========================================\n\nComments:\n- Have you tried `serverMiddleware`? You can access `req.headers` to extract the session. It uses connect instance, check this out stackoverflow.com/questions/13147693/…. It's also a best practice to always run tokens and other sensitive informations in the server.\n- For `serverMiddleware` reference: nuxtjs.org/api/configuration-servermiddleware","metadata":{"transformedAt":"2026-08-18T18:33:07.879Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":162,"estimatedTokens":892}}589{"id":"stack-51434041","source":"stackoverflow","questionId":51434041,"title":"vue.js : error unknown action type?","tags":["javascript","vue.js","nuxt.js"],"text":"Title: vue.js : error unknown action type?\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI created my store store/user.js\n\n```\nexport const state = () => ({\n user: {},\n });\nexport const mutations = {\n\n};\nexport const actions = {\n AUTH ({commit},{email, password}){\nconsole.log('email, password =', email, password)\n }\n};\n\nexport const getters = {};\n```\n\ncomponent:\n\n```\n\n \n \n\n import { mapActions } from 'vuex'\n\n export default {\n\n data() {\n return {\n model:{\n email:\" \" ,\n password:\" \"\n\n }\n\n }\n },\n methods: {\n ...mapActions(['AUTH']),\n}\n}\n```\n\nIn my component , I am trying to execute a vuex action from a module, but I am getting an error, even if this action is defined :\n\n```\nunknown action type: AUTH,\n```\n\nI don't have any idey about problem.\n\nindex.js\n\n```\nimport Vue from 'vue'\nimport Vuex from 'vuex'\n\nimport user from './modules/user.js'\n\nVue.use(Vuex);\n\nconst store = new Vuex.Store({\n modules: {\n user\n }\n})\n```\n\n========================================\n\nCode:\n```text\nexport const state = () => ({\n user: {},\n });\nexport const mutations = {\n\n};\nexport const actions = {\n AUTH ({commit},{email, password}){\nconsole.log('email, password =', email, password)\n }\n};\n\nexport const getters = {};\n```\n\n```text\n<template>\n<form @submit.prevent=\"AUTH(model)\">\n <input type=\"text\" required v-model.lazy = \"model.email\">\n <input type=\"password\" required v-model.lazy = \"model.password\" >\n</template>\n\n\n<script>\n import { mapActions } from 'vuex'\n\n export default {\n\n data() {\n return {\n model:{\n email:\" \" ,\n password:\" \"\n\n }\n\n }\n },\n methods: {\n ...mapActions(['AUTH']),\n}\n}\n```\n\n```text\nunknown action type: AUTH,\n```\n\n```text\nimport Vue from 'vue'\nimport Vuex from 'vuex'\n\nimport user from './modules/user.js'\n\nVue.use(Vuex);\n\nconst store = new Vuex.Store({\n modules: {\n user\n }\n})\n```\n\n```text\nimport { createNamespacedHelpers } from 'vuex'\n\nconst { mapState, mapActions } = createNamespacedHelpers('users')\n```\n\n```text\n...mapActions([\n 'users/AUTH'\n])\n\n// if you are only using one module in the component\n...mapActions('users', [\n 'AUTH'\n])\n```\n\n```text\nexport const state = () => ({\n foo: 0,\n bar: 1\n})\n```\n\n```text\n- store\n-- index.js // the store\n-- users.js // module 'users'\n-- foo.js // module 'foo'\n```\n\n```text\n// template\n<form @submit.prevent=\"submitForm\">\n\n// script\nmethods: {\n ...mapActions({\n auth: 'users/AUTH'\n }),\n submitForm () {\n this.auth(this.model)\n }\n}\n```\n\n```text\ncreateNamespacedHelpers\n```\n\n```text\nindex.js\n```\n\n```text\nstore\n```\n\n========================================\n\nComments:\n- Can you provide your code which creates the store? Are you using vuex modules?\n- Because you're using modules, it'll be namespaced. See this answer.\n- [nuxt] store/index.js should export a method which returns a Vuex instance. i get err\n- When using modules mode in Nuxt, you don't create the store yourself. Instead, export the state, getters, mutations and actions.\n- i use nuxt . how to do it nuxt?\n- i fix store/user.js\n- i get err Uncaught TypeError: _vm.AUTH is not a function\n- Try using `this.$store.dispatch('users/AUTH')`.\n- and Property or method \"AUTH\" is not defined on the instance but referenced during render.\n- i fix but get fn.bind is not a function .\n- I don't see where `bind` is being used in any of the code you've posted.\n- I found a mistake. Thanks a lot for your help","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":215,"estimatedTokens":862}}590{"id":"stack-76831988","source":"stackoverflow","questionId":76831988,"title":"Nuxt i18n Calling useRoute within middleware may lead to misleading results","tags":["javascript","vue.js","nuxt.js","vue-i18n"],"text":"Title: Nuxt i18n Calling useRoute within middleware may lead to misleading results\nTags: javascript, vue.js, nuxt.js, vue-i18n\nSource: Stack Overflow\n\nQuestion:\nSo I am getting this warning in nuxt3:\n`Calling useRoute within middleware may lead to misleading results. Instead, use the (to, from) arguments passed to the middleware to access the new and old routes.`\n\nThis happens because I am calling `useLocalePath()` in my middleware.\n\nThis is one of the middleware where it happens:\n\n```\nexport default defineNuxtRouteMiddleware(async(to, from) => {\n const localPath = useLocalePath()\n\n const isUserAuthenticated = await isAuthenticated()\n\n if (isUserAuthenticated) {\n if (to.fullPath === localPath('login') || to.fullPath === localPath('register')) {\n return navigateTo(localPath('/'))\n }\n } else {\n if (to.fullPath !== localPath('login') && to.fullPath !== localPath('register')) {\n return navigateTo(localPath('login'))\n }\n }\n\n})\n```\n\nI have this in my nuxt.config.ts:\n\n```\ni18n: {\n lazy: true,\n langDir: \"locales\",\n strategy: \"prefix_and_default\",\n locales: [\n {\n code: 'nl-Nl',\n iso: 'nl-Nl',\n name: 'Dutch',\n file: 'nl-NL.json'\n },\n {\n code: 'en',\n iso: 'en',\n name: 'English',\n file: 'en.json'\n },\n ],\n detectBrowserLanguage: {\n useCookie: true,\n cookieCrossOrigin: true,\n alwaysRedirect: true,\n cookieKey: 'i18n_redirected',\n redirectOn: 'root'\n },\n defaultLocale: \"nl-Nl\",\n customRoutes: 'config',\n pages: {\n pricing: {\n en: '/pricing',\n 'nl-Nl': '/prijzen',\n }\n }\n }\n```\n\nThis is the version of i18n that i'm using:\n`\"@nuxtjs/i18n\": \"^8.0.0-beta.12\",`\n\nThe thing is, the code is working perfectly fine, but I don't have any clue why it's giving me this warning.\n\nIs it safe to ignore this warning?\n\n========================================\n\nTop Answer:\n`useLocalePath()` uses the `useRoute()` method under the hood that's why you are getting that warn. one solution could be to use `useI18n()` instead and accesing the App locale variable.\n\n```\nconst locale = useNuxtApp().$i18n.locale;\n\nif (!to.fullPath.includes(\"login\")) {\n return navigateTo(`${locale.value}/login`);\n}\n```\n\nor just add a re-usable composable.\n\n```\nexport default function useTranslateUrl(url: string): string {\n const locale = useNuxtApp().$i18n.locale;\n return `/${locale.value}${url.startsWith(\"/\") ? url : `/${url}`}`;\n}\n```\n\n**Note**: make sure your locales are never in an `iso` format like `en-US`, unless your whole i18n configuration is setup that way.\n\n========================================\n\nCode:\n```text\nexport default defineNuxtRouteMiddleware(async(to, from) => {\n const localPath = useLocalePath()\n\n const isUserAuthenticated = await isAuthenticated()\n\n if (isUserAuthenticated) {\n if (to.fullPath === localPath('login') || to.fullPath === localPath('register')) {\n return navigateTo(localPath('/'))\n }\n } else {\n if (to.fullPath !== localPath('login') && to.fullPath !== localPath('register')) {\n return navigateTo(localPath('login'))\n }\n }\n\n})\n```\n\n```text\ni18n: {\n lazy: true,\n langDir: \"locales\",\n strategy: \"prefix_and_default\",\n locales: [\n {\n code: 'nl-Nl',\n iso: 'nl-Nl',\n name: 'Dutch',\n file: 'nl-NL.json'\n },\n {\n code: 'en',\n iso: 'en',\n name: 'English',\n file: 'en.json'\n },\n ],\n detectBrowserLanguage: {\n useCookie: true,\n cookieCrossOrigin: true,\n alwaysRedirect: true,\n cookieKey: 'i18n_redirected',\n redirectOn: 'root'\n },\n defaultLocale: \"nl-Nl\",\n customRoutes: 'config',\n pages: {\n pricing: {\n en: '/pricing',\n 'nl-Nl': '/prijzen',\n }\n }\n }\n```\n\n```text\nCalling useRoute within middleware may lead to misleading results. Instead, use the (to, from) arguments passed to the middleware to access the new and old routes.\n```\n\n```text\nuseLocalePath()\n```\n\n```text\n\"@nuxtjs/i18n\": \"^8.0.0-beta.12\",\n```\n\n```text\nexport default defineNuxtRouteMiddleware(async(to, from) => {\n const nuxt = useNuxtApp()\n\n const isUserAuthenticated = await isAuthenticated()\n\n if (isUserAuthenticated) {\n if (to.fullPath === nuxt.$localePath('login') || to.fullPath === nuxt.$localePath('register')) {\n return navigateTo(nuxt.$localePath('/'))\n }\n } else {\n if (to.fullPath !== nuxt.$localePath('login') && to.fullPath !== nuxt.$localePath('register')) {\n return navigateTo(nuxt.$localePath('login'))\n }\n }\n\n})\n```\n\n```js\nconst locale = useNuxtApp().$i18n.locale;\n\nif (!to.fullPath.includes(\"login\")) {\n return navigateTo(`${locale.value}/login`);\n}\n```\n\n```text\nexport default function useTranslateUrl(url: string): string {\n const locale = useNuxtApp().$i18n.locale;\n return `/${locale.value}${url.startsWith(\"/\") ? url : `/${url}`}`;\n}\n```\n\n```text\nuseLocalePath()\n```\n\n```text\nuseRoute()\n```\n\n```text\nuseI18n()\n```\n\n```text\niso\n```\n\n```text\nen-US\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":225,"estimatedTokens":1283}}591{"id":"stack-59829082","source":"stackoverflow","questionId":59829082,"title":"Vue-Nuxt: Why can't I see the generated HTMLs correctly?","tags":["html","vuejs2","static","nuxt.js"],"text":"Title: Vue-Nuxt: Why can't I see the generated HTMLs correctly?\nTags: html, vuejs2, static, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSo when I type `npm run generate` Nuxt generates my project into the `dist` folder. In that folder I can find a folder called `_nuxt` where I have `.js` files and the `index.html` file but when I open it in a browser it doesn't show anything.\n\nSo, my question is: **Aren't those static files?**\n\nWhen you work with the *CDN served* `vue.js` you have the `html` file and you click and everything is showed on the browser because those `.html` files are static, they don't need an internal localhost server. **Why `npm run generate` doesn't do the same? Or how can I see those generated files?**\n\n========================================\n\nTop Answer:\n**Nuxt uses server side rendering.** \n\nYou can read more here.\n\nTo generate static HTML files, run:\n\n```\nnuxt generate\n```\n\n**Explanation:** Vanilla Vue.js application is rendered only when the page loads and JavaScript can start running. This means that some clients that do not have JavaScript enabled (web crawlers) won't see the page. Also for a brief second before Vue.js can render the page, there is blank screen, when plain HTML files could already be visible.\n\nNow, server-side rendering (SSR) is a technique for rendering a single page app (SPA) **on the server and then sending a fully rendered page to the client**. The client’s JavaScript bundle can then take over and the SPA can operate as normal. \n\nThis can also help with SEO and with providing meta data to social media channels.\n\nBut on the downside (as you mentioned), such application cannot be hosted at a CDN, since you have to have a Node.js process running to render the page.\n\nIn my opinion, SSR is redundant with SPAs if what you are building is actually an application and not a website. A website should mostly display information and should not be interactive. It should leverage web-based mechanisms such as links, cookies and plain HTML with CSS. In the contrast, web *application* (eg. Vue.js application) should be more like a mobile application: it is larger to download, but performs better and offers much more interactive experience. Such application does not need server-side rendering, since we can wait for it to load a bit more and because it shouldn't be indexed by search engines (it is not a website).\n\n========================================\n\nCode:\n```text\nnpm run generate\n```\n\n```text\ndist\n```\n\n```text\n_nuxt\n```\n\n```text\n.js\n```\n\n```text\nindex.html\n```\n\n```text\nvue.js\n```\n\n```text\nhtml\n```\n\n```text\n.html\n```\n\n```text\nnpm run generate\n```\n\n```sh\npython -m http.server\n```\n\n```text\nSSR\n```\n\n```text\nNuxt.js\n```\n\n```text\nindex.html\n```\n\n```text\nfile:///\n```\n\n```text\n.js\n```\n\n```text\nsrc\n```\n\n```text\nfile:///\n```\n\n```text\n/your_js.js\n```\n\n```text\n/\n```\n\n```text\n/\n```\n\n```text\nBuild the application and generate every route as a HTML file (used for static hosting).\n```\n\n```text\nnuxt generate\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":124,"estimatedTokens":745}}592{"id":"stack-65630874","source":"stackoverflow","questionId":65630874,"title":"How to add a redirection in Nuxt router middleware?","tags":["nuxt.js","middleware"],"text":"Title: How to add a redirection in Nuxt router middleware?\nTags: nuxt.js, middleware\nSource: Stack Overflow\n\nQuestion:\nI have created a middleware to check if new user email has been verified `middleware/verify_email.js`:\n\n```\nexport default function (context) {\n if (context.$auth.loggedIn && !context.$auth.user.email_verified_at) {\n console.log('logged in with email not verified');\n return context.redirect('/auth/verify');\n }\n}\n```\n\nThen, I have set this middlware globally in `nuxt.config.js`:\n\n```\nrouter: {\n middleware: ['auth', 'verify_email']\n },\n```\n\nBut it seems I'm getting an infinite loop, the page in not not responding. It responds again as soon as I comment the redirect line.\n\nNavigationDuplicated: Avoided redundant navigation to current location: \"/auth/verify\".\n\nI probably need to add an exception to this middleware for the page `auth/verify` but I can't figure out how.\n\nAny idea how I should fix this issue ?\n\n========================================\n\nCode:\n```text\nexport default function (context) {\n if (context.$auth.loggedIn && !context.$auth.user.email_verified_at) {\n console.log('logged in with email not verified');\n return context.redirect('/auth/verify');\n }\n}\n```\n\n```text\nrouter: {\n middleware: ['auth', 'verify_email']\n },\n```\n\n```text\nmiddleware/verify_email.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nauth/verify\n```\n\n```js\nexport default function (context) {\n\n if (context.route.name === \"auth-verify\")\n // skip middleware\n return\n }\n\n if (context.$auth.loggedIn && !context.$auth.user.email_verified_at) {\n console.log('logged in with email not verified');\n return context.redirect('/auth/verify');\n }\n}\n```\n\n```text\n'/auth/verify'\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":80,"estimatedTokens":427}}593{"id":"stack-73800242","source":"stackoverflow","questionId":73800242,"title":"Nuxt Content v2 markdown headers rendered as URLs","tags":["html","nuxt.js","markdown","nuxt3.js","nuxt-content"],"text":"Title: Nuxt Content v2 markdown headers rendered as URLs\nTags: html, nuxt.js, markdown, nuxt3.js, nuxt-content\nSource: Stack Overflow\n\nQuestion:\nI'm writing Markdown content in Nuxt 3 & Nuxt Content 2.1 and I am facing a problem as I cannot write h2-h6 headers without it rendering them as links.\n\nh1 works fine with one octothorpe symbol but as soon as I add 1 or more of them to render smaller headers, the application automatically transforms them to URLs.\n\nContent is rendered with the default `[...slug].vue` and `` configuration as seen in the documentation.\n\nWhat's written in Markdown:\n\n```\n# header 1\n\n## header 2\n```\n\n... and what's actually being rendered in HTML:\n\n```\n\n \n header 1\n \n\n \n \n header 2\n \n \n\n```\n\nIs there any way to solve this?\n\n**EDIT:**\n\nNuxt is also transforming simple HTML `` tags to links, but now with an undefined `href`:\n\n```\n\n### header 2\n\n```\n\nto\n\n```\n\n \n header 2\n \n\n```\n\n========================================\n\nTop Answer:\nCheckout the Nuxt Content doc here:\n\nIn Nuxt Content, Prose represents the HTML tags output from the Markdown syntax, for example title levels, links... A Vue component corresponds to each tag, allowing you to override them if needed.\n\nBy default, h2 becomes tag in tag, it is defined in this file. These files are listed in components/prose section.\n\nYou may overwrite it by:\n\n- create **components/content** directory\n\n- create **ProseH2.vue** in it\n\n- copy the code from the origin file, in the **template** section, remove the tag and the v-else, or whatever modification you want to do with it:\n\n```\n\n \n \n \n\n```\n\n**Restart server**, it should changes.\n\n========================================\n\nCode:\n```markdown\n# header 1\n\n## header 2\n```\n\n```html\n<h1 id=\"header-1\">\n <!--[-->\n header 1\n <!--]-->\n</h1>\n\n<h2 id=\"header-2\">\n <a href=\"#header-2\">\n <!--[-->\n header 2\n <!--]-->\n </a>\n</h2>\n```\n\n```html\n<h2>header 2</h2>\n```\n\n```html\n<h2>\n <a href=\"#undefined\">\n header 2\n </a>\n</h2>\n```\n\n```text\n[...slug].vue\n```\n\n```text\n<ContentDoc />\n```\n\n```text\n<h2>\n```\n\n```text\nhref\n```\n\n```text\ncontent: {\n markdown: {\n anchorLinks: false,\n }\n},\n```\n\n```text\n<template>\n <h2 :id=\"id\">\n <slot />\n </h2>\n</template>\n```\n\n========================================\n\nComments:\n- this was driving me nuts. your solution saved me. thank you so much.\n- this should be the accepted answer, with Nick_Ning's answer, you have to change it for every heading tag","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":158,"estimatedTokens":610}}594{"id":"stack-52236443","source":"stackoverflow","questionId":52236443,"title":"Nuxtjs getting firestore data within asyncData","tags":["firebase","vuejs2","google-cloud-firestore","nuxt.js","server-side-rendering"],"text":"Title: Nuxtjs getting firestore data within asyncData\nTags: firebase, vuejs2, google-cloud-firestore, nuxt.js, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nI'm trying to convert my VueJS app to NuxtJS to work with SSR. I'm stuck trying to get data loaded with asyncData. When I add my query to a `'mounted() {}'` function it works fine but I can't get it to work with `asyncData(){}` so that I can use SSR. \n\nDoes anyone have any idea how to fix this. \n\nMy code: \n\n```\n\n \n- {{province.name_nl}}\n \n\n asyncData () {\n return { msg: 'Welcome to my new app' }\n const moment = require(\"moment\");\n var date = moment(new Date()).format(\"YYYY-MM-DD\");\n let housesArray = []\n let provincesArray = []\n\n return firebase.firestore()\n .collection('provinces')\n .get()\n .then(querySnapshot => {\n querySnapshot.forEach(doc => {\n provincesArray.push(doc.data());\n });\n return {provinces: provincesArray}\n });\n },\n```\n\nOr is there another way I should be doing this? Keeping in mind that it does have to work with SSR. \n\nPS: Yes this code is inside my pages folder, not the component, I know that's not allowed.\n\n========================================\n\nCode:\n```text\n<ul>\n <li v-for='province in provinces' v-bind:key=\"province.id\"> {{province.name_nl}}</li>\n </ul>\n\n asyncData () {\n return { msg: 'Welcome to my new app' }\n const moment = require(\"moment\");\n var date = moment(new Date()).format(\"YYYY-MM-DD\");\n let housesArray = []\n let provincesArray = []\n\n return firebase.firestore()\n .collection('provinces')\n .get()\n .then(querySnapshot => {\n querySnapshot.forEach(doc => {\n provincesArray.push(doc.data());\n });\n return {provinces: provincesArray}\n });\n },\n```\n\n```text\n'mounted() {}'\n```\n\n```text\nasyncData(){}\n```\n\n```text\nasync asyncData () {\n const moment = require(\"moment\");\n var date = moment(new Date()).format(\"YYYY-MM-DD\");\n let housesArray = []\n let provincesArray = []\n\nawait firebase.firestore()\n .collection('provinces')\n .orderBy('name_nl')\n .get()\n .then(querySnapshot => {\n querySnapshot.forEach(doc => {\n provincesArray.push(doc.data());\n });\n });\n\nawait firebase.firestore()\n .collection(\"houses\")\n .where(\"valid_until\", \">\", date)\n .get()\n .then(querySnapshot => {\n querySnapshot.forEach(doc => {\n housesArray.push(doc.data());\n });\n });\n\nreturn {\n provinces: provincesArray,\n houses: housesArray\n}\n },\n```\n\n```text\nasyncDate()\n```\n\n```text\nasync\n```\n\n```text\nawait\n```\n\n========================================\n\nComments:\n- so what errors? how its not working\n- Im not getting any errors, but i also cant console.log or debug the code. So it doesn’t show anything. So i’m not sure where to start.\n- you have a return at top of asyncData so no code past that executed\n- Thanks, I didn't realise that the code after a return doesn't get executed. Still trying to learn. But then I still can't return the firestore data because I need to execute 2 calls to firestore, but if I return both with return {provinces: provincesArray, houses: housesArray} the firestore function isn't always executed before the return, any idea on what I have to do to wait for the response, or some documentation anyone knows of that could point me in the correct direction?\n- I just needed to add 'async' 'await' to fix it, thanks for the help.\n- @jonas could you post the updated answer below as your solution? I have the same issue\n- @pmanning yes of course, sorry. Should have thought of that myself. :) Anyway I added my solution now. Just let me know if it isn't clear.\n- how do you import firebase/firestore in .vue?\n- Have a look at the tutorial here: medium.com/@anas.mammeri/… It's from a while back but I think everything is still relevant.","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":133,"estimatedTokens":946}}595{"id":"stack-69645641","source":"stackoverflow","questionId":69645641,"title":"Nuxt firebase write doc after createUserWithEmailAndPassword fail","tags":["javascript","firebase","vue.js","google-cloud-firestore","nuxt.js"],"text":"Title: Nuxt firebase write doc after createUserWithEmailAndPassword fail\nTags: javascript, firebase, vue.js, google-cloud-firestore, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nThe idea of register form is\n\n- add user email and password to firebase auth, this is successful, then\n\n- add new document using their `uid` as document id and insert street field and value; to `profile` collection, failed without error.\n\nThe user and email are added to the auth users in firebase console, but the document writing still unsuccessfull with no error on the console either.\n\nBeen scratching my head for awhile.\n\nHere's my code\n\n```\n\n \n \n \n \n \n Register\n \n \n\nimport Vue from 'vue'\nimport { createUserWithEmailAndPassword, onAuthStateChanged } from 'firebase/auth'\nimport { doc, setDoc } from 'firebase/firestore'\nimport { auth, db } from '~/plugins/firebase.js'\n\nexport default Vue.extend({\n data () {\n return {\n register: {}\n }\n },\n \n methods: {\n async createUser () {\n await createUserWithEmailAndPassword(\n auth,\n this.register.email,\n this.register.password\n ).catch((error) => {\n console.log(error.code)\n console.log(error.message)\n })\n\n onAuthStateChanged(\n auth,\n (user) => {\n if (user) {\n const ref = doc(db, 'profile', user.uid)\n const document = {\n street: this.register.street\n }\n try {\n setDoc(ref, document)\n } catch (e) {\n alert('Error!')\n console.error(e.code)\n console.error(e.message)\n }\n }\n }\n )\n }\n }\n})\n\n```\n\nfirestore rule with no restriction\n\n```\nrules_version = '2';\nservice cloud.firestore {\n match /databases/{database}/documents {\n match /{document=**} {\n allow read;\n allow write;\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\n<template>\n <v-form @submit.prevent=\"createUser\">\n <v-text-field\n v-model=\"register.email\"\n label=\"Email\"\n required\n />\n <v-text-field\n v-model=\"register.password\"\n label=\"Password\"\n required\n />\n <v-text-field\n v-model=\"register.street\"\n required\n label=\"Street\"\n />\n <v-btn\n type=\"submit\"\n >\n Register\n </v-btn>\n </v-form>\n</template>\n\n<script>\nimport Vue from 'vue'\nimport { createUserWithEmailAndPassword, onAuthStateChanged } from 'firebase/auth'\nimport { doc, setDoc } from 'firebase/firestore'\nimport { auth, db } from '~/plugins/firebase.js'\n\nexport default Vue.extend({\n data () {\n return {\n register: {}\n }\n },\n \n methods: {\n async createUser () {\n await createUserWithEmailAndPassword(\n auth,\n this.register.email,\n this.register.password\n ).catch((error) => {\n console.log(error.code)\n console.log(error.message)\n })\n\n onAuthStateChanged(\n auth,\n (user) => {\n if (user) {\n const ref = doc(db, 'profile', user.uid)\n const document = {\n street: this.register.street\n }\n try {\n setDoc(ref, document)\n } catch (e) {\n alert('Error!')\n console.error(e.code)\n console.error(e.message)\n }\n }\n }\n )\n }\n }\n})\n</script>\n```\n\n```text\nrules_version = '2';\nservice cloud.firestore {\n match /databases/{database}/documents {\n match /{document=**} {\n allow read;\n allow write;\n }\n }\n}\n```\n\n```text\nuid\n```\n\n```text\nprofile\n```\n\n```text\nasync createUser () {\n await createUserWithEmailAndPassword(\n auth,\n this.register.email,\n this.register.password\n )\n .then((user) => {\n this.writeToFirestore(user)\n })\n .catch((error) => {\n console.log(error.code)\n console.log(error.message)\n })\n},\n\nasync writeToFirestore(user) {\n if (user) {\n const ref = doc(db, 'profile', user.id)\n const document = {\n street: this.register.street\n }\n try {\n setDoc(ref, document)\n } catch (e) {\n alert('Error!')\n console.error(e.code)\n console.error(e.message)\n }\n }\n},\n```\n\n========================================\n\nComments:\n- Thanks, it works. Little modification on my side I put `this.writeToFirestore(user)` inside `onAuthStateChanged` , just to make sure writing happens after user registered in the backend.","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":223,"estimatedTokens":1071}}596{"id":"stack-71824404","source":"stackoverflow","questionId":71824404,"title":"Add a tag in Nuxt","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: Add a tag in Nuxt\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI would like to add `Please enable your javascript` in the developer mode.\n\nI tried to configure it in the `nuxt.config.js` file but it didn't worked.\n\n========================================\n\nCode:\n```text\n<body><noscript><h1>Please enable your javascript<h1></noscript></body>\n```\n\n```text\nnuxt.config.js\n```\n\n```html\n<!DOCTYPE html>\n<html {{ HTML_ATTRS }}>\n <head {{ HEAD_ATTRS }}>\n {{ HEAD }}\n </head>\n <body {{ BODY_ATTRS }}>\n <noscript>Your browser does not support JavaScript!</noscript>\n {{ APP }}\n </body>\n</html>\n```\n\n```text\nnoscript\n```\n\n```text\napp.html\n```\n\n```text\nssr: true\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":44,"estimatedTokens":174}}597{"id":"stack-56174337","source":"stackoverflow","questionId":56174337,"title":"how to access \"this\" in props validator","tags":["javascript","vue.js","nuxt.js"],"text":"Title: how to access \"this\" in props validator\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm working on a project using nuxt.js, I'm injecting a function in the context of the application as recommended in the official documentation\n\n**https://nuxtjs.org/guide/plugins/#inject-in-root-amp-context**\n\nbut when I try to call the function inside a props validation I get an error\n\n`/plugins/check-props.js`\n\n```\nimport Vue from 'vue'\n\nVue.prototype.$checkProps = function(value, arr) {\n return arr.indexOf(value) !== -1\n}\n```\n\nin a component vue\n\n```\nexport default {\n props: {\n color: {\n type: String,\n validator: function (value, context) {\n this.$checkProps(value, ['success', 'danger'])\n }\n }\n}\n```\n\n`ERROR:` Cannot read property '$checkProps' of undefined\n\nDoes anyone know how I can access \"this\" within validation?\n\nthanks in advance!\n\n========================================\n\nTop Answer:\nFrom the doc:\n\nprops are validated before a component instance is created, so\ninstance properties (e.g. data, computed, etc) will not be available\ninside default or validator functions\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\n\nVue.prototype.$checkProps = function(value, arr) {\n return arr.indexOf(value) !== -1\n}\n```\n\n```text\nexport default {\n props: {\n color: {\n type: String,\n validator: function (value, context) {\n this.$checkProps(value, ['success', 'danger'])\n }\n }\n}\n```\n\n```text\n/plugins/check-props.js\n```\n\n```text\nERROR:\n```\n\n```text\n// array.helpers.js\nexport function containsValue(arr, val) {\n return arr.indexOf(value) !== -1\n}\n\n// component\nimport { containsValue } from 'path/to/helpers/array.helpers';\nprops: {\n foo: {\n //\n validator(value) {\n return containsValue(['foo', 'bar'], value);\n }\n }\n}\n```\n\n```text\n// component\nprops: {\n color: {\n //\n validator(value) {\n return ['success', 'danger'].includes(value);\n }\n }\n}\n```\n\n```text\nthis\n```\n\n```text\nVue.prototype\n```\n\n```text\n$checkProps\n```\n\n```text\nArray.prototype.includes\n```\n\n```text\n{\n validator: (value: any): boolean => {\n return window.$nuxt.$te(value);\n }\n}\n```\n\n```text\n{\n validator: (value: any): boolean => {\n return window.$nuxt.$checkProps(value, ['success', 'danger']);\n }\n}\n```\n\n```text\nfunction checkProps(value: any, arr: string[]): boolean {\n return arr.indexOf(value) !== -1\n}\n\nconst $checkProps: Plugin = (_context: Context, inject: Inject) => {\n inject('checkProps', checkProps);\n};\n\nexport default $checkProps;\n```\n\n```text\n{\n plugins: [{ src: 'plugins/check-props.js', ssr: true }]\n}\n```\n\n```text\nnuxt\n```\n\n```text\nwindow\n```\n\n```text\ni18n\n```\n\n```text\nnuxt\n```\n\n```text\nplugins/check-props.js\n```\n\n```text\n.ts\n```\n\n========================================\n\nComments:\n- As a general comment, the Nuxt docs weren't all that good the last time I checked, don't take their recommendations at face value. In fairness, it's been a bit since I last worked on a project with it, but I doubt they've had a major overhaul.\n- the problem with that is that every time I write a validator, I'll have to import the `{containsValue} from 'array.helpers.js'`?\n- Yes, you'll need to import it multiple times. However if you are planning to reuse this logic in multiple components, for example a group of components that receive a color prop `['success', 'danger']`, you use a `mixin` to extend the components you want to apply these props to. Check the documentation on mixins\n- in fact I would like to access this function from any component, not just a group of components, I would prefer to register the function globally and so that I do not have to import it so I can use some idea?\n- register a function globally in nuxt.js and access within a props validation\n- In general, I avoid using global functions, specially for helpers like this. ES6 has functions that you can use out of the box to achieve this `['foo', 'bar'].includes(value)`\n- Thanks for the support, great answers!","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":195,"estimatedTokens":1010}}598{"id":"stack-75650321","source":"stackoverflow","questionId":75650321,"title":"Nuxt 3 - 404 Page Not Found Error and H3Error Page not found","tags":["nuxt.js"],"text":"Title: Nuxt 3 - 404 Page Not Found Error and H3Error Page not found\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhenever a user visits a non existing page I get in the logs the following error which I would rather not log for every not found page.\n\n[nuxt] error caught during app initialization H3Error: Page not found: /.git/config\nat createError (file:///var/www/site1/.output/server/node_modules/h3/dist/index.mjs:128:15)\nat file:///var/www/site1/.nuxt/dist/server/server.mjs:2154:47\nat triggerAfterEach (file:///var/www/site1/.output/server/node_modules/vue-router/dist/vue-router.mjs:3306:13)\nat file:///var/www/site1/.output/server/node_modules/vue-router/dist/vue-router.mjs:3209:13\nat processTicksAndRejections (node:internal/process/task_queues:96:5)\nat file:///var/www/site1/.nuxt/dist/server/server.mjs:2170:7\nat createNuxtAppServer (file:///var/www/site1/.nuxt/dist/server/server.mjs:19902:7)\nat Object.renderToString (file:///var/www/site1/.output/server/node_modules/vue-bundle-renderer/dist/runtime.mjs:172:19)\nat file:///var/www/site1/node_modules/nuxt/dist/core/runtime/nitro/renderer.mjs:128:21\nat file:///var/www/site1/node_modules/nitropack/dist/runtime/renderer.mjs:12:22 {\nstatusCode: 404,\nfatal: false,\nunhandled: false,\nstatusMessage: 'Page not found: /.git/config',\n__nuxt_error: true\n}\n\nI tried to create a plugin in plugins folder named errorhandler.ts with this code but its not logging anything\n\n```\nexport default defineNuxtPlugin((nuxtApp) => {\n nuxtApp.vueApp.config.errorHandler = (error, context) => {\n console.log(error);\n console.log(context);\n };\n});\n```\n\nThis is an example https://stackblitz.com/edit/nuxt-starter-q2rvlp?file=plugins%2Ferrorhandler.ts.\n\nCan anyone some thoughts about handling not found error in Nuxt 3 and even creating a custom 404 page?\n\nThank you in advance!!!\n\n========================================\n\nTop Answer:\nIn Nuxt 3, you can create a catch-all route ([...path].vue) to handle 404 errors explicitly.\n\nCreate the Catch-All Route:\n\nCreate a file named `[...path].vue` in the pages directory:\n\n```\ntouch pages/[...path].vue\n```\n\nAdd Your Custom 404 Page Content:\n\n```\n\n \n \n\n### 404\n\n \n Oops! The page you’re looking for doesn’t exist.\n \n\n \n Go Back to Home\n \n \n\nexport default {\n name: \"NotFoundPage\",\n};\n\n```\n\nHow It Works:\n\nThe `[...path].vue` file catches all unmatched routes and serves as your custom 404 page.\n\nDocumentation. This is the most native solution for Nuxt 3 that I could find. I hope it helps!\n\n========================================\n\nCode:\n```text\nexport default defineNuxtPlugin((nuxtApp) => {\n nuxtApp.vueApp.config.errorHandler = (error, context) => {\n console.log(error);\n console.log(context);\n };\n});\n```\n\n```text\nimport type { H3Error, H3Event } from 'h3'\n\nexport default defineNitroPlugin((nitroApp) => {\n const h3OnError = nitroApp.h3App.options.onError;\n nitroApp.h3App.options.onError = (error : Error, event : H3Event) => {\n let h3error : H3Error = error as H3Error;\n \n if(h3error?.statusCode === 404)\n {\n h3error.unhandled = false;\n }\n\n if(h3OnError !== undefined)\n {\n return h3OnError(error, event);\n }\n return;\n };\n})\n```\n\n```text\n~/error.vue\n```\n\n```text\nerror\n```\n\n```text\nconst { id } = useRoute().params\n\nconst { data: student, error } = await useMyFetch<IStudentApplicationDetail>(\n `/api/member-student-application/${id}`\n)\n\nif (error.value) {\n throw createError({ statusCode: 404, statusMessage: 'Page Not Found' })\n}\n```\n\n```text\nexport default defineNuxtPlugin((nuxtApp) => {\n nuxtApp.vueApp.config.errorHandler = (error, context) => {\n console.log('🚀 ~ file: error.ts:6 ~ defineNuxtPlugin ~ context:', context)\n console.log('🚀 ~ file: error.ts:6 ~ defineNuxtPlugin ~ error:', error)\n }\n})\n```\n\n```text\n🚀 ~ file: error.ts:6 ~ defineNuxtPlugin ~ context: {} 23:28:22\n🚀 ~ file: error.ts:6 ~ defineNuxtPlugin ~ error: H3Error: Page Not Found 23:28:22\n at Module.createError (file:///Users/januarfonti/Code/Clearview/asifa/asifa-member-fe/node_modules/h3/dist/index.mjs:128:15)\n at Module.createError (/Users/januarfonti/Code/Clearview/asifa/asifa-member-fe/node_modules/nuxt/dist/app/composables/error.js:37:38)\n at setup (/Users/januarfonti/Code/Clearview/asifa/asifa-member-fe/pages/admin/members/student-applications/view/[id].vue:43:35)\n at processTicksAndRejections (node:internal/process/task_queues:96:5) {\n statusCode: 404,\n fatal: false,\n unhandled: false,\n statusMessage: 'Page Not Found',\n __nuxt_error: true\n}\n```\n\n```text\ntouch pages/[...path].vue\n```\n\n```text\n<template>\n <div>\n <h1>404</h1>\n <p>\n Oops! The page you’re looking for doesn’t exist.\n </p>\n <nuxt-link to=\"/\">\n Go Back to Home\n </nuxt-link>\n </div>\n</template>\n\n<script>\nexport default {\n name: \"NotFoundPage\",\n};\n</script>\n```\n\n```text\n[...path].vue\n```\n\n```text\n[...path].vue\n```\n\n========================================\n\nComments:\n- Thank you for your answer still in logs H3Error is not handled any thoughts on that? Also I would like to ask you If you have any idea why the plugin is not logging anything?\n- I don't think we can hide the H3errors that are showing on the terminal log as I think it is an error response which we can use it dynamically to render on the page based on the response given. e.g. If you want to dynamically show what type of statusCode the error type is, you can use the `error.status` from the `error` object props. Hope that make sense. I also updated the `error.vue` file Check it out and my explanation will make more sense. As for the plugin, have you tried using the `app:error`? Visit the stackblitz example I sent above and check the `plugins` folder.\n- Here is the full error handling example from Nuxt. nuxt.com/docs/examples/app/error-handling\n- **Edit on my first comment**. On stackblitz, the h3Error will display but when you use vs code, the H3Error will not show anymore. I tried it with the `nuxtApp.hook('app:error')`.\n- Your stackblitz fork gives a 503 error!! It this how it should be?\n- Thank you for your answer! I added the error.ts and error.vue in my project. But the H3Error is still in the logs, at least when running with npm run dev.\n- Thank you! That helped fixing the error in the console.","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":205,"estimatedTokens":1602}}599{"id":"stack-74082215","source":"stackoverflow","questionId":74082215,"title":"Nuxt 3 files not visible in the directory structure","tags":["vue.js","nuxt.js","nuxt3.js"],"text":"Title: Nuxt 3 files not visible in the directory structure\nTags: vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI recently started learning NuxtJs and create a nuxt app using the nuxt3 template. The code i used to generate the starter project is\n\nnpx nuxi init nuxt-app\n\nHowever the the terminal shows that the app has been created and the dev server also starts displaying the Nuxt3 welcome page. But when i load the directory in vs code the folders like pages,store and components are not visible as seen in the screenshot below .\n\nhttps://i.sstatic.net/D5vut.png\n\n========================================\n\nTop Answer:\nThis behavior is a year old already: Some of the directories are missing when I'm trying to create a new Nuxt js project\n\nThe idea is to have something minimal where you could then add all the needed directories.\n\nBenefit being that if you don't use any `pages`, the final bundle will be smaller (no need to being in Vue router for example). Same for the store (no need to import Vuex/Pinia), server part etc...\n\nIt's less of a \"you have everything from the start\" and more of a \"pick what you like the most\"!\n\n========================================\n\nCode:\n```text\n<NuxtWelcome />\n```\n\n```text\nnode_modules\n```\n\n```text\n<NuxtPages/>\n```\n\n```text\npages\n```\n\n```text\n<script>\n```\n\n```text\n<NuxtPages />\n```\n\n```text\nIndex.vue\n```\n\n```text\n/\n```\n\n```text\nAbout.vue\n```\n\n```text\n/about\n```\n\n```text\npages\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":70,"estimatedTokens":360}}600{"id":"stack-54507001","source":"stackoverflow","questionId":54507001,"title":"Group pages without affecting the router - Nuxt.js","tags":["vuejs2","nuxt.js"],"text":"Title: Group pages without affecting the router - Nuxt.js\nTags: vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using Nuxt to create my application and I have a group of pages that are related in a way. \n\nSo I will simplify things a bit but my current structure looks like this\n\n```\n/pages\n /login\n /registration\n /forgot-password\n /resend-confirmation-email\n .\n .\n .\n```\n\nThis folder structure is creating `/login`, `/registration`, `/forgot-password`, `/resend-confirmation-email` routes, which is cool.\n\nSo, in a way I can group first four pages to a group and name it `authorization`.\n\nIdeally new folder structure should look like\n\n```\n/pages\n /authorization\n /login\n /registration\n /forgot-password\n /resend-confirmation-email\n .\n .\n .\n```\n\nHowever what I would like is for the router to not get messed up, I would very much like for those routes to remain the way they were. \n\nIs that possible?\n\n========================================\n\nTop Answer:\nStarting with Nuxt v3.13.0, you can use the new feature called `Route Groups` for naming directories. This allows you to organize your routes using parentheses/brackets without affecting the path.\n\nFor example:\n\n```\n-| pages/\n---| index.vue\n---| (authorization)/\n-----| login\n-----| registration\n```\n\nThis will produce `/`, `/login` and `/registration` pages in your application.\n\nNuxt documentation about Route Groups.\n\n========================================\n\nCode:\n```text\n/pages\n /login\n /registration\n /forgot-password\n /resend-confirmation-email\n .\n .\n .\n```\n\n```text\n/pages\n /authorization\n /login\n /registration\n /forgot-password\n /resend-confirmation-email\n .\n .\n .\n```\n\n```text\n/login\n```\n\n```text\n/registration\n```\n\n```text\n/forgot-password\n```\n\n```text\n/resend-confirmation-email\n```\n\n```text\nauthorization\n```\n\n```text\nrouter: {\n extendRoutes(nuxtRoutes) {\n nuxtRoutes.map(route => {\n route.path = route.path.replace('/authorization', '');\n route.name = route.name.replace('authorization-', '');\n\n return route;\n });\n },\n ....\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n<router>\n path: /posts\n</router>\n```\n\n```text\npages/auth/\n login.vue\n logout.vue\n register.vue\n forgot.vue\n //etc...\n\n index.vue // not necessary, but a nice convenience page\n```\n\n```text\nwww.website.com/auth/login\nwww.website.com/auth/logout\nwww.website.com/auth/register\nwww.website.com/auth/forgot\n\nwww.website.com/auth // accessible if index.vue exists; maybe a nice convenience page showing auth state and shortcuts\n```\n\n```text\ndefinePageMeta({\n alias: '/login'\n})\n```\n\n```text\ndefinePageMeta\n```\n\n```text\nwww.website.com/login\n```\n\n```text\npages/auth/login.vue\n```\n\n```text\nwww.website.com/auth/login\n```\n\n```text\nwww.website.com/login\n```\n\n```text\n-| pages/\n---| index.vue\n---| (authorization)/\n-----| login\n-----| registration\n```\n\n```text\nRoute Groups\n```\n\n```text\n/\n```\n\n```text\n/login\n```\n\n```text\n/registration\n```\n\n========================================\n\nComments:\n- What about `alias` and `redirect` options? `alias` will better fit here - router.vuejs.org/guide/essentials/…\n- uhm, not sure how will this help me... If I was using vue-router directly I would have known how to do this. But nuxt is creating router file based on directory structure and I'd like to override that....\n- I will try this. I am using nuxt-i18n module as well in order to translate my route names (for the sake of SEO) so I will see how this gets along with it..","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":207,"estimatedTokens":888}}601{"id":"stack-69821787","source":"stackoverflow","questionId":69821787,"title":"Navigating with nuxt-link to anchor/hash on a different page is not working","tags":["vue.js","vuejs2","nuxt.js","vue-router"],"text":"Title: Navigating with nuxt-link to anchor/hash on a different page is not working\nTags: vue.js, vuejs2, nuxt.js, vue-router\nSource: Stack Overflow\n\nQuestion:\nI want to navigate to a specific section of a page from another page. So I added the scrollBehavior function in router object in nuxt.config.js file like this:\n\n```\nrouter: {\n scrollBehavior(to) {\n if (to.hash) {\n return {\n selector: to.hash,\n behavior: \"smooth\"\n };\n }\n }\n }\n```\n\nMy 'pages' directory tree is like this:\n\n```\npages/\n index.vue\n parent.vue\n random.vue\n```\n\nIn default.vue of 'layouts' directory I wrote the navbar:\n\n```\nParent One\nParent Two\n```\n\nInside parent.vue I have two sections:\n\n```\n\n \n\n### Parent One\n\n ...\n \n\n \n\n### Parent Two\n\n ...\n \n\n```\n\nNow, The problem is When I click the 'parent two' button from random.vue file it doesn't work. but when I am in parent.vue file and click the button it scrolls to the second section. But I want to navigate to the second section from random.vue page. If I write the exact code in a vue project then it works fine but doesn't work in nuxt project. But I need to do it in my Nuxt project.\n\n========================================\n\nTop Answer:\nI was able to fix it by using this module: https://nuxt.com/modules/nuxt-anchorscroll along with replacing `` with ``\n\n========================================\n\nCode:\n```js\nrouter: {\n scrollBehavior(to) {\n if (to.hash) {\n return {\n selector: to.hash,\n behavior: \"smooth\"\n };\n }\n }\n }\n```\n\n```text\npages/\n index.vue\n parent.vue\n random.vue\n```\n\n```html\n<button @click=\"$router.push({ name: 'parent' })\">Parent One</button>\n<button @click=\"$router.push({ name: 'parent', hash: '#sec2' })\">Parent Two</button>\n```\n\n```html\n<div class=\"sec-1\" id=\"sec1\">\n <h1>Parent One</h1>\n <p>...\n </p>\n</div>\n<div class=\"sec-2\" id=\"sec2\">\n <h1>Parent Two</h1>\n <p>...\n </p>\n</div>\n```\n\n```js\nexport default function(to, from, savedPosition) {\n console.log(\"this is the hash\", to.hash)\n return new Promise((resolve, reject) => {\n if (to.hash) {\n setTimeout(() => {\n resolve({\n selector: to.hash,\n behavior: \"smooth\"\n })\n }, 10)\n }\n })\n}\n```\n\n```text\n~/app/router.scrollBehavior.js\n```\n\n```text\n<RouterView/>\n```\n\n```text\n<NuxtPage/>\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":131,"estimatedTokens":581}}602{"id":"stack-55377977","source":"stackoverflow","questionId":55377977,"title":"Trying to set Vue Meta page title using string + variable","tags":["javascript","vue.js","nuxt.js","vue-meta"],"text":"Title: Trying to set Vue Meta page title using string + variable\nTags: javascript, vue.js, nuxt.js, vue-meta\nSource: Stack Overflow\n\nQuestion:\nI'm using Vue Meta as part of a blog application within a project using Nuxt JS 2.4.5\n\nI'm having some trouble trying to set the title + a variable from `data ()` and I'm not sure what I'm missing\n\nI've tried multiple attempts at getting it to work, moving code around, using `this` setting it manually, nothing seems to work...\n\n```\n\nimport BlogsFromJson from '~/static/articles/blogs.json';\n\nexport default {\n head: {\n title: 'My Website: Blog: ' + this.myBlogTitle, // or something else\n meta: [\n { hid: 'description', name: 'description', content: 'Read the latest news and articles from Flex Repay UK.' }\n ]\n },\n data () {\n return {\n title: this.$route.params.title,\n blog: BlogsFromJson,\n myBlogTitle: 'some title'\n }\n }\n}\n\n```\n\nI've tried setting a variable within `data ()` and using it statically.\n\nDoing this should give me `My Website: Blog: some title`\n\nWhat could I be missing here?\n\n========================================\n\nTop Answer:\nInstead of defining metaInfo as an object, define it as a function and access this as usual:\n\n Post.vue:\n\n```\n\n \n \n\n### {{{ title }}}\n\n \n\n```\n\nyour script\n\n```\n\n export default {\n name: 'post',\n props: ['title'],\n data () {\n return {\n description: 'A blog post about some stuff'\n }\n },\n metaInfo () {\n return {\n title: this.title,\n meta: [\n { vmid: 'description', name: 'description', content: this.description }\n ]\n }\n }\n }\n\n```\n\n PostContainer.vue:\n\n```\n\n \n \n \n\n import Post from './Post.vue'\n\n export default {\n name: 'post-container',\n components: { Post },\n data () {\n return {\n title: 'Example blog post'\n }\n }\n }\n\n```\n\n========================================\n\nCode:\n```text\n<script>\nimport BlogsFromJson from '~/static/articles/blogs.json';\n\nexport default {\n head: {\n title: 'My Website: Blog: ' + this.myBlogTitle, // or something else\n meta: [\n { hid: 'description', name: 'description', content: 'Read the latest news and articles from Flex Repay UK.' }\n ]\n },\n data () {\n return {\n title: this.$route.params.title,\n blog: BlogsFromJson,\n myBlogTitle: 'some title'\n }\n }\n}\n</script>\n```\n\n```text\ndata ()\n```\n\n```text\nthis\n```\n\n```text\ndata ()\n```\n\n```text\nMy Website: Blog: some title\n```\n\n```text\nhead: {\n ...\n},\n```\n\n```text\nhead () {\n return {\n ...\n }\n}\n```\n\n```text\n<template>\n <div>\n <h1>{{{ title }}}</h1>\n </div>\n</template>\n```\n\n```text\n<script>\n export default {\n name: 'post',\n props: ['title'],\n data () {\n return {\n description: 'A blog post about some stuff'\n }\n },\n metaInfo () {\n return {\n title: this.title,\n meta: [\n { vmid: 'description', name: 'description', content: this.description }\n ]\n }\n }\n }\n</script>\n```\n\n```text\n<template>\n <div>\n <post :title=\"title\"></post>\n </div>\n</template>\n\n<script>\n import Post from './Post.vue'\n\n export default {\n name: 'post-container',\n components: { Post },\n data () {\n return {\n title: 'Example blog post'\n }\n }\n }\n</script>\n```\n\n```text\nmetaInfo() {\n return {\n title: this.pageTitle,\n }\n }\n```\n\n========================================\n\nComments:\n- I'm trying to do: `title: 'Flex Repay UK: Blog' + this.blogTitle` - this is what I need for this project to work within `data ()`\n- Please provide more than just code as an answer. Instead, an explanation of the code and a breakdown of why it answers the question is most beneficial.","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":223,"estimatedTokens":898}}603{"id":"stack-77063035","source":"stackoverflow","questionId":77063035,"title":"WARN [nuxt] Two component files resolving","tags":["nuxt.js","nuxt3.js","nuxt-content"],"text":"Title: WARN [nuxt] Two component files resolving\nTags: nuxt.js, nuxt3.js, nuxt-content\nSource: Stack Overflow\n\nQuestion:\nWARN [nuxt] Two component files resolving to the same name ProseCode:\n\n- ./node_modules/@nuxtjs/mdc/dist/runtime/components/prose/ProseCode.vue\n\n- ./node_modules/@nuxt/content/dist/runtime/components/Prose/ProseCode.vue\n\nWARN [nuxt] Two component files resolving to the same name ProsePre:\n\n- ./node_modules/@nuxtjs/mdc/dist/runtime/components/prose/ProsePre.vue\n\n- ./node_modules/@nuxt/content/dist/runtime/components/Prose/ProsePre.vue\n\nwarning after updated nuxt 3 -> 3.7 & nuxt/content 2.4 -> 2.8\n\nhow can this be fixed?\nthanks\n\n========================================\n\nTop Answer:\nThat is likely related to this issue: https://github.com/nuxt/content/issues/2266 Nuxt typecheck is broken with nuxt/content@2.8.0 )","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":26,"estimatedTokens":210}}604{"id":"stack-77270727","source":"stackoverflow","questionId":77270727,"title":"How to reinitiate/resend a request with $fetch like Axios?","tags":["nuxt.js"],"text":"Title: How to reinitiate/resend a request with $fetch like Axios?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a onResponseError interceptor in which I would like to resend the original request after updating its headers with a new valid token. With Axios this was possible like this:\n\n```\nconst originalRequestConfig = error.config;\n// [...] Update the headers\nreturn $axios.request(originalRequestConfig);\n```\n\nHow do I achieve this with $fetch?\n\nI want to:\n\n- Send a request\n\n- When I get an error code 401, get another token\n\n- Retry the very same request\n\nThis should not be an unusual scenario 🤔\n\n========================================\n\nCode:\n```text\nconst originalRequestConfig = error.config;\n// [...] Update the headers\nreturn $axios.request(originalRequestConfig);\n```\n\n```ts\n// USAGE\n<script lang=\"ts\" setup>\nconst { data, pending, error, refresh } = useFetch('/pages', {})\n</script>\n\n// @/composables/useCustomFetch.ts\nimport type { UseFetchOptions } from 'nuxt/app'\nimport { defu } from 'defu'\n\nexport function useCustomFetch<T> (url: string, options: UseFetchOptions<T> = {}) {\n const config = useRuntimeConfig()\n const { isSignedIn, getToken, setToken } = useAuthStore()\n\n const defaults: UseFetchOptions<T> = {\n baseURL: config.public.apiBaseUrl,\n key: url,\n server: false,\n retry: 1,\n retryStatusCodes: [401],\n retryDelay: 500, // can safely delete this\n\n onRequest({ options }) {\n options.headers = isSignedIn\n ? { Authorization: `Bearer ${getToken()}` } // send token\n : {}\n },\n\n async onResponseError({ response, options }) {\n if (response.status === 401) {\n await useFetch('/auth/refresh', {\n baseURL: config.public.apiBaseUrl,\n method: 'POST',\n server: false,\n credentials: 'include',\n\n onResponse({ response }) {\n setToken(response._data.token) // store token\n },\n },\n )\n }\n }\n }\n\n const params = defu(options, defaults)\n\n return useFetch(url, params)\n }\n```\n\n========================================\n\nComments:\n- While this sounds great and probably answers the question, please note it's wrong way of using `useFetch` as per Nuxt core team member video explaining exactly this youtube.com/watch?v=njsGVmcWviY. Sounds like you should use `$fetch` when doing refresh.","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":89,"estimatedTokens":617}}605{"id":"stack-61700515","source":"stackoverflow","questionId":61700515,"title":"Access to this.$apollo from Vuex store with vue-apollo in NUXT?","tags":["vue.js","vuex","nuxt.js","apollo-client","vue-apollo"],"text":"Title: Access to this.$apollo from Vuex store with vue-apollo in NUXT?\nTags: vue.js, vuex, nuxt.js, apollo-client, vue-apollo\nSource: Stack Overflow\n\nQuestion:\nI want to store the user that comes from the login on an action in the vuex store. But there is no access to `this.$apollo`.\n\n```\nexport const actions = {\n UPSERT_USER({ commit }, { authUser, claims }) {\n this.$apollo\n .mutate({\n mutation: UPSERT_USER_MUTATION,\n variables: {\n id: user.uid,\n email: user.email,\n name: user.name,\n picture: user.picture,\n },\n })\n }\n```\n\nThanks!\n\n========================================\n\nTop Answer:\nBecause I inject apolloProvider in my nuxt apollo plugin using,\n\n```\ninject(\"apollo\", apolloProvider);\n```\n\nThen in my case I access it using,\n\n```\nexport default {\n actions: {\n foo (store, payload) {\n let apolloClient = this.$apollo.defaultClient\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nexport const actions = {\n UPSERT_USER({ commit }, { authUser, claims }) {\n this.$apollo\n .mutate({\n mutation: UPSERT_USER_MUTATION,\n variables: {\n id: user.uid,\n email: user.email,\n name: user.name,\n picture: user.picture,\n },\n })\n }\n```\n\n```text\nthis.$apollo\n```\n\n```text\nexport default {\n actions: {\n foo (store, payload) {\n let client = this.app.apolloProvider.defaultClient\n }\n }\n}\n```\n\n```text\ninject(\"apollo\", apolloProvider);\n```\n\n```text\nexport default {\n actions: {\n foo (store, payload) {\n let apolloClient = this.$apollo.defaultClient\n }\n }\n}\n```\n\n========================================\n\nComments:\n- Hi, thanks for the answer, it works in this way. The problem is that when the mutation is called, onUserChange, `this.app.apolloProvider` is yet undefined. I fixed it with a sleep of 1 second... but I don't think that is a good idea. Do you know how to wait for apolloProvider to be ready on the store? then execute the mutate()?\n- Hmm yes sleeping for a second is not a good idea. Hard to say, but I am pretty sure you are not the first one dealing with apollo in store. Try to search for that a bit, probably your solution is somewhere out there waiting for you to find. I don't know honestly right now ;(\n- yes, thank you. I am using the Firebase Nuxt module, which calls an action when the user is logged in, but at the time the apollo provider is not yet ready in the store.","metadata":{"transformedAt":"2026-08-18T18:33:07.880Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":99,"estimatedTokens":606}}606{"id":"stack-77395749","source":"stackoverflow","questionId":77395749,"title":"Vue Ref nolonger reactive after being returned from composable","tags":["vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: Vue Ref nolonger reactive after being returned from composable\nTags: vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am working with Nuxt 3 composition API using the Vue 3 script setup syntactic sugar.\n\nI have an issue where refs from my composable isn't reactive once it has been returned to a component. Watching the value has no effect.\n\nTake note that I am using VueUse to create different instances of the filedialog (useFileDialog).\n\n```\nimport { useFileDialog } from '@vueuse/core'\nimport { ref as storageRef, getStorage, listAll, getDownloadURL, deleteObject } from 'firebase/storage'\nimport { useStorageFile } from 'vuefire'\nimport { ref, computed, watch } from 'vue'\n\nexport const useFileUpload = (props) => {\n const storage = getStorage();\n const filename = ref();\n const fileRef = ref(null);\n const selectedImages = ref([]);\n const images = ref({});\n const imagePreviews = computed(() => {\n if (images.value) {\n return Array.from(images.value).map(file => URL.createObjectURL(file));\n }\n return [];\n })\n\n const {\n url,\n uploadTask,\n upload,\n } = useStorageFile(fileRef)\n\n const { files, open } = useFileDialog()\n const { open: openMaterialer, files: materialerFiles } = useFileDialog();\n const { open: openPlantegning, files: plantegningFiles } = useFileDialog();\n\n watch(files, (newFiles) => {\n if (newFiles.length > 0) {\n const fileType = newFiles[0].type.split('/')[0]\n if (fileType === 'image') {\n images.value = newFiles\n }\n else return\n }\n })\n\n const uploadFile = async () => {\n// Some upload logic here\n}\n \n\n watchEffect(() => {\n // Confirms reactivity in composable\n console.log('materialerFiles in upload:', materialerFiles.value);\n });\n\n return {\n imagePreviews,\n files,\n materialerFiles,\n plantegningFiles,\n uploadTask,\n open,\n openMaterialer,\n openPlantegning,\n uploadFile,\n };\n};\n```\n\nNow in my component i use the composable (remember that the composable is auto imported)\n\n```\n// files\n const { files, materialerFiles, plantegningFiles } = useFileUpload()\n \n // Watch for changes to materialerFiles\n watch(materialerFiles, (newMaterialerFiles) => {\n console.log('changed')\n userInput.value = {\n ...userInput.value,\n materialerFiles: newMaterialerFiles,\n };\n });\n```\n\nThis should log 'changed' to the console from the component. But nothing happens.\n\nHave i misunderstood something or is this a known issue. Any workarounds or suggestions?\n\nI expect to log the files which should materilaerFiles should contain.\n\n**Steps to reproduce:**\n\n- Create a composable in the \"composable\" directory\n\n- Import useFileDialog from vueUse and ref,watch, computed from vue\n\n- Inside the composable create 3 instances of the fileDialog\n\n- Return the reactive file values from the composable\n\n- in a component deconstruct the composable const {returned values here} = useYourComposable()\n\n- Watch for changes in one or more of the returned values\n\n========================================\n\nTop Answer:\nCurrently you are setting a ref in userInput.value.materialerFiles, not the value of newMaterialerFiles ref.\n\nTry update you watch by setting userInput.value using the value of materialerFiles ref like this:\n\n```\n// files\nconst { files, materialerFiles, plantegningFiles } = useFileUpload()\n\n// Watch for changes to materialerFiles\nwatch(materialerFiles, (newMaterialerFiles) => {\n console.log('changed')\n userInput.value = {\n ...userInput.value,\n materialerFiles: newMaterialerFiles.value,\n };\n});\n```\n\n========================================\n\nCode:\n```text\nimport { useFileDialog } from '@vueuse/core'\nimport { ref as storageRef, getStorage, listAll, getDownloadURL, deleteObject } from 'firebase/storage'\nimport { useStorageFile } from 'vuefire'\nimport { ref, computed, watch } from 'vue'\n\nexport const useFileUpload = (props) => {\n const storage = getStorage();\n const filename = ref();\n const fileRef = ref(null);\n const selectedImages = ref([]);\n const images = ref({});\n const imagePreviews = computed(() => {\n if (images.value) {\n return Array.from(images.value).map(file => URL.createObjectURL(file));\n }\n return [];\n })\n\n const {\n url,\n uploadTask,\n upload,\n } = useStorageFile(fileRef)\n\n const { files, open } = useFileDialog()\n const { open: openMaterialer, files: materialerFiles } = useFileDialog();\n const { open: openPlantegning, files: plantegningFiles } = useFileDialog();\n\n watch(files, (newFiles) => {\n if (newFiles.length > 0) {\n const fileType = newFiles[0].type.split('/')[0]\n if (fileType === 'image') {\n images.value = newFiles\n }\n else return\n }\n })\n\n const uploadFile = async () => {\n// Some upload logic here\n}\n \n\n watchEffect(() => {\n // Confirms reactivity in composable\n console.log('materialerFiles in upload:', materialerFiles.value);\n });\n\n return {\n imagePreviews,\n files,\n materialerFiles,\n plantegningFiles,\n uploadTask,\n open,\n openMaterialer,\n openPlantegning,\n uploadFile,\n };\n};\n```\n\n```text\n// files\n const { files, materialerFiles, plantegningFiles } = useFileUpload()\n \n // Watch for changes to materialerFiles\n watch(materialerFiles, (newMaterialerFiles) => {\n console.log('changed')\n userInput.value = {\n ...userInput.value,\n materialerFiles: newMaterialerFiles,\n };\n });\n```\n\n```text\n// files\nconst { files, materialerFiles, plantegningFiles } = useFileUpload()\n\n// Watch for changes to materialerFiles\nwatch(materialerFiles, (newMaterialerFiles) => {\n console.log('changed')\n userInput.value = {\n ...userInput.value,\n materialerFiles: newMaterialerFiles.value,\n };\n});\n```\n\n========================================\n\nComments:\n- Please, provide a way to reproduce, see stackoverflow.com/help/mcve . Probably something that is specific to autoimports. There's absolutely no difference if watch is called inside custom composable or outside it, it's just JS function without magical properties.\n- Explicitly importing the composable does not change the result.\n- Please, provide a demo. I expect that it won't be possible to reproduce with the provided steps for the reason mentioned above. Notice that the difference is that watchEffect runs immediately and watch doesn't. In case there was 'materialerFiles in upload' but not 'changed', that's why\n- There is no difference in behavior when switching watchEffect out with a normalt watch or the other way around. I get the same result. Working on the demo\n- As far as I can tell the issue lies with the composable from VueUse. All refs i create myself change reactively as expected. But specifically the values deconstructed from usefileDialog does not react to changes once imported in a component\n- The implementation is simple, i see no clue why this would be the case github.com/vueuse/vueuse/blob/main/packages/core/useFileDial‌​og/… . It may be the case where does watch and watchEffect are imported from. If `vue` package has been duped somewhere in the deps, it could be a problem, but I don't see how this would cause this exact behaviour. That you rely on autoimports adds additional points of failure.\n- I get what you're getting at but for that to work, the watch function would need to actually log 'changed' to the console. If it doesn't, where I'm setting the ref won't matter.\n- Or use module-level state in the composable, if it makes sense for it. AKA a \"singleton\" composable.\n- @DarrylNoakes do you have any examples of this? I had ran into a similar problem\n- @mjbates7 You simply hoist state variables out of the composable function to the composable's module's top-level. The way you initialize stuff does have to change a little, but otherwise that's about it. It's the poor man's store; if you are only managing a little state and don't need Pinia's other features, you can simply make a composable that returns a reactive object.","metadata":{"transformedAt":"2026-08-18T18:33:07.881Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":238,"estimatedTokens":2015}}607{"id":"stack-60536751","source":"stackoverflow","questionId":60536751,"title":"Nuxtjs dynamic routes doesn't work on page reload after deploying as a SPA on AWS Amplify console","tags":["amazon-web-services","vue.js","nuxt.js","aws-amplify","aws-amplify-cli"],"text":"Title: Nuxtjs dynamic routes doesn't work on page reload after deploying as a SPA on AWS Amplify console\nTags: amazon-web-services, vue.js, nuxt.js, aws-amplify, aws-amplify-cli\nSource: Stack Overflow\n\nQuestion:\nI have deployed my Nuxtjs app as SPA on AWS using AWS Amplify console. Now my website has some dynamic routes which redirects to 404 page when reloaded or opened in a new tab. I know that when we generate a static site using `nuxt generate` the routes should be using routes() in nuxt.config.js. But in SPA mode it should be working on page refresh or reload. Even in Angular when run in SPA mode dynamic routes work fine. Its so strange that the dynamic routes doesn't work when the website is run as a single page application.\n\nWhen used locally in production mode i.e `npm run build && npm run start` the routes work fine. But after deploying it to AWS Amplify it redirects to 404 page. What am I misssing here?\nHere's the Amplify.yml config i used \n\n```\nversion: 0.1\nfrontend:\n phases:\n preBuild:\n commands:\n - npm ci\n build:\n commands:\n - npm run build\n artifacts:\n # IMPORTANT - Please verify your build output directory\n baseDirectory: dist\n files:\n - '**/*'\n cache:\n paths:\n - node_modules/**/*\ntest:\n artifacts:\n baseDirectory: cypress\n configFilePath: '**/mochawesome.json'\n files:\n - '**/*.png'\n - '**/*.mp4'\n phases:\n```\n\n========================================\n\nTop Answer:\n@lupas helped me in nuxt discord. You just need to set as below\n\n1) On the Amplify console go to: Rewrites and redirects\n2) Delete the existing entry\n3) Add the following:\nSource Address: \nTarget address: /index.html\nType: 200 (Rewrite)\n\n========================================\n\nCode:\n```text\nversion: 0.1\nfrontend:\n phases:\n preBuild:\n commands:\n - npm ci\n build:\n commands:\n - npm run build\n artifacts:\n # IMPORTANT - Please verify your build output directory\n baseDirectory: dist\n files:\n - '**/*'\n cache:\n paths:\n - node_modules/**/*\ntest:\n artifacts:\n baseDirectory: cypress\n configFilePath: '**/mochawesome.json'\n files:\n - '**/*.png'\n - '**/*.mp4'\n phases:\n```\n\n```text\nnuxt generate\n```\n\n```text\nnpm run build && npm run start\n```\n\n```text\n</^[^.]+$|\\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf|map|json)$)([^.]+$)/>\n```\n\n```text\n/index.html\n```\n\n```text\n200 (Rewrite)\n```\n\n```text\nssr: false\n```\n\n========================================\n\nComments:\n- Could you please detail what you wrote in the source address please? I have the exact same issue with a dynamic route like `myWebsite.com/pending/243535`. I tried with `/pending/*` without success\n- In my case, same approach as @Pascal but just using `/pending/` did the trick","metadata":{"transformedAt":"2026-08-18T18:33:07.881Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":110,"estimatedTokens":685}}608{"id":"stack-56135568","source":"stackoverflow","questionId":56135568,"title":"Rendered HTML in bootstrap-vue table header","tags":["vue.js","nuxt.js","bootstrap-vue","vue-i18n"],"text":"Title: Rendered HTML in bootstrap-vue table header\nTags: vue.js, nuxt.js, bootstrap-vue, vue-i18n\nSource: Stack Overflow\n\nQuestion:\nI'm making a site that uses NuxtJS, Bootstrap Vue and vue-i18n.\n\nI have a table (`**`) that shows areas in square meters, and the header should display: sq m** in english, and **m2** (`m2`) in a translation.\n\nSo the header field label is drawn from the i18n locale JSON to the single file component's table header label. The string is drawn correctly, but the HTML part is not rendered, unfortunately, so what I see on the page is **`m2`**.\n\nHere's how I tried to solve it (examples are simplified - parts are deleted from them):\n\n**hu.json** (translation locale file)\n\n```\n{\n \"in_numbers\": {\n \"space\": \"m2\"\n }\n}\n```\n\n**tableComponentFile.vue** (single file component)\n\n```\n\n \n \n \n \n \n \n \n \n \n \n \n\nexport default {\n computed: {\n floors() {\n return [\n { space: 552.96 },\n { space: 796.27 }\n ]\n }\n },\n data() {\n return {\n tableHeader: [\n {\n key: 'space',\n label: this.$t('in_numbers.space'),\n sortable: false\n }\n ]\n }\n }\n}\n\n```\n\nSo, everything works fine, except that I cannot render the HTML from the locale json in the table header - so the table renders with the data in it, and in other components this `` technique works just fine.\n\nIt doesn't work if I try **m²**(`²`) or anything.\n\nThe problem is that `` doesn't seem to react to anything (actually I'm not sure it works) - but it should, as the documentation says (https://bootstrap-vue.js.org/docs/components/table#custom-data-rendering)\n\nAnybody see a way to render HTML in bootstrap-vue's table header?\n\n========================================\n\nTop Answer:\n**Updated answer (June 2020)**\n\nBoth VueJS and bootstrap-vue has changed since the question and the accepted answer was posted. It still not very clear in the bootstrap-vue docs, but you can accomplish the same result with:\n\n\r\n\r\n\n```\n\r\n \r\n \r\n \r\n \r\n // This has changed\r\n // Now you access data.field.label\r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\nexport default {\r\n computed: {\r\n floors() {\r\n return [\r\n { space: 552.96 },\r\n { space: 796.27 }\r\n ]\r\n }\r\n },\r\n data() {\r\n return {\r\n tableHeader: [\r\n {\r\n key: 'space',\r\n label: this.$t('in_numbers.space'),\r\n sortable: false\r\n }\r\n ]\r\n }\r\n }\r\n}\r\n\n```\n\n========================================\n\nCode:\n```text\n{\n \"in_numbers\": {\n \"space\": \"m<sup>2</sup>\"\n }\n}\n```\n\n```text\n<template>\n <b-container fluid>\n <b-row>\n <b-col cols=\"12\">\n <b-table\n :items=\"floors\"\n :fields=\"tableHeader\"\n />\n <template slot=\"HEAD_space\" slot-scope=\"data\">\n <span v-html=\"data.label\"></span>\n </template>\n </b-table>\n </b-col>\n </b-row>\n </b-container>\n</template>\n\n<script>\nexport default {\n computed: {\n floors() {\n return [\n { space: 552.96 },\n { space: 796.27 }\n ]\n }\n },\n data() {\n return {\n tableHeader: [\n {\n key: 'space',\n label: this.$t('in_numbers.space'),\n sortable: false\n }\n ]\n }\n }\n}\n</script>\n```\n\n```text\n<b-table>\n```\n\n```text\nm<sup>2</sup>\n```\n\n```text\nm<sup>2</sup>\n```\n\n```text\n<span v-html=\"$t('in_numbers.space')\"></span>\n```\n\n```text\n²\n```\n\n```text\n<template slot>\n```\n\n```text\n{\n \"in_numbers\": {\n \"space\": \"m<sup>2</sup>\"\n }\n}\n```\n\n```text\n<template>\n <b-container fluid>\n <b-row>\n <b-col cols=\"12\">\n <b-table\n :items=\"floors\"\n :fields=\"tableHeader\"\n >\n <template slot=\"HEAD_space\" slot-scope=\"data\">\n <span v-html=\"data.label\"></span>\n </template>\n </b-table>\n </b-col>\n </b-row>\n </b-container>\n</template>\n\n<script>\nexport default {\n computed: {\n floors() {\n return [\n { space: 552.96 },\n { space: 796.27 }\n ]\n }\n },\n data() {\n return {\n tableHeader: [\n {\n key: 'space',\n label: this.$t('in_numbers.space'),\n sortable: false\n }\n ]\n }\n }\n}\n</script>\n```\n\n```text\n<b-table>\n```\n\n```text\nHEAD_\n```\n\n```html\n<template>\n <b-container fluid>\n <b-row>\n <b-col cols=\"12\">\n <b-table\n :items=\"floors\"\n :fields=\"tableHeader\">\n <template v-slot:head(space)=\"data\"> // This has changed\n <span v-html=\"data.field.label\"></span> // Now you access data.field.label\n </template>\n </b-table>\n </b-col>\n </b-row>\n </b-container>\n</template>\n\n<script>\nexport default {\n computed: {\n floors() {\n return [\n { space: 552.96 },\n { space: 796.27 }\n ]\n }\n },\n data() {\n return {\n tableHeader: [\n {\n key: 'space',\n label: this.$t('in_numbers.space'),\n sortable: false\n }\n ]\n }\n }\n}\n</script>\n```\n\n========================================\n\nComments:\n- Would you be able to expand a little what you've done here? It would be greatly useful :)\n- @Adriano what are you interested in? **VueJS** and **bootstrap-vue** has changed a lot since I posted my original problem, so the answer here might not be correct anymore.\n- I'm having the same problem: in a `b-table` element I need to programmatically inject some dynamic data in the `th` of each column. Injecting data in the `HEAD_space` slot doesn't work for me.\n- If you post your problem here on StackOverflow with some code you tried, you can reference link that here in a comment - maybe I can look at it.\n- This solution worked for me, but as Adriano said, unfortunately, I find hardcoding the keys after \"HEAD_\" far from ideal.\n- Here is an alternative for people looking for a more dynamical solution using a `v-for` (i.e. looping through all the fields without having to explicitely write/hard-code a given one): stackoverflow.com/a/66360753/7894940\n- thanks, this should be the accepted answer! The docs actually do mention this but I only found this after seeing your post. bootstrap-vue.org/docs/components/…","metadata":{"transformedAt":"2026-08-18T18:33:07.881Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":310,"estimatedTokens":1494}}609{"id":"stack-69873943","source":"stackoverflow","questionId":69873943,"title":"How to disable progress bar in Nuxt?","tags":["vue.js","axios","nuxt.js"],"text":"Title: How to disable progress bar in Nuxt?\nTags: vue.js, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am making HTTP communications with Axios in my Nuxt JS Project. When I send a request, a bar appears at the top of the page. How can I turn this off?\n\nAlso: How can I do if I want to edit this instead of closing it? (Color, Thickness)\n\n========================================\n\nCode:\n```js\nexport default {\n loading: false\n}\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- This is a quality of life feature for your end users on slow connection devices. I do recommend not disabling it.\n- I put this manually where requests are made. (Progressbar). My client wants it like this ¯|_(**)_| ¯","metadata":{"transformedAt":"2026-08-18T18:33:07.881Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":27,"estimatedTokens":187}}610{"id":"stack-53194999","source":"stackoverflow","questionId":53194999,"title":"How can I create a custom loading indicator in Nuxt.js?","tags":["javascript","vue.js","nuxt.js"],"text":"Title: How can I create a custom loading indicator in Nuxt.js?\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nInside this page (https://nuxtjs.org/api/configuration-loading-indicator#custom-indicators) says that I can create a custom loading indicator but not says how.\n\nSomebody can help me - how to create and set this into to nuxt.config?\n\n========================================\n\nTop Answer:\nHere is what you need :\n\nYou can create a component for your app.\nYou can read about the Nuxt Loading Here\n\nSet the component has `loading: `\nRead more here The loading indicator Property.\n\n- For nuxt to load it on your pages, you need to add :\n\n```\nloadingIndicator: {\n name: 'chasing-dots',\n color: 'purple',\n background: 'green'\n }\n```\n\nHere is an example of how I configured the component in my app.\n\n```\nexport default {\n\n // LoadingBar component\n loading: '~/path-to-your-loading-component/Loading.vue',\n}\n```\n\nOn the page you want to load, add this.\n\n```\nexport default {\n /*\n ** programmatically start the loader so we force the page to take x2seconds to load\n */\n mounted() {\n this.$nextTick(() => {\n this.$nuxt.$loading.start()\n setTimeout(() => this.$nuxt.$loading.finish(), 2000)\n })\n }\n}\n\n```\n```\n\n========================================\n\nCode:\n```text\nexport default {\n ..., // Other Nuxt configuration\n\n // Simple usage:\n loadingIndicator: '~/custom-locading-indicator.html',\n\n // Or with dynamic configuration variables passed via lodash template syntax\n loadingIndicator: {\n name: '~/custom-locading-indicator.html',\n color: '#000',\n background: '#fff'\n }\n}\n```\n\n```text\nloadingIndicator\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n<template>\n <div>\n <h1>Home page</h1>\n <div v-show=\"$nuxt.$loading.get() > 0\">\n {{loadingIndicator}}%\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n computed: {\n loadingIndicator() {\n return this.$root.$loading.get()\n }\n }\n}\n</script>\n```\n\n```text\n$loading\n```\n\n```text\n$nuxt.$loading.get()\n```\n\n```text\ncomputed: {\n loadingIndicator() {\n return window.$nuxt.$root.$loading.percent\n }\n },\n```\n\n```text\nwindow.$nuxt.$root.$loading.percent\n```\n\n```text\n$nuxt.$loading.get()\n```\n\n```js\ncomputed: {\n nuxtLoading() {\n return this.$nuxt.$loading.percent\n },\n },\n```\n\n```text\n<template>\n <div \n v-if=\"isLoading\"\n class=\"loader\"\n >\n <div class=\"loader__spinner spinner-border text-primary\" role=\"status\">\n <span class=\"sr-only\">Loading...</span>\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n isLoading: false\n }\n },\n methods: {\n start() {\n this.isLoading = true\n },\n finish() {\n this.isLoading = false\n }\n }\n}\n</script>\n\n<style lang=\"scss\" scoped>\n.loader {\n &__spinner {\n position: fixed;\n top: 10px;\n left: 10px;\n }\n}\n</style>\n```\n\n```text\nloadingIndicator: {\n name: 'chasing-dots',\n color: 'purple',\n background: 'green'\n }\n```\n\n```js\nexport default {\n\n // LoadingBar component\n loading: '~/path-to-your-loading-component/Loading.vue',\n}\n```\n\n```js\nexport default {\n /*\n ** programmatically start the loader so we force the page to take x2seconds to load\n */\n mounted() {\n this.$nextTick(() => {\n this.$nuxt.$loading.start()\n setTimeout(() => this.$nuxt.$loading.finish(), 2000)\n })\n }\n}\n</script>\n```\n```\n\n```text\nloading: <your-component-path>\n```\n\n========================================\n\nComments:\n- it's another loading. I need for nuxtjs.org/api/configuration-loading-indicator not for nuxtjs.org/api/configuration-loading\n- The info that I wanted is for: Custom Loading Indicator\n- How can I use an image as the loader in this html template? @aBiscuit\n- The same way you use in any HTML file - with an image tag (or background) and a link to the image. And place the image inside `static` folder.\n- in my nuxt.config.js loadingIndicator: { name: '/loadingIndicator.html', }, and in static folder i have made on loadingIndicator.html file but it didn't work. the loader is not visible. but when i use collection of nuxt it work. custom didn't work.\n- As you can see in examples above, we use webpack alias for `name` property of `loadingIndicator`. This means, that path to html file is resolved during build process. At this point, I would not recommend putting indicator template file into a `static` static folder, as it served a different purpose. Instead, you can put it in `components` or a custom folder and provide a correct path. Example with `components` folder: `name: '~/components/loading-indicator.html'`. Also, suggest not to use camel case for html filenames.\n- I get an error: *`$nuxt.$loading.get is not a function`*","metadata":{"transformedAt":"2026-08-18T18:33:07.881Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":225,"estimatedTokens":1180}}611{"id":"stack-63955208","source":"stackoverflow","questionId":63955208,"title":"Add modifier to v-on in menu activator using Vuetify","tags":["javascript","vue.js","vue-component","nuxt.js","vuetify.js"],"text":"Title: Add modifier to v-on in menu activator using Vuetify\nTags: javascript, vue.js, vue-component, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nSimplified example:\n\n```\n\n \n \n \n // I tried .stop, .stop.prevent, self.prevent, prevent.stop\n \n bla \n \n \n\n```\n\nSo as you can see child event v-on triggers v-menu and shows this div. But it also triggers parent :to event. Any ides?\n\n========================================\n\nTop Answer:\nYou are using the event modifier on v-on, no on v-on.click.\n\nYou can stop the propagation by adding `@click` with the modifier separately to the button:\n\n``\n\n========================================\n\nCode:\n```text\n<v-list>\n <v-list-item :to=\"bla/bla\">\n <v-menu>\n <template v-slot:activator=\"{on}\">\n <v-btn v-on.prevent=\"on\"/> // I tried .stop, .stop.prevent, self.prevent, prevent.stop\n </template>\n <div> bla </div>\n <v-menu> \n </v-list-item>\n</v-list>\n```\n\n```text\n<template v-slot:activator=\"{ on: { click } }\">\n <v-btn v-on:click.stop.prevent=\"click\">\n open\n </v-btn>\n </template>\n```\n\n```text\non\n```\n\n```text\n@click\n```\n\n```text\n<v-btn v-on=\"on\" @click.stop.prevent />\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.881Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":66,"estimatedTokens":296}}612{"id":"stack-53983382","source":"stackoverflow","questionId":53983382,"title":"Nuxt.js After npm run generate cannot find files","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: Nuxt.js After npm run generate cannot find files\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI’m trying to generate my app with npm run generate\non terminal. I’m not getting some error there is everything well generated. And in my development server everything work well routings components etc., but after generate when I open to index.html in dist folder I can’t access other pages, there are errors like that on chrome console.\n\n```\nFailed to load resource: net::ERR_FILE_NOT_FOUND\nf8ff67c7350097487a5e.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND\ne63cddd635f290d15a6f.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND\n9a1a3c7742fdcce5403a.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND\n1e056384fb18617ca6a5.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND\nbde8656.png:1 Failed to load resource: net::ERR_FILE_NOT_FOUND\n/favicon.ico:1 Failed to load resource: net::ERR_FILE_NOT_FOUND\n```\n\nI try to upload dist folder to my ftp but there is too same…\n\nhere is my nuxt.config file\n\n```\nconst pkg = require('./package')\n\nmodule.exports = {\n mode: 'universal',\n\n /*\n ** Headers of the page\n */\n head: {\n title: pkg.name,\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: pkg.description }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n\n /*\n ** Customize the progress-bar color\n */\n loading: { color: '#fff' },\n\n /*\n ** Global CSS\n */\n css: [\n ],\n\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n ],\n\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://github.com/nuxt-community/axios-module#usage\n '@nuxtjs/axios',\n // Doc:https://github.com/nuxt-community/modules/tree/master/packages/bulma\n '@nuxtjs/bulma',\n // ['nuxt-validate', {\n // lang: 'tr',\n // // regular vee-validate options \n // }]\n ],\n /*\n ** Axios module configuration\n */\n axios: {\n // See https://github.com/nuxt-community/axios-module#options\n },\n\n /*\n ** Build configuration\n */\n build: {\n postcss: {\n preset: {\n features: {\n customProperties: false\n }\n }\n },\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nFailed to load resource: net::ERR_FILE_NOT_FOUND\nf8ff67c7350097487a5e.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND\ne63cddd635f290d15a6f.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND\n9a1a3c7742fdcce5403a.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND\n1e056384fb18617ca6a5.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND\nbde8656.png:1 Failed to load resource: net::ERR_FILE_NOT_FOUND\n/favicon.ico:1 Failed to load resource: net::ERR_FILE_NOT_FOUND\n```\n\n```text\nconst pkg = require('./package')\n\nmodule.exports = {\n mode: 'universal',\n\n /*\n ** Headers of the page\n */\n head: {\n title: pkg.name,\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: pkg.description }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n\n /*\n ** Customize the progress-bar color\n */\n loading: { color: '#fff' },\n\n /*\n ** Global CSS\n */\n css: [\n ],\n\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n ],\n\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://github.com/nuxt-community/axios-module#usage\n '@nuxtjs/axios',\n // Doc:https://github.com/nuxt-community/modules/tree/master/packages/bulma\n '@nuxtjs/bulma',\n // ['nuxt-validate', {\n // lang: 'tr',\n // // regular vee-validate options \n // }]\n ],\n /*\n ** Axios module configuration\n */\n axios: {\n // See https://github.com/nuxt-community/axios-module#options\n },\n\n /*\n ** Build configuration\n */\n build: {\n postcss: {\n preset: {\n features: {\n customProperties: false\n }\n }\n },\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n\n }\n }\n}\n```\n\n```text\nexport default {\n router: {\n base: '/app/'\n }\n}\n```\n\n========================================\n\nComments:\n- does your project load data from a server?.\n- No. there is just one api call have which i make something with response thats all.\n- How do u open your generated project? If you open your html file directly in browser it wont work. You need a http server\n- @Aldarund i have upload content of dist folder to my ftp and there is too not working, I think problem is browser search _nuxt folder outside of root\n- Do u upload and access it via root domain e.g yourdomain.com ? or yourdomain.com/somedir ?\n- @Aldarund yes i try to Access via yourdomain.com/dir/","metadata":{"transformedAt":"2026-08-18T18:33:07.881Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":210,"estimatedTokens":1197}}613{"id":"stack-67055165","source":"stackoverflow","questionId":67055165,"title":"TS2749: 'XXX' refers to a value, but is being used as a type here. Did you mean 'typeof XXX'?","tags":["typescript","vue.js","nuxt.js","typescript-typings","vue-test-utils"],"text":"Title: TS2749: 'XXX' refers to a value, but is being used as a type here. Did you mean 'typeof XXX'?\nTags: typescript, vue.js, nuxt.js, typescript-typings, vue-test-utils\nSource: Stack Overflow\n\nQuestion:\nI'm having quite a weird error when running my `npm run dev` developed using `Nuxt.js`, which has `Vue.js` components. Namely, when running the app, I'm seeing errors related to `TypeScript` such as `TS2749: 'About' refers to a value, but is being used as a type here. Did you mean 'typeof About'?`, even though `npm run test` doesn't show anything.\n\nMy **spec.ts** file with complaining line\n\n```\nimport { shallowMount, Wrapper } from \"@vue/test-utils\"; \nimport About from \"@/pages/about.vue\";\n\ndescribe(\"About\", () => {\n const wrapper: Wrapper = shallowMount(About); // The type should be fine when highlighting before setting typing, it shows me the type below.\n\nhttps://i.sstatic.net/OUN8O.png\n\nThe suggested solution with `const wrapper: Wrapper = shallowMount(About);` generates yet another `TypeScript` error causing the test not compiling. Namely, `TS2344: Type 'ExtendedVue' does not satisfy the constraint 'Vue'. Type 'VueConstructor' is missing the following properties from type 'Vue': $el, $options, $parent, $root, and 32 more.`\n\nI'm not sure why `test` is silent, whereas `TypeScript` starts complaining when running the app locally about the tests themselves. They're all passing btw, and the app compiles. It's simply related to some kind of `TypeScript`'s typings in `@vue/test-utils`.\n\n========================================\n\nCode:\n```text\nimport { shallowMount, Wrapper } from \"@vue/test-utils\"; \nimport About from \"@/pages/about.vue\";\n\ndescribe(\"About\", () => {\n const wrapper: Wrapper<About> = shallowMount(About); // <-- Complaining line\n ...\n}\n```\n\n```text\nnpm run dev\n```\n\n```text\nNuxt.js\n```\n\n```text\nVue.js\n```\n\n```text\nTypeScript\n```\n\n```text\nTS2749: 'About' refers to a value, but is being used as a type here. Did you mean 'typeof About'?\n```\n\n```text\nnpm run test\n```\n\n```text\nconst wrapper: Wrapper<typeof About> = shallowMount(About);\n```\n\n```text\nTypeScript\n```\n\n```text\nTS2344: Type 'ExtendedVue<Vue, unknown, unknown, { setLocation: any; }, unknown>' does not satisfy the constraint 'Vue'. Type 'VueConstructor<{ setLocation: any; } & Vue>' is missing the following properties from type 'Vue': $el, $options, $parent, $root, and 32 more.\n```\n\n```text\ntest\n```\n\n```text\nTypeScript\n```\n\n```text\nTypeScript\n```\n\n```text\n@vue/test-utils\n```\n\n```text\nWrapper<About>\n```\n\n```text\nAbout\n```\n\n```text\nWrapper<InstanceType<typeof About>>\n```\n\n========================================\n\nComments:\n- Why do you even type the `wrapper` when it seems TS is perfectly able to infer the type ?\n- for explicit typing\n- The typing is explicit - it comes from `@vue/test-utils`. Duplicate the typing in your own code feels wrong...\n- Well, I've removed it to have a clear console. However, if the types are the same for readability & documentation I'd prefer to use explicit types, and it shouldn't cause anything in the console. Especially, if the tests don't show anything, and `npm run dev` does.\n- Well test runing fine is really strange because `Wrapper` is really NOT valid TS type definition. Anything inside `<>` must by TS type - `About` is not TS type, it is really a value (Vue component definition object)\n- It was a typo, fixed!:)\n- It clarifies, thanks. Mostly, I try to have explicit typing for code readability, but apparently, here I was wrong.\n- PS. `Wrapper` return the same issue as in the question :)\n- `Wrapper>` works","metadata":{"transformedAt":"2026-08-18T18:33:07.881Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":111,"estimatedTokens":894}}614{"id":"stack-65551188","source":"stackoverflow","questionId":65551188,"title":"How to cleanup Nuxt js extra div containers?","tags":["javascript","vue.js","vue-component","nuxt.js"],"text":"Title: How to cleanup Nuxt js extra div containers?\nTags: javascript, vue.js, vue-component, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nthis is my example page:\n\nhttps://i.sstatic.net/CYCRL.png\n\nThis is the Nuxt layout:\n\n```\n\n \n \n \n\n```\n\nAnd this is what's produced by the Nuxt compiler:\n\nhttps://i.sstatic.net/CYdX3.png\n\nAs you can see, there are several, useless, extra containers. Is there any way to get rid of them in Nuxt?\n\n========================================\n\nTop Answer:\nIn case anyone still has this issue years later, you can override the expectations with Nuxt 3+ (and the time of this writing), you can use the `rootTag` config option.\n\nSo your `nuxt.config.ts` may look like this:\n\n```\nexport default defineNuxtConfig({\n compatibilityDate: '2024-04-03',\n\n app: {\n rootTag: 'body',\n rootId: 'app',\n },\n})\n```\n\nUsing this config puts all HTML elements inside ``, things are contained by the main wrapping div to keep things a bit more tidy.\n\nAnd as for the `` tags, I have seen Nuxt examples and have also done it with 0 issues, but you can have multiple root elements or remove the wrapping `` which just adds another layer of nested elements.\n\ne.g.\n\n```\n\n \n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div>\n <Nuxt />\n </div>\n</template>\n```\n\n```text\n<div id=\"__nuxt\">\n```\n\n```text\n<div id=\"__layout\">\n```\n\n```text\nglobalName\n```\n\n```text\nexport default defineNuxtConfig({\n compatibilityDate: '2024-04-03',\n\n app: {\n rootTag: 'body',\n rootId: 'app',\n },\n})\n```\n\n```text\n<template>\n <NuxtPage />\n</template>\n```\n\n```text\nrootTag\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n<body>\n```\n\n```text\n<template></template>\n```\n\n```text\n<div>\n```\n\n========================================\n\nComments:\n- Clément - I know it's not your fault, but it is so, so, SO tiring that we cannot control, as a very basic, fundamental level, the semantic structure of, for lack of a better term, a damn blank white html page. It is craptacular that things are wrapped within 'div' which has zero meaning in any given state. Zero. FFS at least put it in an existing HTML element that means something, and can be re-used, like 'section', or even 'article' (tho there are requirements expected using the last one). Thanks for reading, I owe you a coffee/beer/your happy liquid for listening to my rant.\n- This has been renamed. Currently on Nuxt 3.2 nuxt.config.js: `export default { app: { rootId: '...' }}`\n- nuxt.com/docs/api/configuration/nuxt-config/#rootid","metadata":{"transformedAt":"2026-08-18T18:33:07.881Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":121,"estimatedTokens":625}}615{"id":"stack-65774179","source":"stackoverflow","questionId":65774179,"title":"TypeError: stripe.redirectToCheckout is not a function in nuxt.js","tags":["vue.js","stripe-payments","nuxt.js"],"text":"Title: TypeError: stripe.redirectToCheckout is not a function in nuxt.js\nTags: vue.js, stripe-payments, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to integrate stripe payment gateway. I have a nuxt.js for front-end and adonis.js for backend.\n\nFrom front-end I am calling an api to backend to create `checkoutSession` and return the `sessionID`. I am able to create `checkoutSession` and return the `sessionID` and in api response I am calling the\n`stripe.redirectToCheckout` but it is not redirecting rather gives error as stripe.redirectToCheckout is not a function. How can I redirect users to checkout Page?\n\nI have install the stripe-js file also.\n\n```\nimport { loadStripe } from '@stripe/stripe-js'\nconst stripe = loadStripe(process.env.STRIPE_PK)\n\nBuy\n\nimport { loadStripe } from '@stripe/stripe-js'\nconst stripe = loadStripe(process.env.STRIPE_PK)\n\nexport default {\n methods: {\n checkout() {\n let params = {\n payment_method_types: ['card'],\n line_items: [\n {\n name: 'Buy Now',\n images: ['image.jpg'],\n amount: 100 + '00',\n currency: 'usd',\n quantity: 1,\n },\n ],\n mode: 'payment',\n success_url: `${process.env.URL}/success`,\n cancel_url: window.location.href,\n }\n axios\n .post(`${process.env.API_BASE_URL}/stripe/session`, params, {\n 'Content-type': 'application/json',\n Accept: 'application/json',\n })\n .then((response) => {\n this.stripeSession = response.data.data\n stripe.redirectToCheckout({sessionId: this.stripeSession})\n })\n .catch((e) => {\n console.log(e)\n })\n }\n },\n}\n\n```\n\n========================================\n\nTop Answer:\nAccording to tyhe doc, `loadStripe` is an async function, try adding `await` in stripe assignement:\n\n```\nconst stripe = await loadStripe(process.env.STRIPE_PK)\n```\n\nEdit:\nTo get rid of `Module parse failed: Cannot use keyword 'await' outside an async function` error you just need to add async before your function declaration :\n\n```\nasync function myAsyncFunction() {\n const test = await myPromise();\n}\n```\n\nAs I do not have the full definition of your function I cannot show it to you in your code :-(\n\nBut a weird solution (mixing 'await' and 'then') would be :\n\n```\nimport { loadStripe } from '@stripe/stripe-js';\n\naxios\n .post(`${process.env.API_BASE_URL}/stripe/session`, params, {\n 'Content-type': 'application/json',\n Accept: 'application/json',\n })\n .then(async response => {\n this.stripeSession = response.data.data;\n const stripe = await loadStripe(process.env.STRIPE_PK);\n stripe.redirectToCheckout({ sessionId: this.stripeSession });\n })\n .catch(e => {\n console.log(e);\n });\n```\n\n========================================\n\nCode:\n```text\nimport { loadStripe } from '@stripe/stripe-js'\nconst stripe = loadStripe(process.env.STRIPE_PK)\n\n<button class=\"btn btn-primary btn-block text-center rounded\" @click=\"checkout()\">Buy</button>\n\nimport { loadStripe } from '@stripe/stripe-js'\nconst stripe = loadStripe(process.env.STRIPE_PK)\n\nexport default {\n methods: {\n checkout() {\n let params = {\n payment_method_types: ['card'],\n line_items: [\n {\n name: 'Buy Now',\n images: ['image.jpg'],\n amount: 100 + '00',\n currency: 'usd',\n quantity: 1,\n },\n ],\n mode: 'payment',\n success_url: `${process.env.URL}/success`,\n cancel_url: window.location.href,\n }\n axios\n .post(`${process.env.API_BASE_URL}/stripe/session`, params, {\n 'Content-type': 'application/json',\n Accept: 'application/json',\n })\n .then((response) => {\n this.stripeSession = response.data.data\n stripe.redirectToCheckout({sessionId: this.stripeSession})\n })\n .catch((e) => {\n console.log(e)\n })\n }\n },\n}\n</script>\n```\n\n```text\ncheckoutSession\n```\n\n```text\nsessionID\n```\n\n```text\ncheckoutSession\n```\n\n```text\nsessionID\n```\n\n```text\nstripe.redirectToCheckout\n```\n\n```text\nimport { loadStripe } from '@stripe/stripe-js';\n\nexport default {\n methods: {\n async checkout() {\n let params = {\n payment_method_types: ['card'],\n line_items: [\n {\n name: 'Buy Now',\n images: ['image.jpg'],\n amount: 100 + '00',\n currency: 'usd',\n quantity: 1,\n },\n ],\n mode: 'payment',\n success_url: `${process.env.URL}/success`,\n cancel_url: window.location.href,\n };\n\n try {\n const { data } = await axios.post(`${process.env.API_BASE_URL}/stripe/session`, params, {\n 'Content-type': 'application/json',\n Accept: 'application/json',\n });\n this.stripeSession = data.data;\n const stripe = await loadStripe(process.env.STRIPE_PK);\n stripe.redirectToCheckout({ sessionId: this.stripeSession });\n } catch (error) {\n console.error(error);\n }\n },\n },\n};\n```\n\n```text\nconst stripe = await loadStripe(process.env.STRIPE_PK)\n```\n\n```text\nasync function myAsyncFunction() {\n const test = await myPromise();\n}\n```\n\n```text\nimport { loadStripe } from '@stripe/stripe-js';\n\naxios\n .post(`${process.env.API_BASE_URL}/stripe/session`, params, {\n 'Content-type': 'application/json',\n Accept: 'application/json',\n })\n .then(async response => {\n this.stripeSession = response.data.data;\n const stripe = await loadStripe(process.env.STRIPE_PK);\n stripe.redirectToCheckout({ sessionId: this.stripeSession });\n })\n .catch(e => {\n console.log(e);\n });\n```\n\n```text\nloadStripe\n```\n\n```text\nawait\n```\n\n```text\nModule parse failed: Cannot use keyword 'await' outside an async function\n```\n\n========================================\n\nComments:\n- You are supposed to send `sessionId` but you are sending whole `stripeSession`. Did you try `{ sessionId: this.stripeSession.id }`?\n- Yes, from backend api I am sending only the session.id in response not the entire session.\n- @AdamOrlov `stripe.redirectToCheckout is not a function` this is the error I am getting\n- What version of `stripe-js` are you using?\n- @AdamOrlov stripe-js : `^1.11.0`\n- using async gets this error `Module parse failed: Cannot use keyword 'await' outside an async function`\n- I have used nuxt.js for the front-end\n- `await loadStripe` definitely helped! Great answer!","metadata":{"transformedAt":"2026-08-18T18:33:07.881Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":254,"estimatedTokens":1623}}616{"id":"stack-67512208","source":"stackoverflow","questionId":67512208,"title":"Dynamically change colours of element in vue loop","tags":["css","vue.js","nuxt.js","vuex"],"text":"Title: Dynamically change colours of element in vue loop\nTags: css, vue.js, nuxt.js, vuex\nSource: Stack Overflow\n\nQuestion:\nso I am trying to achieve the following design:\nhttps://i.sstatic.net/5LDBh.png\n\nSpecifically the colourful badges on top. Now these items are grouped and can be any number.\nIn the picture they are grouped into 2 but they can easily be 4 or 5.\n\nI wanted a way to programmatically change the background and text colour of each badge for each group.\n\nI have tried soo many things that haven't worked for me, at best I am currently only able to get the first colour to change.\n\nthis is my page:\n\n```\n\n \n \n \n \n \n \n\n \n {{ route.origin }} - {{ route.destination }}\n \n {{ departureDate.formattedDate }}\n \n \n\n \n \n \n \n \n \n\nimport { mapState } from 'vuex';\nimport type from '~/components/bus/type.vue';\nimport schedule from '~/components/bus/schedule.vue';\n\nexport default {\n name: 'schedules',\n layout: 'bus-default',\n components: {type, schedule},\n async fetch({ store }) {\n const trip = store.state.trip;\n const schedule = store.state.schedule;\n\n await store.dispatch('schedule/getSchedules', {\n company: trip.company.alias,\n origin: trip.route.origin,\n destination: trip.route.destination, \n date: trip.departureDate.fullDate,\n schedules: schedule.schedules\n });\n },\n computed: {\n ...mapState({\n company: state => state.trip.company.name,\n route: state => state.trip.route,\n departureDate: state => state.trip.departureDate,\n schedules: state => state.schedule.schedules,\n colours: state => state.schedule.colours\n }),\n }\n}\n\n```\n\nThis is my component that contains the badge:\n\n```\n\n \n {{ name }}\n \n \n\nimport { mapState } from 'vuex';\n\nexport default {\n name: 'type',\n props: ['name', 'bg-color', 'text-color'],\n computed: {\n ...mapState({\n colours: state => state.schedule.colours\n }),\n }\n}\n\n```\n\nThis is my store file:\n\n```\nexport const state = () => ({\n schedules: [],\n schedule: {},\n colours: [{'bg': 'bg-red-400', 'text': 'text-white'}, {'bg': 'bg-blue-400', 'text': 'text-white'}, {'bg': 'bg-yellow-600', 'text': 'text-gray-800'}],\n colour: {}\n});\n\nexport const mutations = {\n setColours(state, colours) {\n state.colours = colours;\n },\n setColour(state, colour) {\n state.colour = colour;\n },\n setSchedules(state, schedules) {\n state.schedules = schedules;\n },\n}\n\nexport const actions = {\n async getSchedules({ commit }, params) {\n const res = await this.$api.get('/bus/schedules', { params: params });\n commit('setSchedules', res.data); \n },\n initialiseColours({ commit }) {\n const colours = [{'bg': 'bg-red-400', 'text': 'text-white'}, {'bg': 'bg-blue-400', 'text': 'text-white'}, {'bg': 'bg-yellow-600', 'text': 'text-gray-800'}];\n commit('setColours', colours); \n },\n getRandomColour({ commit, state }) {\n var colours = [...state.colours];\n console.log('colours:', colours);\n var index = Math.floor(Math.random() * colours.length);\n const colour = colours.splice(index, 1)[0];\n commit('setColours', colours); \n commit('setColour', colour); \n },\n}\n```\n\nSo what I want to achieve here is to programmatically assign random background colours to each \"badge\" in each group. The badges I'm referring to are the executive and standard in the picture.\n\nAlso the text should be visible depending on the background, white when necessary or black when necessary.\n\nFor some reason my solution only changes the first item, the 2nd item is transparent however when I inspect HTML I see the class there but it doesn't show the colour in the browser.\n\nEdit: So one last thing I forgot to add is colours should be used without replacement, meaning when one could has been used it should not repeat again.\n\n========================================\n\nTop Answer:\nYour code is close to working, but there's a problem in the class binding:\n\n```\n ❌\n```\n\nThat binding sets two classes on the `div` named `\"bgColor\"` and `\"textColor\"`, but if you actually want the values of those props to be the class names, you should bind an array of those props:\n\n```\n\n```\n\nAssuming those class names correspond to existing styles, the background and text color would update accordingly.\n\nTo randomize the badge colors, shuffle a copy of the `state.schedule.colours` array in the computed property:\n\n```\n// https://stackoverflow.com/a/2450976/6277151\nfunction shuffleArray(array) {\n if (!array || array.length 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n const temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n return array;\n}\n\nexport default {\n computed: {\n ...mapState({\n colours: state => shuffleArray(state.schedule.colours)\n }),\n }\n}\n```\n\ndemo\n\n========================================\n\nCode:\n```html\n<template>\n <div class=\"w-full flex flex-col px-6\">\n <div class=\"flex flex-row\">\n <button class=\"flex flex-wrap justify-center content-center w-20 h-20 bg-blob-1 bg-no-repeat bg-contain bg-center -ml-3\">\n <img class=\"flex w-5 h-5\" src=\"~/assets/images/icon-back.svg\" alt=\"\">\n </button>\n </div>\n\n <div class=\"flex flex-col mt-1\">\n <span class=\"font-raleway font-black text-2xl text-white\">{{ route.origin }} - {{ route.destination }}</span>\n <div class=\"inline-block w-44 bg-black bg-opacity-50 rounded p-2\">\n <div class=\"font-raleway text-md text-white\">{{ departureDate.formattedDate }}</div>\n </div>\n </div>\n\n <div class=\"flex flex-col mt-10\">\n <type :name=\"name\" :bg-color=\"colours[index].bg\" :text-color=\"colours[index].text\" v-for=\"(values, name, index) in schedules\" :key=\"name\" class=\"mb-10\">\n <schedule :schedule=\"schedule\" v-for=\"schedule in values\" :key=\"schedule.id\" class=\"mb-1\" />\n </type>\n </div>\n </div>\n</template>\n\n<script>\nimport { mapState } from 'vuex';\nimport type from '~/components/bus/type.vue';\nimport schedule from '~/components/bus/schedule.vue';\n\nexport default {\n name: 'schedules',\n layout: 'bus-default',\n components: {type, schedule},\n async fetch({ store }) {\n const trip = store.state.trip;\n const schedule = store.state.schedule;\n\n await store.dispatch('schedule/getSchedules', {\n company: trip.company.alias,\n origin: trip.route.origin,\n destination: trip.route.destination, \n date: trip.departureDate.fullDate,\n schedules: schedule.schedules\n });\n },\n computed: {\n ...mapState({\n company: state => state.trip.company.name,\n route: state => state.trip.route,\n departureDate: state => state.trip.departureDate,\n schedules: state => state.schedule.schedules,\n colours: state => state.schedule.colours\n }),\n }\n}\n</script>\n```\n\n```html\n<template>\n <div>\n <div :class=\"{bgColor: true, textColor}\" :key=\"bgColor\" class=\"w-auto inline-block rounded-full px-3 py-1 ml-3 absolute z-20 shadow-md -mt-4 font-raleway text-sm capitalize\">{{ name }}</div>\n <slot></slot>\n </div>\n</template>\n\n<script>\nimport { mapState } from 'vuex';\n\nexport default {\n name: 'type',\n props: ['name', 'bg-color', 'text-color'],\n computed: {\n ...mapState({\n colours: state => state.schedule.colours\n }),\n }\n}\n</script>\n```\n\n```js\nexport const state = () => ({\n schedules: [],\n schedule: {},\n colours: [{'bg': 'bg-red-400', 'text': 'text-white'}, {'bg': 'bg-blue-400', 'text': 'text-white'}, {'bg': 'bg-yellow-600', 'text': 'text-gray-800'}],\n colour: {}\n});\n\nexport const mutations = {\n setColours(state, colours) {\n state.colours = colours;\n },\n setColour(state, colour) {\n state.colour = colour;\n },\n setSchedules(state, schedules) {\n state.schedules = schedules;\n },\n}\n\nexport const actions = {\n async getSchedules({ commit }, params) {\n const res = await this.$api.get('/bus/schedules', { params: params });\n commit('setSchedules', res.data); \n },\n initialiseColours({ commit }) {\n const colours = [{'bg': 'bg-red-400', 'text': 'text-white'}, {'bg': 'bg-blue-400', 'text': 'text-white'}, {'bg': 'bg-yellow-600', 'text': 'text-gray-800'}];\n commit('setColours', colours); \n },\n getRandomColour({ commit, state }) {\n var colours = [...state.colours];\n console.log('colours:', colours);\n var index = Math.floor(Math.random() * colours.length);\n const colour = colours.splice(index, 1)[0];\n commit('setColours', colours); \n commit('setColour', colour); \n },\n}\n```\n\n```html\n<template>\n <div>\n <div\n v-for=\"(button, index) in numberOfIterations\"\n :key=\"button\"\n :class=\"[arrayOfColours[findRandomInRange()]]\"\n >\n div #{{ index }}\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n arrayOfColours: ['red', 'blue', 'orange'],\n numberOfIterations: 6,\n }\n },\n methods: {\n findRandomInRange() {\n return Math.floor(Math.random() * this.numberOfIterations) % this.arrayOfColours.length\n },\n },\n}\n</script>\n\n<style>\n.red {\n background-color: red;\n}\n.blue {\n background-color: blue;\n}\n.orange {\n background-color: orange;\n}\n</style>\n```\n\n```html\n<template>\n <div>\n <div v-for=\"(button, index) in arrayOfColours\" :key=\"button\" :class=\"[arrayOfColours[index]]\">\n div #{{ index }}\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n arrayOfColours: ['red', 'blue', 'orange'],\n }\n },\n created() {\n this.shuffle() // shuffle the order of the array before you mount it to the DOM\n },\n methods: {\n shuffle() {\n this.arrayOfColours.sort(() => Math.random() - 0.5)\n },\n },\n}\n</script>\n```\n\n```text\nnumberOfIterations\n```\n\n```text\n% this.arrayOfColours.length\n```\n\n```text\nfindRandomInRange()\n```\n\n```text\n:key\n```\n\n```html\n<div :class=\"{bgColor: true, textColor}\"> ❌\n```\n\n```html\n<div :class=\"[bgColor, textColor]\">\n```\n\n```js\n// https://stackoverflow.com/a/2450976/6277151\nfunction shuffleArray(array) {\n if (!array || array.length <= 1) return array;\n array = array.slice();\n for (let i = array.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n const temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n return array;\n}\n\nexport default {\n computed: {\n ...mapState({\n colours: state => shuffleArray(state.schedule.colours)\n }),\n }\n}\n```\n\n```text\ndiv\n```\n\n```text\n\"bgColor\"\n```\n\n```text\n\"textColor\"\n```\n\n```text\nstate.schedule.colours\n```\n\n========================================\n\nComments:\n- Do you really need to use vuex here? Looks like more work than anything else. Otherwise, this is my take on your use case: stackoverflow.com/a/67382023/8816585 If you want something totally random, use a simple `colours` array with `['bg-red-400', 'bg-blue-400', 'bg-yellow-400' etc...]` in it rather than an array of objects with a useless `bg` key.","metadata":{"transformedAt":"2026-08-18T18:33:07.881Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":449,"estimatedTokens":2677}}617{"id":"stack-60472642","source":"stackoverflow","questionId":60472642,"title":"NuxtJS Changes assets file names in production","tags":["vue.js","webpack","nuxt.js"],"text":"Title: NuxtJS Changes assets file names in production\nTags: vue.js, webpack, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm new to VueJS, NuxtJS, Webpack. Currently using NuxtJS for a static site, its going good till now. The only thing that worries me is that the file names is assets folder gets change to some hash after build. For example:\n\n```\n~/assets/images/image.png\n```\n\nChanges to:\n\n```\n/_nuxt/img/1e88315.png\n```\n\nIs their anyway we can use same image name or image name with hash like: `/_nuxt/img/image-1e88315.png`\n\nAlso, is their anyway we can change `_nuxt` folder name to something else?\n\nThanks!\n\n========================================\n\nCode:\n```text\n~/assets/images/image.png\n```\n\n```text\n/_nuxt/img/1e88315.png\n```\n\n```text\n/_nuxt/img/image-1e88315.png\n```\n\n```text\n_nuxt\n```\n\n```text\n{\n app: ({ isDev }) => isDev ? '[name].js' : '[contenthash].js',\n chunk: ({ isDev }) => isDev ? '[name].js' : '[contenthash].js',\n css: ({ isDev }) => isDev ? '[name].css' : '[contenthash].css',\n img: ({ isDev }) => isDev ? '[path][name].[ext]' : 'img/[contenthash:7].[ext]',\n font: ({ isDev }) => isDev ? '[path][name].[ext]' : 'fonts/[contenthash:7].[ext]',\n video: ({ isDev }) => isDev ? '[path][name].[ext]' : 'videos/[contenthash:7].[ext]'\n}\n```\n\n```text\nbuild: {\n filenames: {\n img: 'img/[name]-[contenthash:7].[ext]'\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.881Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":60,"estimatedTokens":339}}618{"id":"stack-63547656","source":"stackoverflow","questionId":63547656,"title":"Error ServerMiddleware should expose a handle nuxt","tags":["websocket","nuxt.js","ws"],"text":"Title: Error ServerMiddleware should expose a handle nuxt\nTags: websocket, nuxt.js, ws\nSource: Stack Overflow\n\nQuestion:\n- The new nuxt.js setup does not come with a server folder\n\n- You create an API folder and put a file inside which exposes the server\n\n- I am trying to use websockets using the ws library to parse user session and getting this error\n\n**Here is my code for app.js placed inside api folder**\n\n```\nimport http from 'http'\nimport logger from 'express-pino-logger'\nimport express from 'express'\nimport cookieParser from 'cookie-parser'\nimport WebSocket from 'ws'\nconst app = express()\nconst sessionParser = cookieParser()\nconst map = new Map()\napp.use(logger())\napp.use(express.json())\napp.use(express.urlencoded({ extended: true }))\napp.use(sessionParser)\napp.use('/v1', (req, res) => res.json('hello'))\n\nconst server = http.createServer(app)\nconst wss = new WebSocket.Server({ noServer: true })\n\nwss.on('connection', function connection(ws, request, client) {\n ws.on('message', function message(msg) {\n console.log(`Received message ${msg} from user ${client}`)\n })\n})\n\nserver.on('upgrade', function (request, socket, head) {\n console.log('Parsing session from request...')\n\n sessionParser(request, {}, () => {\n if (!request.session.userId) {\n socket.destroy()\n return\n }\n\n console.log('Session is parsed!')\n\n wss.handleUpgrade(request, socket, head, function (ws) {\n wss.emit('connection', ws, request)\n })\n })\n})\n\nwss.on('connection', function (ws, request) {\n const userId = request.session.userId\n\n map.set(userId, ws)\n\n ws.on('message', function (message) {\n //\n // Here we can now use session parameters.\n //\n console.log(`Received message ${message} from user ${userId}`)\n })\n\n ws.on('close', function () {\n map.delete(userId)\n })\n})\n\nserver.listen(3000)\n\nexport default server\n```\n\n**My nuxt.config.js file**\n\n```\nexport default {\n /*\n ** Nuxt rendering mode\n ** See https://nuxtjs.org/api/configuration-mode\n */\n mode: 'universal',\n /*\n ** Nuxt target\n ** See https://nuxtjs.org/api/configuration-target\n */\n target: 'server',\n /*\n ** Headers of the page\n ** See https://nuxtjs.org/api/configuration-head\n */\n head: {\n title: process.env.npm_package_name || '',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n {\n hid: 'description',\n name: 'description',\n content: process.env.npm_package_description || '',\n },\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],\n },\n /*\n ** Global CSS\n */\n css: [],\n /*\n ** Plugins to load before mounting the App\n ** https://nuxtjs.org/guide/plugins\n */\n plugins: [],\n /*\n ** Auto import components\n ** See https://nuxtjs.org/api/configuration-components\n */\n components: true,\n /*\n ** Nuxt.js dev-modules\n */\n buildModules: [\n // Doc: https://github.com/nuxt-community/eslint-module\n '@nuxtjs/eslint-module',\n // Doc: https://github.com/nuxt-community/stylelint-module\n '@nuxtjs/stylelint-module',\n ],\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://axios.nuxtjs.org/usage\n '@nuxtjs/axios',\n '@nuxtjs/pwa',\n ],\n /*\n ** Axios module configuration\n ** See https://axios.nuxtjs.org/options\n */\n axios: {},\n /*\n ** Build configuration\n ** See https://nuxtjs.org/api/configuration-build/\n */\n build: {},\n serverMiddleware: ['~/api/app'],\n}\n```\n\nhttps://i.sstatic.net/Ggelo.png\n\n**How do I expose the websocket server from app.js?**\n\n========================================\n\nCode:\n```text\nimport http from 'http'\nimport logger from 'express-pino-logger'\nimport express from 'express'\nimport cookieParser from 'cookie-parser'\nimport WebSocket from 'ws'\nconst app = express()\nconst sessionParser = cookieParser()\nconst map = new Map()\napp.use(logger())\napp.use(express.json())\napp.use(express.urlencoded({ extended: true }))\napp.use(sessionParser)\napp.use('/v1', (req, res) => res.json('hello'))\n\nconst server = http.createServer(app)\nconst wss = new WebSocket.Server({ noServer: true })\n\nwss.on('connection', function connection(ws, request, client) {\n ws.on('message', function message(msg) {\n console.log(`Received message ${msg} from user ${client}`)\n })\n})\n\nserver.on('upgrade', function (request, socket, head) {\n console.log('Parsing session from request...')\n\n sessionParser(request, {}, () => {\n if (!request.session.userId) {\n socket.destroy()\n return\n }\n\n console.log('Session is parsed!')\n\n wss.handleUpgrade(request, socket, head, function (ws) {\n wss.emit('connection', ws, request)\n })\n })\n})\n\nwss.on('connection', function (ws, request) {\n const userId = request.session.userId\n\n map.set(userId, ws)\n\n ws.on('message', function (message) {\n //\n // Here we can now use session parameters.\n //\n console.log(`Received message ${message} from user ${userId}`)\n })\n\n ws.on('close', function () {\n map.delete(userId)\n })\n})\n\nserver.listen(3000)\n\nexport default server\n```\n\n```text\nexport default {\n /*\n ** Nuxt rendering mode\n ** See https://nuxtjs.org/api/configuration-mode\n */\n mode: 'universal',\n /*\n ** Nuxt target\n ** See https://nuxtjs.org/api/configuration-target\n */\n target: 'server',\n /*\n ** Headers of the page\n ** See https://nuxtjs.org/api/configuration-head\n */\n head: {\n title: process.env.npm_package_name || '',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n {\n hid: 'description',\n name: 'description',\n content: process.env.npm_package_description || '',\n },\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],\n },\n /*\n ** Global CSS\n */\n css: [],\n /*\n ** Plugins to load before mounting the App\n ** https://nuxtjs.org/guide/plugins\n */\n plugins: [],\n /*\n ** Auto import components\n ** See https://nuxtjs.org/api/configuration-components\n */\n components: true,\n /*\n ** Nuxt.js dev-modules\n */\n buildModules: [\n // Doc: https://github.com/nuxt-community/eslint-module\n '@nuxtjs/eslint-module',\n // Doc: https://github.com/nuxt-community/stylelint-module\n '@nuxtjs/stylelint-module',\n ],\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://axios.nuxtjs.org/usage\n '@nuxtjs/axios',\n '@nuxtjs/pwa',\n ],\n /*\n ** Axios module configuration\n ** See https://axios.nuxtjs.org/options\n */\n axios: {},\n /*\n ** Build configuration\n ** See https://nuxtjs.org/api/configuration-build/\n */\n build: {},\n serverMiddleware: ['~/api/app'],\n}\n```\n\n========================================\n\nComments:\n- tried removing server.listen(3000) after figuring out nuxt must be calling it on its own still same error\n- Back here to up vote this. I had to add `export default app;` at the bottom of the file. Weird thought because other Nuxt SM I have I don't need to do that.","metadata":{"transformedAt":"2026-08-18T18:33:07.882Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":301,"estimatedTokens":1704}}619{"id":"stack-62487122","source":"stackoverflow","questionId":62487122,"title":"TypeError: Cannot read property 'get' of undefined - Vue-resource and Nuxt","tags":["javascript","vue.js","vuejs2","vuex","nuxt.js"],"text":"Title: TypeError: Cannot read property 'get' of undefined - Vue-resource and Nuxt\nTags: javascript, vue.js, vuejs2, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nbeen receiveing error like this in my Vuex Store\n\nTypeError: Cannot read property 'get' of undefined\n\nI already have added a plugin for the vue-resource\n\nThis is my code that is receiving that error\n\n```\nasync getAllStudents({commit}) {\nawait Vue.$http.get(`/api/students`)\n .then((res) => {\n if (res.status === 200) {\n commit('setAllStudents', res.data)\n }\n }).catch(function(error) {\n console.log(error);\n });\n```\n\n},\n\n========================================\n\nTop Answer:\nTry this, use `this._vm` instead of `Vue`:\n\n```\nasync getAllStudents({commit}) {\nawait this._vm.$http.get(`/api/students`)\n .then((res) => {\n if (res.status === 200) {\n commit('setAllStudents', res.data)\n }\n }).catch(function(error) {\n console.log(error);\n });\n},\n```\n\n========================================\n\nCode:\n```text\nasync getAllStudents({commit}) {\nawait Vue.$http.get(`/api/students`)\n .then((res) => {\n if (res.status === 200) {\n commit('setAllStudents', res.data)\n }\n }).catch(function(error) {\n console.log(error);\n });\n```\n\n```text\nasync getAllStudents({commit}) {\nawait this.$axios.get(`/api/students`)\n .then((res) => {\n if (res.status === 200) {\n commit('setAllStudents', res.data)\n }\n }).catch(function(error) {\n console.log(error);\n });\n},\n```\n\n```text\nconst routerBase = process.env.DEPLOY_ENV === 'GH_PAGES' ? {\n router: {\n base: '/boussadjra-brahim/'\n }\n} : {}\n\nexport default {\n mode: 'universal',\n /*\n ** Headers of the page\n */\n head: {\n titleTemplate: '%s - ' + 'Boussadjra Brahim',\n title: 'Boussadjra Brahim' || '',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: process.env.npm_package_description || '' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ],\n\n },\n\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n ],\n\n ....\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://axios.nuxtjs.org/usage\n '@nuxtjs/axios',\n ],\n\n\n ....\n}\n```\n\n```text\nthis\n```\n\n```text\nVue\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nasync getAllStudents({commit}) {\nawait this._vm.$http.get(`/api/students`)\n .then((res) => {\n if (res.status === 200) {\n commit('setAllStudents', res.data)\n }\n }).catch(function(error) {\n console.log(error);\n });\n},\n```\n\n```text\nthis._vm\n```\n\n```text\nVue\n```\n\n========================================\n\nComments:\n- In which file are you doing this?\n- In my store file - /store/enrollment\n- thanks bro. Tried this one and it works but I want to use axios more\n- The point is how to use vue instance, so you can use axios with `this._vm.$axios.get`","metadata":{"transformedAt":"2026-08-18T18:33:07.882Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":159,"estimatedTokens":724}}620{"id":"stack-59147460","source":"stackoverflow","questionId":59147460,"title":"why i get, Cannot set property of undefined","tags":["javascript","vue.js","nuxt.js"],"text":"Title: why i get, Cannot set property of undefined\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm working on small project using **nuxt** **js** and **axios** and i try to put the response data in my `formFields` object but i get undefined error message in the console, since i have already declared `formFields` in data as you can see : \n\nthis is my code : \n\n```\neditCustomers (customerId, submit = false) {\n this.editMode = true\n this.customerId = customerId\n if (submit === 1) {\n // this.$Progress.start()\n this.$axios.$post('mydomain.com' + customerId + '/1', $('#add-customer').serialize()).then(function (data) {\n this.validation(data)\n // another form validation again using the helper\n this.refresh = true\n })\n // this.$Progress.finish()\n } else {\n this.$axios.$get('mydomain.com' + customerId).then(function (data) {\n this.formFields = data.customers[0]\n })\n }\n}\n```\n\nmy data variables : \n\n```\ndata () {\nreturn {\n laravelData: {},\n formFields: {},\n search: null,\n editMode: true,\n customerId: null,\n refresh: false\n}\n }\n```\n\nas you can see i have already declared data, but when i do `this.formFields = data.customers[0]`\ni get this error message : \n\n```\nUncaught (in promise) TypeError: Cannot set property 'formFields' of undefined\n```\n\n========================================\n\nTop Answer:\nIn JavaScript, `this` refers to the current target of the current scope, when using the `function` keyword to declare a function, `this` refers to the object with which the function is invoked.\n\nThe way you have written your code, `this` no longer refers to the Vue instance, `this` refers to `undefined` (because the callback is presumably invoked without a `this` arg), try capturing `this` outside of the function and enclosing it in its closure:\n\n```\neditCustomers (customerId, submit = false) {\n this.editMode = true\n this.customerId = customerId\n const vm = this; // vm = this = Vue instance\n if (submit === 1) {\n // this.$Progress.start()\n\n this.$axios.$post('mydomain.com' + customerId + '/1', $('#add-customer').serialize()).then(function (data) {\n // vm = Vue instance; this = undefined\n vm.validation(data)\n // another form validation again using the helper\n vm.refresh = true\n })\n // this.$Progress.finish()\n } else {\n this.$axios.$get('mydomain.com' + customerId).then(function (data) {\n // vm = Vue instance; this = undefined\n vm.formFields = data.customers[0]\n })\n }\n}\n```\n\nETA:\nFor a better understanding of this:\n\n\r\n\r\n\n```\nfunction myName() { return this.name};\r\nvar obj = {name:'test'};\r\nvar objName = myName.bind(obj); // a new function where the `this` arg is bound to `obj`\r\nvar text = objName(); // text === 'test'\r\nconsole.log(text);\n```\n\n========================================\n\nCode:\n```text\neditCustomers (customerId, submit = false) {\n this.editMode = true\n this.customerId = customerId\n if (submit === 1) {\n // this.$Progress.start()\n this.$axios.$post('mydomain.com' + customerId + '/1', $('#add-customer').serialize()).then(function (data) {\n this.validation(data)\n // another form validation again using the helper\n this.refresh = true\n })\n // this.$Progress.finish()\n } else {\n this.$axios.$get('mydomain.com' + customerId).then(function (data) {\n this.formFields = data.customers[0]\n })\n }\n}\n```\n\n```text\ndata () {\nreturn {\n laravelData: {},\n formFields: {},\n search: null,\n editMode: true,\n customerId: null,\n refresh: false\n}\n }\n```\n\n```text\nUncaught (in promise) TypeError: Cannot set property 'formFields' of undefined\n```\n\n```text\nformFields\n```\n\n```text\nformFields\n```\n\n```text\nthis.formFields = data.customers[0]\n```\n\n```text\nthis.$axios.$get('mydomain.com' + customerId).then(function (data) {\n this.formFields = data.customers[0]\n})\n```\n\n```text\nthis.$axios.$get('mydomain.com' + customerId).then((data) => {\n // Now you can access your class instance\n this.formFields = data.customers[0]\n})\n```\n\n```js\neditCustomers (customerId, submit = false) {\n this.editMode = true\n this.customerId = customerId\n const vm = this; // vm = this = Vue instance\n if (submit === 1) {\n // this.$Progress.start()\n\n this.$axios.$post('mydomain.com' + customerId + '/1', $('#add-customer').serialize()).then(function (data) {\n // vm = Vue instance; this = undefined\n vm.validation(data)\n // another form validation again using the helper\n vm.refresh = true\n })\n // this.$Progress.finish()\n } else {\n this.$axios.$get('mydomain.com' + customerId).then(function (data) {\n // vm = Vue instance; this = undefined\n vm.formFields = data.customers[0]\n })\n }\n}\n```\n\n```js\nfunction myName() { return this.name};\nvar obj = {name:'test'};\nvar objName = myName.bind(obj); // a new function where the `this` arg is bound to `obj`\nvar text = objName(); // text === 'test'\nconsole.log(text);\n```\n\n```text\nthis\n```\n\n```text\nfunction\n```\n\n```text\nthis\n```\n\n```text\nthis\n```\n\n```text\nthis\n```\n\n```text\nundefined\n```\n\n```text\nthis\n```\n\n```text\nthis\n```\n\n========================================\n\nComments:\n- Likely because your code runs in strict mode where `this` in a *normal function call* is `undefined`. What do you expect `this` to refer to? Have a look at How to access the correct `this` inside a callback?\n- Every time you enter a new function the value of `this` changes. If you replace your callback functions with arrow functions the outer `this` value will be preserved. So change `function (data) {` to `data => {`.\n- Does this answer your question? How to access the correct `this` inside a callback?","metadata":{"transformedAt":"2026-08-18T18:33:07.882Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":231,"estimatedTokens":1388}}621{"id":"stack-68518805","source":"stackoverflow","questionId":68518805,"title":"How to exclude specific component from caching Using Nuxt.js keep-alive props?","tags":["vue.js","nuxt.js"],"text":"Title: How to exclude specific component from caching Using Nuxt.js keep-alive props?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have trouble with Nuxt.js keep-alive prop, I am trying to cache all components except one, and load dynamic data again.\nBut all components are cached, I can't figure out what am I doing wrong.\nIs this the correct way to use keep-alive in Nuxt.js?\n\n`Default layout`\n\n```\n\n \n \n \n\n```\n\n`Inside basket`\n\n```\n\n \n \n\n### basket\n\n {{items}}\n \n\nexport default { \n async fetch() {\n let resp = await this.$axios.$get('api/items')\n this.items = resp.data\n }, \n fetchOnServer:false,\n}\n\n```\n\nVue devtools\n\nhttps://i.sstatic.net/el62D.png\n\n========================================\n\nCode:\n```html\n<template>\n <div>\n <Nuxt keep-alive :keep-alive-props=\"{exclude: ['basket']}\" />\n </div>\n</template>\n```\n\n```html\n<template>\n <div>\n <h1>basket</h1>\n {{items}}\n </div>\n</template>\n\n<script>\nexport default { \n async fetch() {\n let resp = await this.$axios.$get('api/items')\n this.items = resp.data\n }, \n fetchOnServer:false,\n}\n</script>\n```\n\n```text\nDefault layout\n```\n\n```text\nInside basket\n```\n\n```text\npages/\n - index.vue\n - basket.vue\n```\n\n```html\n<Nuxt keep-alive :keep-alive-props=\"{exclude: ['pages/basket.vue']}\" />\n```\n\n```text\nkeep-alive\n```\n\n```text\nbasket\n```\n\n```text\nbasket\n```\n\n```text\n\"pages/basket.vue\"\n```\n\n========================================\n\nComments:\n- Can you give a `name: 'basket'` to your Basket component and see if this changes anything?\n- I tried but to no avail, the API is not called during routing\n- What? Can you please make a minimal reproducible example and explain a bit better what you want to do here? It's not clear and we're missing info.\n- The Nuxt documentation suggests that you can exclude non-page components too. `:keep-alive-props=\"{ exclude: ['modal'] }\"`, `modal` is obviously not a page component.","metadata":{"transformedAt":"2026-08-18T18:33:07.882Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":116,"estimatedTokens":477}}622{"id":"stack-51008997","source":"stackoverflow","questionId":51008997,"title":"Nuxt, splitting up Vuex store into separate files gives error: unknown mutation type: login","tags":["javascript","vuex","nuxt.js","vuex-modules"],"text":"Title: Nuxt, splitting up Vuex store into separate files gives error: unknown mutation type: login\nTags: javascript, vuex, nuxt.js, vuex-modules\nSource: Stack Overflow\n\nQuestion:\nI'm trying to **split up my Nuxt Vuex store files into separate files**. And NOT have all **Vuex** `getters`, `mutations` and `actions` into one huge file. This demo project is on Github by the way.\n\nI'v read this official Nuxt Vuex Store documentation; but can't seem to get it working. It's a bit vague on where to put stuff.\n\nI have the following in these files:\n\n### Below is my: store/index.js\n\n```\nimport Vue from \"vue\";\nimport Vuex from \"vuex\";\nimport Auth from \"./modules/auth\";\n\nVue.use(Vuex);\n\nexport const store = () => {\n return new Vuex.Store({\n state: {\n\n },\n modules: {\n Auth\n }\n })\n}\n```\n\n### This is in my: store/auth.js\n\n```\nconst state = () => {\n username: null\n};\n\nconst getters = {\n username: state => {\n return state.username;\n },\n isAuthenticated: state => {\n return state.username != null;\n }\n};\n\nconst mutations = {\n login: (vuexContext, username) => {\n vuexContext.username = username;\n this.$router.push(\"/dashboard\");\n },\n logout: vuexContext => {\n vuexContext.username = null;\n this.$router.push(\"/\");\n }\n};\n\nconst actions = {\n\n};\n\nexport default {\n state,\n getters,\n mutations,\n actions,\n};\n```\n\n### And finally in my: pages/index.vue\n\nThis is where I'm calling that **login** mutation:\n\n```\n\n export default {\n layout: \"non-logged-in\",\n data() {\n return {\n username: null\n }\n },\n methods: {\n onSubmit() {\n this.$store.commit(\"login\", this.username);\n }\n }\n }\n\n```\n\n### The error I'm getting:\n\n`[vuex] unknown mutation type: login`\n\nWhat am I doing wrong here? I thought i'm importing all the stuff correctly in the `store/index.js`\n\n========================================\n\nTop Answer:\nSo as @jeremy.raza described this is what I changed in order to get it working:\n\n### store/index.js\n\n```\nimport Vue from \"vue\";\nimport Vuex from \"vuex\";\nimport Auth from \"./modules/auth\";\n\nVue.use(Vuex)\n\nconst store = () => {\n return new Vuex.Store({\n state: {\n\n },\n modules: {\n Auth\n }\n })\n}\n\nexport default store;\n```\n\n### Changes in the store/auth.js\n\nNote the changes in how I wrote the `state`, `getters` and `mutations` method notation.\n\n```\nconst state = () => ({\n username: null\n});\n\nconst getters = {\n username(state) {\n return state.username;\n },\n isAuthenticated(state) {\n return state.username != null;\n }\n};\n\nconst mutations = {\n login(vuexContext, username) {\n vuexContext.username = username;\n this.$router.push(\"/dashboard\");\n },\n logout(vuexContext) {\n vuexContext.username = null;\n this.$router.push(\"/\");\n }\n};\n\nconst actions = {\n\n};\n\nexport default {\n state,\n getters,\n mutations,\n actions,\n};\n```\n\n========================================\n\nCode:\n```text\nimport Vue from \"vue\";\nimport Vuex from \"vuex\";\nimport Auth from \"./modules/auth\";\n\nVue.use(Vuex);\n\nexport const store = () => {\n return new Vuex.Store({\n state: {\n\n },\n modules: {\n Auth\n }\n })\n}\n```\n\n```text\nconst state = () => {\n username: null\n};\n\nconst getters = {\n username: state => {\n return state.username;\n },\n isAuthenticated: state => {\n return state.username != null;\n }\n};\n\nconst mutations = {\n login: (vuexContext, username) => {\n vuexContext.username = username;\n this.$router.push(\"/dashboard\");\n },\n logout: vuexContext => {\n vuexContext.username = null;\n this.$router.push(\"/\");\n }\n};\n\nconst actions = {\n\n};\n\nexport default {\n state,\n getters,\n mutations,\n actions,\n};\n```\n\n```text\n<script>\n export default {\n layout: \"non-logged-in\",\n data() {\n return {\n username: null\n }\n },\n methods: {\n onSubmit() {\n this.$store.commit(\"login\", this.username);\n }\n }\n }\n</script>\n```\n\n```text\ngetters\n```\n\n```text\nmutations\n```\n\n```text\nactions\n```\n\n```text\n[vuex] unknown mutation type: login\n```\n\n```text\nstore/index.js\n```\n\n```text\nexport default store\n```\n\n```text\nimport Vue from \"vue\";\nimport Vuex from \"vuex\";\nimport Auth from \"./modules/auth\";\n\nVue.use(Vuex)\n\nconst store = () => {\n return new Vuex.Store({\n state: {\n\n },\n modules: {\n Auth\n }\n })\n}\n\nexport default store;\n```\n\n```text\nconst state = () => ({\n username: null\n});\n\nconst getters = {\n username(state) {\n return state.username;\n },\n isAuthenticated(state) {\n return state.username != null;\n }\n};\n\nconst mutations = {\n login(vuexContext, username) {\n vuexContext.username = username;\n this.$router.push(\"/dashboard\");\n },\n logout(vuexContext) {\n vuexContext.username = null;\n this.$router.push(\"/\");\n }\n};\n\nconst actions = {\n\n};\n\nexport default {\n state,\n getters,\n mutations,\n actions,\n};\n```\n\n```text\nstate\n```\n\n```text\ngetters\n```\n\n```text\nmutations\n```\n\n========================================\n\nComments:\n- Thank you! This worked great. Together with some other changes; I got it working now.\n- Thanks for this Dennis Burger. I managed to use Vuex in module mode.\n- its getting deprecated, what will be the new way to implement this? As of Nuxt 3, it will be removed.","metadata":{"transformedAt":"2026-08-18T18:33:07.882Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":345,"estimatedTokens":1322}}623{"id":"stack-59782289","source":"stackoverflow","questionId":59782289,"title":"VueJS render property inside html string using v-html","tags":["vue.js","nuxt.js"],"text":"Title: VueJS render property inside html string using v-html\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nhttps://i.sstatic.net/1Ga8F.png\n\nI have a string of html where I get from Editor and stored in the database.\n\n`\n\n### ***Profile Of User:***\n\n{{user}}\n\n`\n\n**I want to retrieve it from the database and render it as HTML. when I use v-html, it will be rendered as:** \n\n```\n\n```\n\n### ***Profile Of User:***\n\n{{user}}\n\n**How to render {{hello}} from data property if I have data property like this:** \n\n```\ndata() {\n return {\n user: \"Lim Socheat\",\n content:\"\n\n### ***Profile Of User:***\n\n{{user}}\n\n\"\n };\n },\n```\n\n**Expected Result:** \n\n### ***Profile Of User:***\n\nLim Socheat\n\nbecause *{{ user }}* will be rendered as *Lim Socheat*\n\n========================================\n\nTop Answer:\nI found the answer. hope it helps someone in the future. \n\nOrginal post: https://forum.vuejs.org/t/evaluate-string-as-vuejs-on-vuejs2-x/20392/2 \n\nVueJS - Interpolate a string within a string\n\n```\n\n \n \n Print\n \n \n \n \n \n\n \n export default {\n data() {\n return {\n hello: \"HELLO DATA\",\n user: \"Lim Socheat\",\n content: \"\"\n };\n },\n\n methods: {\n getLayout() {\n this.$axios\n .$get(\"/api/layout/reciept\", {\n params: {\n type: \"reciept\"\n }\n })\n .then(response => {\n this.content = response.content;\n })\n .catch(error => {\n this.$toast.error(error);\n });\n },\n\n evalInContext(string) {\n try {\n return eval(\"this.\" + string);\n } catch (error) {\n try {\n return eval(string);\n } catch (errorWithoutThis) {\n console.warn(\n \"Error en script: \" + string,\n errorWithoutThis\n );\n return null;\n }\n }\n },\n parse(string) {\n return string.replace(/{{.*?}}/g, match => {\n var expression = match.slice(2, -2);\n\n return this.evalInContext(expression);\n });\n }\n },\n\n computed: {\n id() {\n return this.$route.params.id;\n }\n },\n\n watch: {\n id: {\n handler() {\n this.getLayout();\n },\n immediate: true\n }\n }\n };\n \n```\n\n========================================\n\nCode:\n```text\n<v-card-text v-html=\"content\"></v-card-text>\n```\n\n```text\ndata() {\n return {\n user: \"Lim Socheat\",\n content:\"<h3><a href=\"#\" rel=\"noopener noreferrer nofollow\"><em><strong>Profile Of User:</strong></em></a></h3><p></p><p>{{user}}</p>\"\n };\n },\n```\n\n```text\n<h3><a href=\"#\" rel=\"noopener noreferrer nofollow\"><em><strong>Profile Of User:</strong></em></a></h3><p></p><p>{{user}}</p>\n```\n\n```text\ncomputed: {\n content() {\n return '<h3><a href=\"#\" rel=\"noopener noreferrer nofollow\"><em><strong>Profile Of User:</strong></em></a></h3><p></p><p>' + this.user + '</p>';\n }\n }\n```\n\n```text\ncomputed: {\n content() {\n // keep a map of all your variables\n let valueMap = {\n user: this.user,\n otherKey: 250\n };\n let value = '<h3><a href=\"#\" rel=\"noopener noreferrer nofollow\"><em><strong>Profile Of User:</strong></em></a></h3><p></p><p>{{user}}</p>';\n let allKeys = Object.keys(valueMap);\n allKeys.forEach((key) => {\n var myRegExp = new RegExp('{{' + key + '}}','i');\n value = value.replace(myRegExp, valueMap[key]);\n });\n return value;\n }\n }\n```\n\n```text\n<template>\n <v-container>\n <v-card>\n <v-card-title>Print</v-card-title>\n <v-divider></v-divider>\n <v-card-text v-html=\"parse(content)\"></v-card-text>\n </v-card>\n </v-container>\n </template>\n\n <script>\n export default {\n data() {\n return {\n hello: \"HELLO DATA\",\n user: \"Lim Socheat\",\n content: \"\"\n };\n },\n\n methods: {\n getLayout() {\n this.$axios\n .$get(\"/api/layout/reciept\", {\n params: {\n type: \"reciept\"\n }\n })\n .then(response => {\n this.content = response.content;\n })\n .catch(error => {\n this.$toast.error(error);\n });\n },\n\n evalInContext(string) {\n try {\n return eval(\"this.\" + string);\n } catch (error) {\n try {\n return eval(string);\n } catch (errorWithoutThis) {\n console.warn(\n \"Error en script: \" + string,\n errorWithoutThis\n );\n return null;\n }\n }\n },\n parse(string) {\n return string.replace(/{{.*?}}/g, match => {\n var expression = match.slice(2, -2);\n\n return this.evalInContext(expression);\n });\n }\n },\n\n computed: {\n id() {\n return this.$route.params.id;\n }\n },\n\n watch: {\n id: {\n handler() {\n this.getLayout();\n },\n immediate: true\n }\n }\n };\n </script>\n```\n\n```text\n<template>\n <v-container>\n <v-card>\n <v-card-title>Print</v-card-title>\n <v-divider></v-divider>\n <v-card-text>\n <component :is=\"dynamicComponent\"></component>\n </v-card-text>\n </v-card>\n </v-container>\n</template>\n\n<script>\nimport { reactive, shallowRef, ref } from 'vue'\nexport default {\n data() {\n return {\n hello: \"HELLO DATA\",\n user: \"Lim Socheat\",\n content: shallowRef(null)\n };\n },\n\n methods: {\n getLayout() {\n this.$axios\n .$get(\"/api/layout/reciept\", {\n params: {\n type: \"reciept\"\n }\n })\n .then(response => {\n this.content = response.content;\n })\n .catch(error => {\n this.$toast.error(error);\n });\n },\n },\n\n computed: {\n id() {\n return this.$route.params.id;\n },\n dynamicComponent() {\n let $this = this;\n return {\n data: function () {\n return {\n hello: ref($this.hello),\n user: ref($this.user),\n }\n },\n template: $this.content ? $this.content : \"loading...\"\n };\n }\n },\n\n watch: {\n id: {\n handler() {\n this.getLayout();\n },\n immediate: true\n }\n }\n};\n</script>\n```\n\n========================================\n\nComments:\n- Hi, in this scenario, I can not do that. Because I get HTML STRING from the database, where I can dynamically change from Editor. I have edited the question.\n- @LimSocheat I have updated the code. Please check now.\n- Hi, Thanks for answering, your answer gives me the idea and solves my problem.","metadata":{"transformedAt":"2026-08-18T18:33:07.882Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":343,"estimatedTokens":1783}}624{"id":"stack-68458274","source":"stackoverflow","questionId":68458274,"title":"How to prerender content with Nuxt Js from own Api?","tags":["vue.js","nuxt.js","vuex"],"text":"Title: How to prerender content with Nuxt Js from own Api?\nTags: vue.js, nuxt.js, vuex\nSource: Stack Overflow\n\nQuestion:\nI have a Vuex store\n\n`/store/articles.js`\n\n```\nexport const state = () => ({\n article:'',\n})\nexport const mutations = {\n setArticle(state, payload) {\n state.article= payload.data;\n }\n}\nexport const actions = {\n async getArticle ({ commit }, id) {\n try {\n const { data } = await axios.post('http://test.local/api/getArticle',id);\n commit('setArticle', { data })\n } catch (e) {\n console.log(e);\n }\n }\n}\n```\n\nmy API returns a JSON like example this\n\n```\n{\n \"id\": 1,\n \"title\": \"some title\",\n \"content\": \"some content\",\n \"image\": \"article_img1.jpg\"\n}\n```\n\nthere is my page and content from API\n\n`/pages/article/slug.vue`\n\n```\n\n \n \n\n### {{ article.title }}\n\n \n \n \n\nexport default {\n computed:{\n article(){\n return this.$store.dispatch('getArticle',1)\n },\n },\n}\n\n```\n\nContent appears fine,\nbut when I look at the content page code, there is no content.\nHow to make the content prerendered, on this way?\n\nAnd how to generate static pages from an API, do I need to use @nuxt/content ? I am trying this, but it looks like works only from `.md` or `.json` files, I don't understand how to generate automatically with some API fetching.\n\n========================================\n\nTop Answer:\nYou can totally generate pages from an API without the need of `nuxt/content`. I have written an in-depth answer here: Rewriting to a 404 page doesn't work if the page doesn't exist on a site created with SSG in Nuxt.js\n\nShowing how to achieve a clean generation of your pages during build time.\n\nOtherwise, you can also the steps described into the documentation here: https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-generate#function-which-returns-a-promise\n\nAlso, be sure to have `ssr` set to `true` in your `nuxt.config.js` file.\n\n========================================\n\nCode:\n```js\nexport const state = () => ({\n article:'',\n})\nexport const mutations = {\n setArticle(state, payload) {\n state.article= payload.data;\n }\n}\nexport const actions = {\n async getArticle ({ commit }, id) {\n try {\n const { data } = await axios.post('http://test.local/api/getArticle',id);\n commit('setArticle', { data })\n } catch (e) {\n console.log(e);\n }\n }\n}\n```\n\n```json\n{\n \"id\": 1,\n \"title\": \"some title\",\n \"content\": \"some content\",\n \"image\": \"article_img1.jpg\"\n}\n```\n\n```html\n<template>\n <div> \n <h4>{{ article.title }}</h4>\n <img :src=\"'/images/'+article.image\" />\n <div v-html=\"article.content\" />\n </div>\n</template>\n\n<script>\nexport default {\n computed:{\n article(){\n return this.$store.dispatch('getArticle',1)\n },\n },\n}\n</script>\n```\n\n```text\n/store/articles.js\n```\n\n```text\n/pages/article/slug.vue\n```\n\n```text\n.md\n```\n\n```text\n.json\n```\n\n```text\nasync asyncData({params, store}) {\n articles: await store.dispatch('articles/articlesById', {'id': params.id, \n return {articles};\n },\n```\n\n```text\nnuxt/content\n```\n\n```text\nssr\n```\n\n```text\ntrue\n```\n\n```text\nnuxt.config.js\n```\n\n```html\n<template>\n <div> \n <h4>{{ article.title }}</h4>\n <img :src=\"'/images/'+article.image\" />\n <div v-html=\"article.content\" />\n </div>\n</template>\n\n<script>\nexport default {\n computed: {\n articles() {\n return this.$store.state.article\n }\n },\n async asyncData() {\n await this.$store.dispatch('getArticle',1)\n },\n}\n</script>\n```\n\n```text\nasyncData\n```\n\n========================================\n\nComments:\n- This will not prerender it ahead of time.\n- async asyncData({params, store}) { articles: await store.dispatch('articles/articlesById', {'id': params.id, return {articles}; }, this works\n- Yes that depends on implementation. Feel free to \"edit\" my answer and accept if it helped","metadata":{"transformedAt":"2026-08-18T18:33:07.882Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":208,"estimatedTokens":948}}625{"id":"stack-60561167","source":"stackoverflow","questionId":60561167,"title":"Bundling a plugin with Rollup but having duplicate Vue.js package imported in the client app's bundle (Nuxt)","tags":["vue.js","webpack","plugins","nuxt.js","rollup"],"text":"Title: Bundling a plugin with Rollup but having duplicate Vue.js package imported in the client app's bundle (Nuxt)\nTags: vue.js, webpack, plugins, nuxt.js, rollup\nSource: Stack Overflow\n\nQuestion:\nDear Stack Overflow / Vue.js / Rollup community\n\nThis could be a noob question for the master plugin developers working with Vue and Rollup. I will write the question very explicitly hoping that it could help other noobs like me in the future.\n\nI have simple plugin that helps with form validation. One of the components in this plugin imports Vue in order to programatically create a component and append to DOM on mount like below:\n\n```\nimport Vue from 'vue'\nimport Notification from './Notification.vue' /* a very simple Vue component */\n...\nmounted() {\n const NotificationClass = Vue.extend(Notification)\n const notificationInstance = new NotificationClass({ propsData: { name: 'ABC' } })\n notificationInstance.$mount('#something')\n}\n```\n\nThis works as expected, and this plugin is bundled using Rollup with a config like this:\n\n```\nimport vue from 'rollup-plugin-vue'\nimport babel from 'rollup-plugin-babel'\nimport { terser } from 'rollup-plugin-terser'\nimport resolve from 'rollup-plugin-node-resolve'\nimport commonjs from 'rollup-plugin-commonjs'\n\nexport default {\n input: 'src/index.js',\n output: {\n name: 'forms',\n globals: {\n vue: 'Vue'\n }\n },\n plugins: [\n vue(),\n babel(),\n resolve(),\n commonjs(),\n terser()\n ],\n external: ['vue']\n}\n```\n\nAs you can see, Vue.js is getting externalised in this bundle. The aim (and the assumption) is that the client app that imports this plugin will be running on Vue, therefore there's no need to bundle it here (assumption). \n\nThe very simple src/index.js that the bundler uses is below:\n\n```\nimport Form from './Form.vue'\n\nexport default {\n install(Vue, _) {\n Vue.component('bs-form', Form)\n }\n}\n```\n\nRollup creates 2 files (one esm and one umd) and references them in in the plugins package.json file like below:\n\n```\n\"name\": \"bs-forms\",\n \"main\": \"./dist/umd.js\",\n \"module\": \"./dist/esm.js\",\n \"files\": [\n \"dist/*\"\n ],\n \"scripts\": {\n \"build\": \"npm run build:umd & npm run build:es\",\n \"build:es\": \"rollup --config rollup.config.js --format es --file dist/esm.js\",\n \"build:umd\": \"rollup --config rollup.config.js --format umd --file dist/umd.js\"\n }\n```\n\nEverything works as expected up to this point and the bundles are generated nicely.\n\nThe client app (Nuxt SSR) imports this plugin (using npm-link since it's in development) with a very simple import in a plugin file:\n\n```\n/* main.js*/\nimport Vue from 'vue'\n\nimport bsForms from 'bs-forms'\nVue.use(bsForms)\n```\n\nThis plugin file (main.js) is added to nuxt.config.js as a plugin:\n\n```\n// Nuxt Plugins\n...\nplugins: [{src: '~/plugins/main'}]\n...\n```\n\nEverything still works as expected but here comes the problem:\n\nhttps://i.sstatic.net/by2DH.png\nSince the clients is a Nuxt app, the Vue is imported by default of course but the externalised Vue module (by the forms plugin) is also imported in the client. Therefore there is a duplication of this package in the client bundle.\n\nI guess the client app can configure its webpack config in order to remove this duplicated module. Perhaps by using something like a Dedupe plugin or something? Can someone suggests how to best handle situation like these?\n\nBut what I really want to learn, is the best practice of bundling the plugin at the first place, so that the client doesn't have to change anything in its config and simply imports this plugin and move on. \n\nI know that importing the Vue.js in the plugin may not be a great thing to do at the first place. But there could be other reasons for an import like this as well, for example imagine that the plugin could be written in Typescript and Vue.js / Typescript is written by using Vue.extend statements (see below) which also imports Vue (in order to enable type interface):\n\n```\nimport Vue from 'vue'\n\nconst Component = Vue.extend({\n // type inference enabled\n})\n```\n\nSo here's the long question. Please masters of Rollup, help me and the community out by suggesting best practice approaches (or your approaches) to handle situations like these.\n\nThank you!!!!\n\n========================================\n\nTop Answer:\nI had the same problem and I found this answer of @vatson very helpful\n\nYour problem is the combination of \"npm link\", the nature of nodejs module loading and the vue intolerance to multiple instances from different places.\n\nShort introduction how import in nodejs works. If your script has some kind of library import, then nodejs initially looks in the local node_modules folder, if local node_modules doesn't contain required dependency then nodejs goes to the folder above to find node_modules and your imported dependency there.\n\nYou do not need to publish your package on NPM. It is enough if you generate your package locally using `npm pack` and then install it in your other project `npm install /absolute_path_to_your_local_package/your_package_name.tgz`. If you update something in your package, you can reinstall it in your other project and everything should work.\n\nHere is the source about the difference between `npm pack` and `npm link` https://stackoverflow.com/a/50689049/6072503.\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\nimport Notification from './Notification.vue' /* a very simple Vue component */\n...\nmounted() {\n const NotificationClass = Vue.extend(Notification)\n const notificationInstance = new NotificationClass({ propsData: { name: 'ABC' } })\n notificationInstance.$mount('#something')\n}\n```\n\n```text\nimport vue from 'rollup-plugin-vue'\nimport babel from 'rollup-plugin-babel'\nimport { terser } from 'rollup-plugin-terser'\nimport resolve from 'rollup-plugin-node-resolve'\nimport commonjs from 'rollup-plugin-commonjs'\n\nexport default {\n input: 'src/index.js',\n output: {\n name: 'forms',\n globals: {\n vue: 'Vue'\n }\n },\n plugins: [\n vue(),\n babel(),\n resolve(),\n commonjs(),\n terser()\n ],\n external: ['vue']\n}\n```\n\n```text\nimport Form from './Form.vue'\n\nexport default {\n install(Vue, _) {\n Vue.component('bs-form', Form)\n }\n}\n```\n\n```text\n\"name\": \"bs-forms\",\n \"main\": \"./dist/umd.js\",\n \"module\": \"./dist/esm.js\",\n \"files\": [\n \"dist/*\"\n ],\n \"scripts\": {\n \"build\": \"npm run build:umd & npm run build:es\",\n \"build:es\": \"rollup --config rollup.config.js --format es --file dist/esm.js\",\n \"build:umd\": \"rollup --config rollup.config.js --format umd --file dist/umd.js\"\n }\n```\n\n```text\n/* main.js*/\nimport Vue from 'vue'\n\nimport bsForms from 'bs-forms'\nVue.use(bsForms)\n```\n\n```text\n// Nuxt Plugins\n...\nplugins: [{src: '~/plugins/main'}]\n...\n```\n\n```text\nimport Vue from 'vue'\n\nconst Component = Vue.extend({\n // type inference enabled\n})\n```\n\n```text\nnpm install -save <plugin-name>\n```\n\n```text\nnpm link <plugin-name>\n```\n\n```text\nnpm pack\n```\n\n```text\nnpm install /absolute_path_to_your_local_package/your_package_name.tgz\n```\n\n```text\nnpm pack\n```\n\n```text\nnpm link\n```\n\n========================================\n\nComments:\n- Can you publish a repository of your setup so that it's easier to reproduce? Also an unrelated question, what tool did you use to generate the nice picture? :)\n- That's Webpack's good old bundle analyser plugin :) github.com/webpack-contrib/webpack-bundle-analyzer","metadata":{"transformedAt":"2026-08-18T18:33:07.882Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":253,"estimatedTokens":1833}}626{"id":"stack-59316450","source":"stackoverflow","questionId":59316450,"title":"How to make html generated by `nuxt generate` fully static?","tags":["javascript","vue.js","nuxt.js"],"text":"Title: How to make html generated by `nuxt generate` fully static?\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have this very simple vue page located at `pageas/index.vue`:\n\n```\n\n hello world\n\n```\n\nAfter running `nuxt generate`, the generated html file `dist/index.html` doesn't have any \"hello world\" in it.\n\nThat means the generate site isn't fully static. It still requires a browser to run js to render the final html, and search engines might not be able to see html in vue pages.\n\nI wonder is there anyway to make nuxt fully generated html files at least when the vue pages are static(e.g., don't have `asyncData` or `fetch` specified)?\n\n========================================\n\nCode:\n```text\n<template>\n <div>hello world</div>\n</template>\n```\n\n```text\npageas/index.vue\n```\n\n```text\nnuxt generate\n```\n\n```text\ndist/index.html\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nexport default {\n mode: 'universal'\n}\n```\n\n```text\nuniversal\n```\n\n```text\nnpm run generate\n```\n\n========================================\n\nComments:\n- This is not possible with nuxt without using SSR. You can take a look at gridsome as alternative: gridsome.org","metadata":{"transformedAt":"2026-08-18T18:33:07.882Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":66,"estimatedTokens":294}}627{"id":"stack-76127659","source":"stackoverflow","questionId":76127659,"title":"Route params are undefined in layouts/components in Nuxt 3","tags":["vue.js","nuxt.js","vue-router","nuxt3.js"],"text":"Title: Route params are undefined in layouts/components in Nuxt 3\nTags: vue.js, nuxt.js, vue-router, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm having problems with route params being undefined in components/layouts in Nuxt 3. It seems like a bug but it would be such a critical bug, that I almost don't believe it can be a bug.\n\nConsider the following files:\n\n```\n// pages/index.vue\n\n \n Click me\n \n\n```\n\n```\n// pages/test-[id].vue\n\ndefinePageMeta({ layout: \"test\" });\nconst route = useRoute();\nconsole.log(\"page\", route.params.id);\n\n \n {{ route.params.id }}\n \n\n```\n\n```\n// layouts/test.vue\n\nconst route = useRoute();\nconsole.log(\"layout\", route.params.id);\n\n \n \n \n \n\n```\n\n```\n// components/test.vue\n\nconst route = useRoute();\nconsole.log(\"component\", route.params.id);\n\n \n {{ route.params.id }}\n \n\n```\n\nClicking the link will give the following console output:\n\n```\nlayout undefined [test.vue:4:8](http://localhost:3001/_nuxt/layouts/test.vue)\ncomponent undefined [test.vue:4:8](http://localhost:3001/_nuxt/components/test.vue)\npage 123 [test-[id].vue:6:8](http://localhost:3001/_nuxt/pages/test-[id].vue)\n```\n\nIf we navigate from `/` to `/test-123` with a NuxtLink and print `route.params.id` in the layout, component and page, only the page is able to access the id. The layout and component will print undefined. If I reload the page, the component, layout and page all are able to access the route params. So the issue only occurs when navigating from one page to another.\n\nI'm on Nuxt `3.4.2`. Here is a reproduction of the issue.\n\nIs this a bug or am I doing something wrong here?\n\n========================================\n\nTop Answer:\nJust to add a \"shortcut\" here: ivan119 found a different solution that has been working for me, as seen in his comment on the Github issue OP created: https://github.com/nuxt/nuxt/issues/20471#issuecomment-1785954699\n\nI lost much time until i found solution, please try\n\n```\nconst route = useRouter().currentRoute.value\nconst id = route.params.id\n```\n\nfor some reason \"useRoute().params.id\" is cached\n\n========================================\n\nCode:\n```text\n// pages/index.vue\n<template>\n <div>\n <NuxtLink to=\"/test-123\">Click me</NuxtLink>\n </div>\n</template>\n```\n\n```text\n// pages/test-[id].vue\n<script setup lang=\"ts\">\ndefinePageMeta({ layout: \"test\" });\nconst route = useRoute();\nconsole.log(\"page\", route.params.id);\n</script>\n\n<template>\n <div>\n {{ route.params.id }}\n </div>\n</template>\n```\n\n```text\n// layouts/test.vue\n<script setup lang=\"ts\">\nconst route = useRoute();\nconsole.log(\"layout\", route.params.id);\n</script>\n\n<template>\n <div>\n <test></test>\n <slot></slot>\n </div>\n</template>\n```\n\n```text\n// components/test.vue\n<script setup lang=\"ts\">\nconst route = useRoute();\nconsole.log(\"component\", route.params.id);\n</script>\n\n<template>\n <div>\n {{ route.params.id }}\n </div>\n</template>\n```\n\n```text\nlayout undefined [test.vue:4:8](http://localhost:3001/_nuxt/layouts/test.vue)\ncomponent undefined [test.vue:4:8](http://localhost:3001/_nuxt/components/test.vue)\npage 123 [test-[id].vue:6:8](http://localhost:3001/_nuxt/pages/test-[id].vue)\n```\n\n```text\n/\n```\n\n```text\n/test-123\n```\n\n```text\nroute.params.id\n```\n\n```text\n3.4.2\n```\n\n```js\nexport default defineNuxtRouteMiddleware((to) => {\n console.log('Middleware', to.params.id)\n})\n```\n\n```js\nexport default defineNuxtRouteMiddleware((to) => {\n console.log('Middleware', to.params.id)\n useState('routeParamId', () => to.params.id)\n})\n```\n\n```js\n<script setup lang=\"ts\">\nconst paramId = useState('routeParamId')\nconsole.log('ParamId is', paramId.value)\n</script>\n\n<template>\n <div>\n <slot></slot>\n </div>\n</template>\n```\n\n```js\n<script setup lang=\"ts\">\ndefinePageMeta({ layout: \"test\", middleware: 'check-route' });\nconst route = useRoute();\n</script>\n\n<template>\n <div>\n {{ route.params.id }}\n </div>\n</template>\n```\n\n```text\nNuxtLink\n```\n\n```text\nNuxtLayout\n```\n\n```text\nNuxtPage\n```\n\n```text\nNuxtLayout\n```\n\n```text\ntest\n```\n\n```text\nmiddleware\n```\n\n```text\n~middlware/check-auth.ts\n```\n\n```text\ntest-[id]\n```\n\n```text\nmiddleware\n```\n\n```text\nuseState\n```\n\n```text\n~middlware/check-auth.ts\n```\n\n```text\nlayout\n```\n\n```text\n~layouts/test.vue\n```\n\n```text\ntest-[id]\n```\n\n```text\n~pages/test-[id].vue\n```\n\n```text\nconst route = useRouter().currentRoute.value\nconst id = route.params.id\n```\n\n```text\n<RouterView />\n```\n\n```text\n<NuxtPage />\n```\n\n========================================\n\nComments:\n- I had this problem and I used instead of in my App.vue file and my problem solved.\n- This seems to do the trick! I have opened a issue on Github related to this.\n- Thank you so much for your comment! I am using a PrimeVue template and it had `` everywhere. I did not want to change much because of the chance I would break things but switching it over to `` solved my issue of `route.params` not updating in `useRouter()`\n- @Maarten glad I could help ;)","metadata":{"transformedAt":"2026-08-18T18:33:07.882Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":281,"estimatedTokens":1245}}628{"id":"stack-65237657","source":"stackoverflow","questionId":65237657,"title":"How to make an append item always visible in v-select vuetify","tags":["vue.js","nuxt.js","vuetify.js","v-select"],"text":"Title: How to make an append item always visible in v-select vuetify\nTags: vue.js, nuxt.js, vuetify.js, v-select\nSource: Stack Overflow\n\nQuestion:\nI have a vuetify v-select dropdown.\nInside I made a slot #append-item in which I have a button \"validate\"\nI want the button to always be visible when I scroll inside the dropdown.\n\n========================================\n\nTop Answer:\nI added this style to my \"validate\" button and it worked:\n\n```\n.append {\n position: sticky;\n bottom: 0;\n background: white;\n}\n\n \n\n \n \n Validate\n \n \n \n```\n\n========================================\n\nCode:\n```text\n<template #append-item>\n <div class=\"append\">\n <v-btn color=\"primary\">valider</v-btn>\n </div>\n </template>\n```\n\n```text\n.append{\n position:sticky;\n bottom:8px;\n width:100%;\n display:flex;\n justify-content :center;\n background :white;\n \n}\n```\n\n```text\nappend\n```\n\n```text\n.append {\n position: sticky;\n bottom: 0;\n background: white;\n}\n\n\n <template #append-item>\n\n <div class=\"append\">\n <v-btn color=\"primary\">\n Validate\n </v-btn>\n </div>\n </template>\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.882Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":75,"estimatedTokens":284}}629{"id":"stack-74713292","source":"stackoverflow","questionId":74713292,"title":"How to change TTL when using swr in Nuxt 3? (per-route preferably)","tags":["javascript","nuxt.js","server-side-rendering","nuxt3.js","ttl"],"text":"Title: How to change TTL when using swr in Nuxt 3? (per-route preferably)\nTags: javascript, nuxt.js, server-side-rendering, nuxt3.js, ttl\nSource: Stack Overflow\n\nQuestion:\nThe Nuxt 3 documentations says that `swr enables a static build, that lasts for a configurable TTL`, however, nowhere was I able to find how exactly one would change the TTL & whether it can be set per-route. Is that possible? If so, how?\n\nI've looked at github & also tried to find it in Vite / Nitro documentation but didn't find anything.\n\nI found something about image TTL in Nitro config source files but I suppose that's not what I was looking for.\n\n========================================\n\nTop Answer:\nThis github issue is about that subject, it is still in the works (you can subscribe to it to get the latest updates!) but this is how the whole final API may look like:\n\n```\nexport default defineNuxtConfig({\n routes: {\n '/': { prerender: true },\n '/blog/*': { static: true },\n '/stats/*': { swr: '10 min' }, // 👈🏻 TTL of 10 minutes\n '/admin/*': { ssr: false },\n '/react/*': { redirect: '/vue' },\n }\n})\n```\n\n========================================\n\nCode:\n```text\nswr enables a static build, that lasts for a configurable TTL\n```\n\n```js\nexport default defineNuxtConfig({\n routeRules: {\n '/**': { swr: 5 }, // 👈🏻 TTL in seconds\n }\n})\n```\n\n```js\nexport default defineNuxtConfig({\n routes: {\n '/': { prerender: true },\n '/blog/*': { static: true },\n '/stats/*': { swr: '10 min' }, // 👈🏻 TTL of 10 minutes\n '/admin/*': { ssr: false },\n '/react/*': { redirect: '/vue' },\n }\n})\n```\n\n========================================\n\nComments:\n- The API only accepts a boolean or a number for swr. The number is the number of seconds.\n- Sorry if my answer wasn't specific enough regarding the seconds.\n- No problem, I'm just having trouble with specifying it to work only for some routes. When I enable it on '/test-swr': { swr: 5 }, it doesn't work for some reason...\n- Is `/test-swr` specified above or below `/**`? Try putting it above.\n- seem like no matter where I put it, the `/**` overrides the TTL for all routes this is what it looks like: ` routeRules: { '/no-swr/time-test': { swr: 0 }, '/**': { swr: 10 }, } ` and when I only enable it for a specific route, it stays disabled ` routeRules: { '/time-test': { swr: 10 }, } `\n- @Matej where do you host your app? I was told swr works on Netlify only and would like to check that. Thanks.\n- @DavidDahan there are several places where SWR may be working, mainly most of the Edge Rendering (SSR) places like Cloudflare workers, Vercel etc IMO.\n- @kissu thanks I was wondering because on this page I can read both `currently Netlify and Vercel are supported` and `currently enables full incremental static generation on Netlify, with Vercel coming soon`. So I'm not sure if Vercel is actually supported.\n- @DavidDahan ISR is not the same as SWR and I think that it should be supported indeed.","metadata":{"transformedAt":"2026-08-18T18:33:07.882Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":67,"estimatedTokens":741}}630{"id":"stack-62619317","source":"stackoverflow","questionId":62619317,"title":"How to see generated routes in nuxtjs","tags":["vue.js","nuxt.js"],"text":"Title: How to see generated routes in nuxtjs\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIs there a way to see the route list generated by Nuxtjs based on pages folder items ?\nThe problem is I don't know what exact route name is generated for the component.\n\n```\n$router.push({name: 'no-idea-what-the-route-name-is', query: { id: data.id } })\n```\n\nthis is very useful in a large scale app.\nin Laravel easily we can use `php artisan route:list` command in same scenario.\n\n========================================\n\nCode:\n```text\n$router.push({name: 'no-idea-what-the-route-name-is', query: { id: data.id } })\n```\n\n```text\nphp artisan route:list\n```\n\n```text\n.nuxt\n```\n\n```text\nrouter.js\n```\n\n========================================\n\nComments:\n- seems the generated route is kept in \".nuxt/router.js\" file !\n- This file doesn't exist in nuxt 3\n- Theres also a routes.json in that folder.\n- note that, .nuxt folder will be generated automatically when executing nuxt dev or nuxt build\n- Use Vue DevTools -> Pages to see a list of Vue routes. Mentioned in github.com/nuxt/nuxt/issues/6830","metadata":{"transformedAt":"2026-08-18T18:33:07.882Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":42,"estimatedTokens":274}}631{"id":"stack-65871711","source":"stackoverflow","questionId":65871711,"title":"CORS Missing Allow Origin","tags":["vue.js","cors","nuxt.js","django-cors-headers"],"text":"Title: CORS Missing Allow Origin\nTags: vue.js, cors, nuxt.js, django-cors-headers\nSource: Stack Overflow\n\nQuestion:\nMy server (written with `Django`) is running at `http://localhost:8000`.\n\nThe `Nuxt` application is running at `http://localhost:3000`.\n\nWhen I send a request (like `http://localhost:8000/api/v1/user/position/`) to the server, I get the following error in the `firefox` browser.\n\nCross-Origin Request Blocked: The Same Origin Policy disallows reading\nthe remote resource at http://localhost:8000/api/v1/user/position/.\n(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).\n\n**Firefox:**\n\nhttps://i.sstatic.net/cZPwr.png\n\n**Chrome:**\n\nhttps://i.sstatic.net/WaFvJ.png\n\nI saw this link and this but I do not know where the problem comes from?\n\nBelow is a section of my `nuxt.config.js` file.\n\n```\nmodules: [\n '@nuxtjs/axios',\n '@nuxtjs/proxy'\n],\naxios: {\n baseURL: 'http://localhost:8000/api/v1/', \n},\n```\n\nAnd function that I'm sending a request:\n\n```\nasync getAllPosition() {\n this.loading_position = true;\n await this.$axios.get('user/position/').then(response => {\n this.position = response.data;\n }).finally(() => {\n this.loading_position = false;\n })\n }\n```\n\nI think it's about proxy, but i don't know how to config it.\n\n========================================\n\nTop Answer:\nAs the error message reveals: You need to specify a `Access-Control-Allow-Origin`-header in your Server to allow your request across origins. (yea ::3000 and ::8000 are different origins). Modern Browsers will fire a options (pre-flight) request to check the Access-* headers when requesting another origin. You must answer those `OPTIONS` requests with at least a Access-Control header.\n`Access-Control-Allow-Origin: localhost:3000` should be fine for development.\n\nMore about CORS and the Browser OPTIONS Request here:\n\nhttps://enable-cors.org/\n\nWhy is an OPTIONS request sent and can I disable it?\n\n========================================\n\nCode:\n```text\nmodules: [\n '@nuxtjs/axios',\n '@nuxtjs/proxy'\n],\naxios: {\n baseURL: 'http://localhost:8000/api/v1/', \n},\n```\n\n```text\nasync getAllPosition() {\n this.loading_position = true;\n await this.$axios.get('user/position/').then(response => {\n this.position = response.data;\n }).finally(() => {\n this.loading_position = false;\n })\n }\n```\n\n```text\nDjango\n```\n\n```text\nhttp://localhost:8000\n```\n\n```text\nNuxt\n```\n\n```text\nhttp://localhost:3000\n```\n\n```text\nhttp://localhost:8000/api/v1/user/position/\n```\n\n```text\nfirefox\n```\n\n```text\nnuxt.config.js\n```\n\n```text\npip install django-cors-headers\n```\n\n```text\n// settings.py\n\nINSTALLED_APPS = [\n ...\n 'corsheaders',\n]\n\nMIDDLEWARE = [\n ...\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n ...\n]\n\nCORS_ALLOWED_ORIGINS = [\n \"http://localhost:3000\",\n]\n```\n\n```text\nAccess-Control-Allow-Origin\n```\n\n```text\nDjango\n```\n\n```text\ndjango-cors-headers\n```\n\n```text\nsettings.py\n```\n\n```text\nAccess-Control-Allow-Origin\n```\n\n```text\nOPTIONS\n```\n\n```text\nAccess-Control-Allow-Origin: localhost:3000\n```\n\n```text\nexport default {\n ...\n proxy: {\n '/api': { \n target: 'http://localhost:8000',\n pathRewrite: {\n '^/api': '/api',\n changeOrigin: true\n } \n }\n },\n}\n```\n\n```text\nAccess-Control-Allow-Origin Header\n```\n\n========================================\n\nComments:\n- This document can help you nuxtjs.org/faq/http-proxy","metadata":{"transformedAt":"2026-08-18T18:33:07.882Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":191,"estimatedTokens":861}}632{"id":"stack-69623771","source":"stackoverflow","questionId":69623771,"title":"How to use a private API key with Nuxt (on the client)?","tags":["vue.js","nuxt.js"],"text":"Title: How to use a private API key with Nuxt (on the client)?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\n**Problem Solved**\n\nIf you're struggling with the same issue, look at the accepted answer which is one way to achieve it by using serverMiddleware\n\nI'm using an API which required a private key. I've stored the key inside a .env file, and called it in the nuxt configuration file, like this :\n\n```\nprivateRuntimeConfig: {\n secretKey: process.env.MY_SECRET_KEY\n},\n```\n\nMy API call is done inside the asyncData() hook on my index page. It works fine when i load this page, or reload it, but everytime i use the navigation to come back to this page, i end up with an error (I use a buffer to convert my API key to base64)\n\nFirst argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.\n\nAfter some research and debugging, i found out that my private key wasn't available at the time, and the \"secret\" value used in my api call was \"undefined\".\n\nThe thing I don't get is why is this working on initial load / reload but not on page navigation ? And is there a way to fix it without using a backend ? (SSR for SEO and the ability to use private keys without exposing them are the main reasons why i used Nuxt for my project)\n\nHere is my code :\n\n```\nasync asyncData({ $content, store, $config }) {\n const secret = Buffer.from($config.secretKey).toString('base64')\n const request = await fetch('https://app.snipcart.com/api/products', {\n headers: {\n 'Authorization': `Basic ${secret}`,\n 'Accept': 'application/json'\n }\n })\n const result = await request.json()\n store.commit('products/addProducts', result)\n const stocks = store.getters['products/getProducts']\n\n return { stocks }\n},\n```\n\n========================================\n\nTop Answer:\n### Update\n\nLooking at the `@nuxtjs/snipcart` module's key key and since it's a `buildModules`, you can totally put it there since it will be available only during the build (on Node.js only)!\n\nFor more info, Snipcart do have a lot of blog posts, this one based on Nuxt may help clearing things up: https://www.storyblok.com/tp/how-to-build-a-shop-with-nuxt-storyblok-and-snipcart\n\nYou do have your key initially because you're reaching the server when you enter the page or hard refresh it.\n\nIf you navigate after the hydration, it will be a client side navigation so you will not be able to have access to the private key. At the end, if your key is **really** private (nowadays, some API provide keys that can be exposed), you'll need to work around it in some ways.\n\nLooking at Snipcart: https://docs.snipcart.com/v3/api-reference/authentication, it clearly states that the key should be available in\n\nAppear in your compiled front-end assets (HTML, JavaScript)\n\nMeanwhile, if you need to make another call to your backend (trying to access something else than `products`), you'll need to make a second call.\n\nWith Nuxt2, you cannot reach for the backend each time as of right now since you will stay in an SPA context (Nuxt is a `server` **then** `client` Vue app basically). But you could write down the token into a cookie or even better, use a backend as a proxy to hide this specific key (or even a serverless function).\n\nSome more info can be found on my other answer here: https://stackoverflow.com/a/69575243/8816585\n\n========================================\n\nCode:\n```text\nprivateRuntimeConfig: {\n secretKey: process.env.MY_SECRET_KEY\n},\n```\n\n```text\nasync asyncData({ $content, store, $config }) {\n const secret = Buffer.from($config.secretKey).toString('base64')\n const request = await fetch('https://app.snipcart.com/api/products', {\n headers: {\n 'Authorization': `Basic ${secret}`,\n 'Accept': 'application/json'\n }\n })\n const result = await request.json()\n store.commit('products/addProducts', result)\n const stocks = store.getters['products/getProducts']\n\n\n\n return { stocks }\n},\n```\n\n```js\nconst bodyParser = require('body-parser')\nconst axios = require('axios')\nconst app = require('express')()\n\napp.use(bodyParser.json())\napp.all('/getProducts', (request, response) => {\n \n const url = 'https://app.snipcart.com/api/products'\n const secret = Buffer.from(process.env.SNIPCART_SECRET).toString('base64')\n const config = {\n headers: {\n 'Authorization': `Basic ${secret}`,\n 'Accept': 'application/json'\n }\n }\n\n axios\n .get(url, config)\n .then(res => {\n const products = {} \n res.data.items.forEach(\n item => {\n const productId = item.userDefinedId.replace(/-/g, '')\n const stocks = {}\n\n item.variants.forEach(\n variant => {\n const size = variant.variation[0].option\n const stock = variant.stock\n stocks[size] = stock\n }\n )\n products[productId] = stocks\n \n }\n )\n response.json(products)\n })\n .catch( err => response.json(err) )\n})\n\nmodule.exports = app\n```\n\n```js\nserverMiddleware: [\n { path: \"/server\", handler: \"~/server/snipcart.js\" }\n]\n```\n\n```js\nasync asyncData({ $content, store, $axios }) {\n \n await $axios\n .get('/server/getProducts')\n .then(res => store.commit('products/addProducts', res.data))\n .catch(err => console.log(err))\n \n const stocks = store.getters['products/getProducts']\n\n return {stocks, masterplanProducts }\n},\n```\n\n```text\nserver/snipcart.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nif ($config.secretKey) {\n const secret = Buffer.from($config.secretKey).toString('base64')\n const request = await fetch('https://app.snipcart.com/api/products', {\n headers: {\n 'Authorization': `Basic ${secret}`,\n 'Accept': 'application/json'\n }\n })\n const result = await request.json()\n store.commit('products/addProducts', result)\n}\nconst stocks = store.getters['products/getProducts']\n```\n\n```text\n@nuxtjs/snipcart\n```\n\n```text\nbuildModules\n```\n\n```text\nproducts\n```\n\n```text\nserver\n```\n\n```text\nclient\n```\n\n========================================\n\nComments:\n- Even if this works in your case, the next call will not be doable if you're trying to access `/cart` or any other path that requires this token.\n- Yes, I figured this out when I tried to clean cache + reload from another route before accessing this one. That's why i deleted this post (but since it can prevent someone else to make the same mistake, i've put it back with an update line)\n- I'm using the module in the current version of the shop, but still, I didn't find how to securely use the private API key with it. I need to access the remaining stock for each product/variant in order to display an \"out of stock\" / \"Only 2 left\" kind of message directly on the product page, and I don't think there is a way to do it which doesn't not involved the private API key.\n- As stated here by Daniel, you can indeed use a `serverMiddleware` to have some kind of local REST API that will forward your call to an external API without exposing your public token. I don't have any experience with this but this is a great approach, well done!\n- Feel free to mark your answer as accepted when you'll be able to.","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":211,"estimatedTokens":1855}}633{"id":"stack-65250206","source":"stackoverflow","questionId":65250206,"title":"Problem with deploy Nuxt.js in GitHub Pages","tags":["vue.js","nuxt.js","vue-router","github-pages"],"text":"Title: Problem with deploy Nuxt.js in GitHub Pages\nTags: vue.js, nuxt.js, vue-router, github-pages\nSource: Stack Overflow\n\nQuestion:\nI recently started learning `Nuxt.Js` and faced with the problem of deployment on GitHub Pages.\n\nI do everything according to the instructions:\n\nhttps://medium.com/@kozyreva.hanna/nuxt-js-gh-pages-deployment-73b88aa3aa65\n\nInfinite `nuxt-loading` appears on `gh-pages` instead of content.\n\nGitHub: https://github.com/Owe7x/slide\n\nGH-pages: https://owe7x.github.io/slide/\n\nWhat could be the problem?\n\n========================================\n\nCode:\n```text\nNuxt.Js\n```\n\n```text\nnuxt-loading\n```\n\n```text\ngh-pages\n```\n\n```text\ntarget: 'static',\n router: {\n base: '/<repository-name>/'\n }\n```\n\n```text\ndist\n```\n\n```text\n.gitignore\n```\n\n```text\nnpm run generate\n```\n\n```text\ngit add .\n```\n\n```text\ngit commit -m \"deploy on gh-pages\"\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ngit subtree push --prefix dist origin gh-pages\n```\n\n```text\ngh-pages\n```\n\n========================================\n\nComments:\n- Thanks a lot) Only now there is a problem with the paths \"Failed to load resource: the server responded with a status of 404 ()\"\n- could you show a screenshot of that error?\n- ibb.co/CvgmVcx GH-Pages: owe7x.github.io/slide\n- after running `npm run generate` go to dist/index.html and remove the slash `/` before any source link\n- mmmm sorry, Try this nuxtjs.org/faq/github-pages","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":81,"estimatedTokens":358}}634{"id":"stack-62202526","source":"stackoverflow","questionId":62202526,"title":"How do I get the POST data from a nuxtjs server middleware?","tags":["express","nuxt.js"],"text":"Title: How do I get the POST data from a nuxtjs server middleware?\nTags: express, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHow do I get the POST data from a nuxtjs server middleware? So far I've managed to do it for GET, but for POST the body is just not there. `req.body` is undefined.\n\n========================================\n\nTop Answer:\nYou do not need to use express because nuxt server already running connect instance for this. Just do this for receiving the POST request:\n\nyourservermiddleware.js -\n\n```\nexport default {\n path: '/yourservermiddlware',\n async handler(req, res, next) {\n\n req.on('data', async (data) => {\n let payload = JSON.parse(data.toString())\n console.log(\"received request\", payload)\n res.end(JSON.stringify('send back what you want'))\n next()\n })\n\n \n }\n}\n```\n\nP.S. and do not forget to register servermiddleware at the nuxt.config.js\n\n========================================\n\nCode:\n```text\nreq.body\n```\n\n```text\nserverMiddleware: [\n '~/api/v1/index.js'\n],\n```\n\n```text\nconst bodyParser = require('body-parser')\nconst app = require('express')()\nmodule.exports = { path: '/api', handler: app }\napp.use(bodyParser.json());\napp.post('/newsletter/subscribe', (req, res) => {\n res.json(req.body)\n})\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n/api/v1/index.js\n```\n\n```text\napp.use(bodyParser.json())\n```\n\n```text\nexport default {\n path: '/yourservermiddlware',\n async handler(req, res, next) {\n\n req.on('data', async (data) => {\n let payload = JSON.parse(data.toString())\n console.log(\"received request\", payload)\n res.end(JSON.stringify('send back what you want'))\n next()\n })\n\n\n \n }\n}\n```\n\n========================================\n\nComments:\n- Very useful! Thanks! I don't know why this is not in the docs. I added it and referenced this question (github.com/nuxt/nuxtjs.org/pull/711)\n- Someone should try using `express.Router()` instead of what I've done `require('express')()` - post another answer if it works :)","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":91,"estimatedTokens":505}}635{"id":"stack-58787024","source":"stackoverflow","questionId":58787024,"title":"Nuxt Plugins not working after build ( use apexchart )","tags":["vue.js","nuxt.js","apexcharts"],"text":"Title: Nuxt Plugins not working after build ( use apexchart )\nTags: vue.js, nuxt.js, apexcharts\nSource: Stack Overflow\n\nQuestion:\nI use apex chart in nuxt\n\nand apply plugins with my code\n\nthis working in dev mode\n\n```\ncross-env NODE_ENV=development HOST=0.0.0.0 PORT=3000 nodemon server/index.js --watch server\n```\n\nbut not working in build source\n\n```\nnuxt build && cross-env NODE_ENV=production HOST=0.0.0.0 PORT=80 node server/index.js\n```\n\nHere is my codes\n\nplugins/vue-apexchar.js\n\n```\nimport Vue from 'vue'\nimport VueApexCharts from 'vue-apexcharts'\n\nVue.component('VueApexCharts', VueApexCharts);\n```\n\nnuxt.config.js\n\n```\nplugins: [\n { src : '~/plugins/vue-apexchart.js', ssr : false },\n],\nbuild: {\n vendor : [\n 'vue-apexchart'\n ]\n}\n```\n\nweekChart.vue\n\n```\n\n```\n\nthese codes working in dev mode but not working build files\n\nI needs your helps for solve this problomes\n\nPlease Help me\n\nHere is my source code > https://github.com/zoz0312/Nuxt_Blog\n\n========================================\n\nCode:\n```text\ncross-env NODE_ENV=development HOST=0.0.0.0 PORT=3000 nodemon server/index.js --watch server\n```\n\n```text\nnuxt build && cross-env NODE_ENV=production HOST=0.0.0.0 PORT=80 node server/index.js\n```\n\n```text\nimport Vue from 'vue'\nimport VueApexCharts from 'vue-apexcharts'\n\nVue.component('VueApexCharts', VueApexCharts);\n```\n\n```text\nplugins: [\n { src : '~/plugins/vue-apexchart.js', ssr : false },\n],\nbuild: {\n vendor : [\n 'vue-apexchart'\n ]\n}\n```\n\n```text\n<VueApexCharts max-width=\"300\" type=\"area\" :options=\"chartOptions\" :series=\"series\"></VueApexCharts>\n```\n\n```text\n<client-only>\n <MY COMPONENT/>\n</client-only>\n```\n\n========================================\n\nComments:\n- Hope this issue can help you :)\n- I solved this problem THANK YOU!!!!\n- I was happy to help :) Have a good day\n- You are having spelling mistake you file name is \"vue-apexchar.js\" but in plugin you put vue-apexchart.js","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":105,"estimatedTokens":479}}636{"id":"stack-50830955","source":"stackoverflow","questionId":50830955,"title":"Using Nuxt.js project both with or without electron","tags":["electron","nuxt.js"],"text":"Title: Using Nuxt.js project both with or without electron\nTags: electron, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI would like to configure a Nuxt.js project to be able to eitheir run it using `nuxt start` or using electron. The goal is to have the same code for a web app and an electron app.\n\nIs it possible to combine both fontionnalities in the same project?\n\n========================================\n\nTop Answer:\nNuxt Community template is out of updates.use the following boilerplate for nuxt+electron\n\n```\n# Install vue-cli and scaffold boilerplate\nnpm install -g vue-cli\nvue init michalzaq12/electron-nuxt \n```\n\nLink: https://github.com/michalzaq12/electron-nuxt\n\n========================================\n\nCode:\n```text\nnuxt start\n```\n\n```text\nelectron-template\n```\n\n```text\nvue init nuxt-community/electron-template my-project\n```\n\n```text\n# Install vue-cli and scaffold boilerplate\nnpm install -g vue-cli\nvue init michalzaq12/electron-nuxt <project-name>\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":42,"estimatedTokens":243}}637{"id":"stack-67215827","source":"stackoverflow","questionId":67215827,"title":"Nuxt Auth Module - Multiple redirect options after logout","tags":["vue.js","authentication","nuxt.js"],"text":"Title: Nuxt Auth Module - Multiple redirect options after logout\nTags: vue.js, authentication, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a website where the user logs in and then gets access to a dashboard. The user can log in and out from their dashboard as well as from the home page. Now I want that when the user logs out from the dashboard, he gets directed to a different page than when he logs out from the home page. Is this somehow possible with the `auth` module in Nuxt? I haven't found a way so far.\n\nmy nuxt.config.js looks like this at the moment:\n\n```\nauth: {\n redirect: {\n home: \"/\",\n login: \"/\"\n },\n strategies: {\n local: {\n endpoints: {\n login: { url: \"/api/session\", method: \"post\" },\n logout: { url: \"/api/session\", method: \"destroy\" },\n user: { url: \"/api/settings\", method: \"get\", propertyName: false }\n },\n tokenType: 'Bearer'\n }\n },\n redirect: {\n login: '/',\n logout: '/',\n home: false,\n },\n }\n```\n\nAnd then there is the button from the home page:\n\n```\n\nLogout\n\n```\n\nand the button from the Dashboard:\n\n```\n\nLogout\n\n```\n\n========================================\n\nTop Answer:\nI think you can simply use `$router.push('/dashboard')`:\n\n```\n\n Logout\n\n```\n\n========================================\n\nCode:\n```text\nauth: {\n redirect: {\n home: \"/\",\n login: \"/\"\n },\n strategies: {\n local: {\n endpoints: {\n login: { url: \"/api/session\", method: \"post\" },\n logout: { url: \"/api/session\", method: \"destroy\" },\n user: { url: \"/api/settings\", method: \"get\", propertyName: false }\n },\n tokenType: 'Bearer'\n }\n },\n redirect: {\n login: '/',\n logout: '/',\n home: false,\n },\n }\n```\n\n```text\n<span v-if=\"this.$store.state.auth.loggedIn\" class=\"inline-flex rounded-md shadow\">\n<button\n @click=\"$auth.logout()\"\n v-scroll-to=\"'#login'\"\n >Logout</button>\n</span>\n```\n\n```text\n<button\n @click=\"$auth.logout()\"\n>\n<span class=\"font-normal text-sm mt-0/5\">Logout</span>\n</button>\n```\n\n```text\nauth\n```\n\n```js\nexport default function({ $auth }) {\n $auth.onRedirect((to, from) => {\n if(from === '/dashboard'){return '/another-logout'}\n })\n}\n```\n\n```js\n{\n auth: {\n plugins: [ '~/plugins/auth.js' ],\n strategies: {}\n }\n}\n```\n\n```js\n{\n auth: {\n watchLoggedIn: false, // add this line\n strategies: {}\n }\n}\n```\n\n```js\nfunction routeOption (route, key, value) {\n return route.matched.some((m) => {\n if (process.client) {\n return Object.values(m.components).some(component => component.options && component.options[key] === value)\n } else {\n return Object.values(m.components).some(component => Object.values(component._Ctor).some(ctor => ctor.options && ctor.options[key] === value))\n }\n })\n}\nexport default function ({ $auth }) {\n $auth.$storage.watchState('loggedIn', (loggedIn) => {\n if (!routeOption($auth.ctx.route, 'auth', false)) {\n let redirectKey = loggedIn ? 'home' : 'logout'\n if (redirectKey == 'logout') {\n const logout_type = $auth.$storage.getUniversal('logout_type')\n if (logout_type) {\n redirectKey = 'logout_' + logout_type\n // delete to ensure use only once\n $auth.$storage.removeUniversal('logout_type')\n }\n }\n $auth.redirect(redirectKey)\n }\n })\n $auth.logoutWith = (logout_type, ...args) => {\n $auth.$storage.setUniversal('logout_type', logout_type)\n $auth.logout(...args)\n }\n}\n```\n\n```js\n{\n auth: {\n watchLoggedIn: false,\n plugins: [ '~/plugins/auth.js' ],\n redirect: {\n login: '/login',\n logout: '/logout',\n logout_dash: '/another_logout',\n home: '/home'\n },\n }\n}\n```\n\n```html\n<button @click=\"$auth.logoutWith('dash')\"></button>\n```\n\n```text\nplugins/auth.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nwatchLoggedIn\n```\n\n```text\nlogoutWith\n```\n\n```text\nloggedIn\n```\n\n```text\nplugin/auth.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nredirect\n```\n\n```text\nlogoutWith\n```\n\n```text\n<button @click=\"$auth.logout();$router.push('/dashboard')\">\n <span class=\"font-normal text-sm mt-0/5\">Logout</span>\n</button>\n```\n\n```text\n$router.push('/dashboard')\n```\n\n```text\nredirect: false,\n```\n\n========================================\n\nComments:\n- Please , if you have found any solution.\n- I thought so too, but the redirect `logout: '/'` in nuxt.config.js seems to override the `$router.push('/dashboard')`. But I guess I need that redirect for the \"normal\" Logout case, where the user is supposed to be redirected to '/'\n- I tested this snippet, and it worked for me. User redirected to `/dashboard`. BTW I don't think `Nuxt-auth` provides any feature for multiple redirects for `logout`.\n- This answer is really simple and it worked a treat!","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":242,"estimatedTokens":1181}}638{"id":"stack-79779466","source":"stackoverflow","questionId":79779466,"title":"Nuxt 4 + shadcn/vue Overriding component You can specify a priority option when calling addComponent to avoid this warning warnings for all components","tags":["vue.js","nuxt.js","shadcnui"],"text":"Title: Nuxt 4 + shadcn/vue Overriding component You can specify a priority option when calling addComponent to avoid this warning warnings for all components\nTags: vue.js, nuxt.js, shadcnui\nSource: Stack Overflow\n\nQuestion:\nI’m using Nuxt 4 with shadcn-nuxt@2.2.0, and I’m getting warnings for every shadcn-vue component:\n\n```\nWARN Overriding StepperDescription component. You can specify a priority option when calling addComponent to avoid this warning.\nWARN Overriding Table component. You can specify a priority option when calling addComponent to avoid this warning.\nWARN Overriding Switch component. You can specify a priority option when calling addComponent to avoid this warning.\n... (and so on for all components)\n```\n\nhttps://i.sstatic.net/AVkROs8J.png\n\n---\n\nHow can I properly remove or silence these “Overriding component” warnings in a Nuxt 4 project using shadcn-nuxt?\n\nMy Nuxt 4 config:\n\n```\n// https://nuxt.com/docs/api/configuration/nuxt-config\nimport tailwind from '@tailwindcss/vite';\n\nexport default defineNuxtConfig({\n devtools: { enabled: true },\n compatibilityDate: '2025-07-15',\n modules: [\n '@nuxt/eslint',\n '@nuxt/fonts',\n 'shadcn-nuxt',\n '@vueuse/nuxt',\n '@nuxtjs/color-mode',\n ],\n colorMode: {\n preference: 'system',\n fallback: 'light',\n hid: 'nuxt-color-mode-script',\n globalName: '__NUXT_COLOR_MODE__',\n componentName: 'ColorScheme',\n classPrefix: '',\n classSuffix: '',\n storage: 'localStorage',\n storageKey: 'nuxt-color-mode',\n },\n css: ['~/assets/css/main.css'],\n vite: {\n plugins: [tailwind()],\n },\n eslint: {\n config: {\n formatters: {\n html: 'prettier',\n },\n },\n },\n shadcn: {\n /**\n * Prefix for all the imported component\n */\n prefix: '',\n /**\n * Directory that the component lives in.\n * @default \"./components/ui\"\n */\n componentDir: '~/components/ui',\n },\n alias: {\n '@components': '~/components',\n '@ui': '~/components/ui',\n '@utils': '~/lib/utils',\n },\n});\n```\n\nI also added this to my `nuxt.config`, but it doesn't resolve the warnings.\n\n```\n...\n components: [\n {\n path: '~/components/ui',\n extensions: ['.vue', '.ts'],\n },\n ],\n...\n```\n\nWhat should I do?\n\n========================================\n\nCode:\n```bash\nWARN Overriding StepperDescription component. You can specify a priority option when calling addComponent to avoid this warning.\nWARN Overriding Table component. You can specify a priority option when calling addComponent to avoid this warning.\nWARN Overriding Switch component. You can specify a priority option when calling addComponent to avoid this warning.\n... (and so on for all components)\n```\n\n```ts\n// https://nuxt.com/docs/api/configuration/nuxt-config\nimport tailwind from '@tailwindcss/vite';\n\nexport default defineNuxtConfig({\n devtools: { enabled: true },\n compatibilityDate: '2025-07-15',\n modules: [\n '@nuxt/eslint',\n '@nuxt/fonts',\n 'shadcn-nuxt',\n '@vueuse/nuxt',\n '@nuxtjs/color-mode',\n ],\n colorMode: {\n preference: 'system',\n fallback: 'light',\n hid: 'nuxt-color-mode-script',\n globalName: '__NUXT_COLOR_MODE__',\n componentName: 'ColorScheme',\n classPrefix: '',\n classSuffix: '',\n storage: 'localStorage',\n storageKey: 'nuxt-color-mode',\n },\n css: ['~/assets/css/main.css'],\n vite: {\n plugins: [tailwind()],\n },\n eslint: {\n config: {\n formatters: {\n html: 'prettier',\n },\n },\n },\n shadcn: {\n /**\n * Prefix for all the imported component\n */\n prefix: '',\n /**\n * Directory that the component lives in.\n * @default \"./components/ui\"\n */\n componentDir: '~/components/ui',\n },\n alias: {\n '@components': '~/components',\n '@ui': '~/components/ui',\n '@utils': '~/lib/utils',\n },\n});\n```\n\n```ts\n...\n components: [\n {\n path: '~/components/ui',\n extensions: ['.vue', '.ts'],\n },\n ],\n...\n```\n\n```text\nnuxt.config\n```\n\n```bash\nrm -rf node_modules .nuxt .output\n```\n\n```json\n// example\n\"shadcn-nuxt\": \"https://pkg.pr.new/shadcn-nuxt@1418\"\n```\n\n```bash\nnpm install # `yarn install`, `pnpm install`, `yarn install`, or `bun install`\n```\n\n```bash\n# npm\nnpx nuxi prepare\n# yarn\nyarn nuxi prepare\n# pnpm\npnpm exec nuxi prepare\n# bun\nbunx --bun nuxi prepare\n```\n\n```text\nnode_modules\n```\n\n```text\n.nuxt\n```\n\n```text\n.output\n```\n\n```text\nshadcn_nuxt\n```\n\n```text\npackage.json\n```\n\n```text\nnpm install\n```\n\n========================================\n\nComments:\n- This solution worked perfectly for me! Thanks a lot for sharing.\n- Thank you bro. It worked. Now I can upgrade to nuxt4 using the nuxt3 folder structure. And now I'm trying to upgrade the compatibility version from 4 to 5.","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":225,"estimatedTokens":1147}}639{"id":"stack-57031005","source":"stackoverflow","questionId":57031005,"title":"Nuxt.js with vuex-persist - persisted state not available in asyncData upon page refresh","tags":["vuex","nuxt.js","vue-ssr"],"text":"Title: Nuxt.js with vuex-persist - persisted state not available in asyncData upon page refresh\nTags: vuex, nuxt.js, vue-ssr\nSource: Stack Overflow\n\nQuestion:\nUpon first page refresh, the asyncData function is not able to fetch the persisted state. When I another NuxtLink, and go back to this page, while the state is not mutated in the meantime, the data is there. This means the persisted state is not available on the server side at first load/refresh. LocalStorage is where I choose to persist the relevant state items.\n\nA pages component that uses asyncData:\n\n```\nasyncData({ app, params, store }) {\n //its not available upon first refresh, but is after following a random nuxtlink and going back\n const cartProducts = store.getters.getCartProducts \n},\n```\n\nstore/index.js is straightforward. Unfortunately, the state is completely empty in asyncData upon first page refresh.\n\n```\ngetCartProducts(state) {\n return state.cart.products\n },\n```\n\nvuex-persist.js imported properly with mode 'client' as recommended in the Github Readme\n\n```\nimport VuexPersistence from 'vuex-persist'\n/** https://github.com/championswimmer/vuex-persist#tips-for-nuxt */\n\nexport default ({ store }) => {\n window.onNuxtReady(() => {\n new VuexPersistence({\n key: 'cartStorage'\n /* your options */\n }).plugin(store)\n })\n}\n```\n\nHow can I make sure the relevant store terms from local storage are persisted **before** asyncData is called?\n\n========================================\n\nCode:\n```text\nasyncData({ app, params, store }) {\n //its not available upon first refresh, but is after following a random nuxtlink and going back\n const cartProducts = store.getters.getCartProducts \n},\n```\n\n```text\ngetCartProducts(state) {\n return state.cart.products\n },\n```\n\n```text\nimport VuexPersistence from 'vuex-persist'\n/** https://github.com/championswimmer/vuex-persist#tips-for-nuxt */\n\nexport default ({ store }) => {\n window.onNuxtReady(() => {\n new VuexPersistence({\n key: 'cartStorage'\n /* your options */\n }).plugin(store)\n })\n}\n```\n\n```text\nlocalstorage\n```\n\n```text\nasyncData\n```\n\n```text\nasyncData\n```\n\n```text\nlocalstorage\n```\n\n========================================\n\nComments:\n- So using state is not the right decision for a shopping cart type implementation then. Server session should work fine. Concept of SSR still confuses me, thanks for the answer once again.\n- @ViBoNaCci ye it might be confusing at first. And yes, its much better to have cart contents on server tied to account if u can. For client persistence only cookies could be used. E.g. some custom module for vuex that use universal-cookie as a storage option or nuxt-universal storage package\n- check out nuxtServerInit for how to populate server data into the store on server load. You're also able to access req/res from asyncData","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":94,"estimatedTokens":703}}640{"id":"stack-60179774","source":"stackoverflow","questionId":60179774,"title":"Server side singleton injection in Nuxt","tags":["vue.js","nuxt.js"],"text":"Title: Server side singleton injection in Nuxt\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI need a shared object (e.g.cache/logger/service) instance (singleton) on serverside accessible to SS middleware/plugins/nuxtserverinit.\n\nI have tried a local module which tries to inject `$cache` in serverside context during `render:done` hook (see below), but no matter what I tried it still was not available during SS request processing.\n\n```\n// modules/myCache.js\nexport default function(_moduleOptions,config) {\n\n this.nuxt.hook(\"render:before\", context => {\n const cache=new myExoticCache()\n\n// I tried all the below combinations\n context.nuxt.$cache1=cache\n context.serverContext.$cache2=cache\n context.options.$cache3=cache\n context.globals.$cache4=cache\n\n });\n\n this.nuxt.hook(\"render:done\", context => {\n\n// tried the above here too \n\n });\n}\n\n// plugins/myplug.js\nexport default ({serverContext,nuxt}, inject) => {\n//all of the below are undefined\n//nuxt.$cache\n//serverContext.$cache\n\n}\n```\n\nSeems like I am missing something. Would be great to find out what.\nHow can I pass value from `route:done` hook to any server-side `middleware/plugin/nuxtserverinit`.\n\n========================================\n\nCode:\n```js\n// modules/myCache.js\nexport default function(_moduleOptions,config) {\n\n this.nuxt.hook(\"render:before\", context => {\n const cache=new myExoticCache()\n\n// I tried all the below combinations\n context.nuxt.$cache1=cache\n context.serverContext.$cache2=cache\n context.options.$cache3=cache\n context.globals.$cache4=cache\n\n });\n\n this.nuxt.hook(\"render:done\", context => {\n\n// tried the above here too \n\n });\n}\n\n// plugins/myplug.js\nexport default ({serverContext,nuxt}, inject) => {\n//all of the below are undefined\n//nuxt.$cache\n//serverContext.$cache\n\n}\n```\n\n```text\n$cache\n```\n\n```text\nrender:done\n```\n\n```text\nroute:done\n```\n\n```text\nmiddleware/plugin/nuxtserverinit\n```\n\n```text\n// modules/myCache.js\nexport default function(_moduleOptions) {\n const $cache = 'CACHE';\n this.nuxt.hook('vue-renderer:ssr:prepareContext', ssrContext => {\n ssrContext.$cache = $cache;\n })\n}\n\n// plugins/myplug.js\nexport default function ({ ssrContext }) {\n if (process.server) {\n console.log(ssrContext.$cache)\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":109,"estimatedTokens":572}}641{"id":"stack-56709366","source":"stackoverflow","questionId":56709366,"title":"Turn off webpack-hot-middleware client overlay in Nuxt application","tags":["vue.js","webpack","nuxt.js","webpack-hot-middleware"],"text":"Title: Turn off webpack-hot-middleware client overlay in Nuxt application\nTags: vue.js, webpack, nuxt.js, webpack-hot-middleware\nSource: Stack Overflow\n\nQuestion:\nI'm trying to turn off the overlay from webpack-hot-middleware in my Nuxt application.\n\nI tried editing the config in nuxt.config.js but the overlay persists.\n\n```\nbuild: {\n // turn off client overlay when errors are present\n hotMiddleware: {\n overlay: false\n },\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n // Run ESLint on save\n if (ctx.isDev && ctx.isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n });\n }\n }\n }\n```\n\n========================================\n\nCode:\n```text\nbuild: {\n // turn off client overlay when errors are present\n hotMiddleware: {\n overlay: false\n },\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n // Run ESLint on save\n if (ctx.isDev && ctx.isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n });\n }\n }\n }\n```\n\n```js\nbuild: {\n hotMiddleware: {\n client: {\n // turn off client overlay when errors are present\n overlay: false\n }\n }\n }\n```\n\n========================================\n\nComments:\n- Yep - that does it. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":73,"estimatedTokens":363}}642{"id":"stack-76753315","source":"stackoverflow","questionId":76753315,"title":"Cannot start Nuxt: Cannot read properties of undefined (reading 'srcDir')","tags":["module","environment-variables","nuxt.js","access-token","spotify"],"text":"Title: Cannot start Nuxt: Cannot read properties of undefined (reading 'srcDir')\nTags: module, environment-variables, nuxt.js, access-token, spotify\nSource: Stack Overflow\n\nQuestion:\nDescription:\nI'm encountering an error while trying to start my Nuxt.js application. The error message I'm seeing is as follows:\n\n```\nCannot start nuxt: Cannot read properties of undefined (reading 'srcDir')\nat module.exports (node_modules\\@nuxtjs\\dotenv\\lib\\module.js:9:24)\nat installModule (/D:/muse/node_modules/@nuxt/kit/dist/index.mjs:2409:101)\nat async initNuxt (/D:/muse/node_modules/nuxt/dist/index.mjs:3237:7)\nat async load (/D:/muse/node_modules/nuxi/dist/chunks/dev.mjs:205:9)\nat async Object.invoke (/D:/muse/node_modules/nuxi/dist/chunks/dev.mjs:249:5)\nat async _main (/D:/muse/node_modules/nuxi/dist/cli.mjs:49:20)\n```\n\nthis is my `package.json` file\n\n```\n{\n \"name\": \"nuxt-app\",\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\",\n \"postinstall\": \"nuxt prepare\"\n },\n \"devDependencies\": {\n \"@nuxt/devtools\": \"latest\",\n \"@nuxtjs/tailwindcss\": \"^6.8.0\",\n \"@types/node\": \"^18.16.19\",\n \"autoprefixer\": \"^10.4.14\",\n \"nuxt\": \"^3.6.3\",\n \"nuxt-icon\": \"^0.4.2\",\n \"postcss\": \"^8.4.26\",\n \"tailwind-scrollbar\": \"^3.0.4\",\n \"tailwindcss\": \"^3.3.3\"\n },\n \"dependencies\": {\n \"@headlessui/vue\": \"^1.7.14\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"@tailwindcss/forms\": \"^0.5.4\",\n \"axios\": \"^1.4.0\",\n \"bootstrap\": \"^5.3.0\",\n \"tailwind-scrollbar-hide\": \"^1.1.7\"\n }\n}\n```\n\nI have tried to investigate the issue and it seems to be related to the @nuxtjs/dotenv module. The error seems to be occurring in the module's code at line 9, where it tries to access a property named 'srcDir' from an object, but it's undefined.\n\nI have already checked my nuxt.config.js file, and the configuration seems to be correct. The @nuxtjs/dotenv module is properly installed in my project, and I have a valid .env file with the required environment variables.\n\nCould anyone help me understand why this error is happening and how to resolve it? Any insights or suggestions would be greatly appreciated.\nI'm ready to also provide as much details as needed.\nThank you.\n\nHere is my nuxtconfig.js file\n\n```\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n modules: [\"@nuxtjs/tailwindcss\", \"nuxt-icon\", \"@nuxtjs/dotenv\"],\n css: [\"@/assets/css/main.css\"],\n postcss: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n },\n app: {\n head: {\n title: \"Muse\",\n meta: [\n {\n name: \"description\",\n content: \"\",\n },\n ],\n link: [{}],\n },\n },\n});\n```\n\n========================================\n\nCode:\n```text\nCannot start nuxt: Cannot read properties of undefined (reading 'srcDir')\nat module.exports (node_modules\\@nuxtjs\\dotenv\\lib\\module.js:9:24)\nat installModule (/D:/muse/node_modules/@nuxt/kit/dist/index.mjs:2409:101)\nat async initNuxt (/D:/muse/node_modules/nuxt/dist/index.mjs:3237:7)\nat async load (/D:/muse/node_modules/nuxi/dist/chunks/dev.mjs:205:9)\nat async Object.invoke (/D:/muse/node_modules/nuxi/dist/chunks/dev.mjs:249:5)\nat async _main (/D:/muse/node_modules/nuxi/dist/cli.mjs:49:20)\n```\n\n```text\n{\n \"name\": \"nuxt-app\",\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\",\n \"postinstall\": \"nuxt prepare\"\n },\n \"devDependencies\": {\n \"@nuxt/devtools\": \"latest\",\n \"@nuxtjs/tailwindcss\": \"^6.8.0\",\n \"@types/node\": \"^18.16.19\",\n \"autoprefixer\": \"^10.4.14\",\n \"nuxt\": \"^3.6.3\",\n \"nuxt-icon\": \"^0.4.2\",\n \"postcss\": \"^8.4.26\",\n \"tailwind-scrollbar\": \"^3.0.4\",\n \"tailwindcss\": \"^3.3.3\"\n },\n \"dependencies\": {\n \"@headlessui/vue\": \"^1.7.14\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"@tailwindcss/forms\": \"^0.5.4\",\n \"axios\": \"^1.4.0\",\n \"bootstrap\": \"^5.3.0\",\n \"tailwind-scrollbar-hide\": \"^1.1.7\"\n }\n}\n```\n\n```text\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n modules: [\"@nuxtjs/tailwindcss\", \"nuxt-icon\", \"@nuxtjs/dotenv\"],\n css: [\"@/assets/css/main.css\"],\n postcss: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n },\n app: {\n head: {\n title: \"Muse\",\n meta: [\n {\n name: \"description\",\n content: \"\",\n },\n ],\n link: [{}],\n },\n },\n});\n```\n\n```text\npackage.json\n```\n\n```text\nprocess.env.variableName\n```\n\n========================================\n\nComments:\n- Its not necessary to use @nuxtjs/dotenv for environment variables. You have configure nuxt.config.js file with only by .env file. Can we see your nuxt.config.js file?\n- Hi @miltonbhowmick , I deleted the `@nuxtjs/dotenv\"` within my `nuxt.config.js` and the app is able to load again. Thank you so much for your help.","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":174,"estimatedTokens":1202}}643{"id":"stack-60981046","source":"stackoverflow","questionId":60981046,"title":"Nuxt Apollo websockets link options?","tags":["websocket","nuxt.js","apollo","subscription"],"text":"Title: Nuxt Apollo websockets link options?\nTags: websocket, nuxt.js, apollo, subscription\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get websocket subscriptions working with Nuxt Apollo. For my server (8base.com) I need to send along a `connectionParams` object with the subscription request. \n\nIt seems Nuxt Apollo has a `httpLinkOptions` but what I really need is a `wssLinkOptions`. Anyone know of a way to do this with Nuxt? Ideally I don't have to replace Nuxt Apollo, as I'm using it all throughout the app.\n\n========================================\n\nTop Answer:\nAccording to the docs, you can setup a subscription as a WebSocketLink.\n\nhttps://www.npmjs.com/package/@nuxtjs/apollo/v/3.0.4#example-with-subscription-graphcool-as-example\n\n```\n// Set up subscription\n const wsLink = new WebSocketLink({\n uri: `wss://subscriptions.graph.cool/v1/${process.env.GRAPHQL_ALIAS}`,\n options: {\n reconnect: true,\n connectionParams: () => {\n const token = process.server ? ctx.req.session : window.__NUXT__.state.session\n return {\n Authorization: token ? `Bearer ${token}` : null\n }\n }\n }\n })\n```\n\nAnd here's the full example:\n\nNuxt Config:\n\n```\n// nuxt.config.js\napollo:{\n clientConfigs:{\n default: '~/apollo/client-configs/default.js'\n }\n}\n```\n\nDefault Client Config:\n\n```\n// apollo/client-configs/default.js\nimport { ApolloLink, concat, split } from 'apollo-link'\nimport { HttpLink } from 'apollo-link-http'\nimport { InMemoryCache } from 'apollo-cache-inmemory'\nimport { WebSocketLink } from 'apollo-link-ws'\nimport { getMainDefinition } from 'apollo-utilities'\nimport 'subscriptions-transport-ws' // this is the default of apollo-link-ws\n\nexport default (ctx) => {\n const httpLink = new HttpLink({uri: 'https://api.graph.cool/simple/v1/' + process.env.GRAPHQL_ALIAS})\n const authMiddleware = new ApolloLink((operation, forward) => {\n const token = process.server ? ctx.req.session : window.__NUXT__.state.session\n operation.setContext({\n headers: {\n Authorization: token ? `Bearer ${token}` : null\n }\n })\n return forward(operation)\n })\n // Set up subscription\n const wsLink = new WebSocketLink({\n uri: `wss://subscriptions.graph.cool/v1/${process.env.GRAPHQL_ALIAS}`,\n options: {\n reconnect: true,\n connectionParams: () => {\n const token = process.server ? ctx.req.session : window.__NUXT__.state.session\n return {\n Authorization: token ? `Bearer ${token}` : null\n }\n }\n }\n })\n\n const link = split(\n ({query}) => {\n const {kind, operation} = getMainDefinition(query)\n return kind === 'OperationDefinition' && operation === 'subscription'\n },\n wsLink,\n httpLink\n )\n\n return {\n link: concat(authMiddleware, link),\n cache: new InMemoryCache()\n }\n}\n```\n\nThe Client Config subscription should work using the Vue Apollo model: https://apollo.vuejs.org/guide/apollo/subscriptions.html#setup\n\nIf you just need the basics, you may also be able to just specify your HTTP and WS endpints:\n\n```\napollo:{\n clientConfigs:{\n default:{\n httpEndpoint: YOUR_ENDPOINT,\n wsEndpoint: YOUR_WS_ENDPOINT\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nconnectionParams\n```\n\n```text\nhttpLinkOptions\n```\n\n```text\nwssLinkOptions\n```\n\n```text\nplugins: [\n { src: \"~/plugins/apollo-ws-client.js\", mode: \"client\" }\n ],\n apollo: {\n clientConfigs: {\n default: \"~/plugins/apollo-config-default.js\"\n }\n },\n```\n\n```text\nexport default function() {\n return {\n httpEndpoint: \"https://api.8base.com/123456\",\n wsEndpoint: \"wss://ws.8base.com\"\n }\n}\n```\n\n```text\nexport default ({ app }) => {\n const client = app.apolloProvider.defaultClient\n const token = app.$apolloHelpers.getToken()\n\n if (token) {\n client.wsClient.lazy = true\n client.wsClient.reconnect = true\n client.wsClient.connectionParams = () => {\n return {\n workspaceId: \"123456\",\n token: token\n }\n }\n }\n}\n```\n\n```text\nwsClient\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nplugins/apollo-config-default.js\n```\n\n```text\nplugins/apollo-ws-client.js\n```\n\n```text\n// Set up subscription\n const wsLink = new WebSocketLink({\n uri: `wss://subscriptions.graph.cool/v1/${process.env.GRAPHQL_ALIAS}`,\n options: {\n reconnect: true,\n connectionParams: () => {\n const token = process.server ? ctx.req.session : window.__NUXT__.state.session\n return {\n Authorization: token ? `Bearer ${token}` : null\n }\n }\n }\n })\n```\n\n```text\n// nuxt.config.js\napollo:{\n clientConfigs:{\n default: '~/apollo/client-configs/default.js'\n }\n}\n```\n\n```text\n// apollo/client-configs/default.js\nimport { ApolloLink, concat, split } from 'apollo-link'\nimport { HttpLink } from 'apollo-link-http'\nimport { InMemoryCache } from 'apollo-cache-inmemory'\nimport { WebSocketLink } from 'apollo-link-ws'\nimport { getMainDefinition } from 'apollo-utilities'\nimport 'subscriptions-transport-ws' // this is the default of apollo-link-ws\n\nexport default (ctx) => {\n const httpLink = new HttpLink({uri: 'https://api.graph.cool/simple/v1/' + process.env.GRAPHQL_ALIAS})\n const authMiddleware = new ApolloLink((operation, forward) => {\n const token = process.server ? ctx.req.session : window.__NUXT__.state.session\n operation.setContext({\n headers: {\n Authorization: token ? `Bearer ${token}` : null\n }\n })\n return forward(operation)\n })\n // Set up subscription\n const wsLink = new WebSocketLink({\n uri: `wss://subscriptions.graph.cool/v1/${process.env.GRAPHQL_ALIAS}`,\n options: {\n reconnect: true,\n connectionParams: () => {\n const token = process.server ? ctx.req.session : window.__NUXT__.state.session\n return {\n Authorization: token ? `Bearer ${token}` : null\n }\n }\n }\n })\n\n const link = split(\n ({query}) => {\n const {kind, operation} = getMainDefinition(query)\n return kind === 'OperationDefinition' && operation === 'subscription'\n },\n wsLink,\n httpLink\n )\n\n return {\n link: concat(authMiddleware, link),\n cache: new InMemoryCache()\n }\n}\n```\n\n```text\napollo:{\n clientConfigs:{\n default:{\n httpEndpoint: YOUR_ENDPOINT,\n wsEndpoint: YOUR_WS_ENDPOINT\n }\n }\n}\n```\n\n```text\nmodules: [\n '@nuxtjs/apollo',\n ],\n apollo: {\n clientConfigs: {\n default: {\n httpEndpoint: 'your_graphql_url'\n }\n }\n },\n env: {\n WS_URL: 'ws://you_url/ws',\n }\n```\n\n========================================\n\nComments:\n- Hey Drew, did you end up finding a solution for this? I'm having exactly same issue but the answers don't work for me.\n- @KatieKim yeah see accepted answer. But ultimately we stopped using Nuxt Apollo as it was just really buggy. We use GraphQL Request now and have never had any problems with it.\n- Thanks good find, that is the old docs, so curious if it works, but I will try it out.\n- I'm unable to figure out how to merge this example with the current way Nuxt Apollo wants to setup Apollo: github.com/nuxt-community/apollo-module\n- I added some more detail, specifically, how the Nuxt config loads the Client Config Subscription. Hope it's more helpful :)\n- how do you add headers to that? mine are completely ignored\n- Yes, but how do you then set a headers on that?\n- on nuxt.config just add these lines","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":294,"estimatedTokens":1819}}644{"id":"stack-61889192","source":"stackoverflow","questionId":61889192,"title":"vue-awesome-swiper(swiperjs) on Nuxt js not working in production but works on dev","tags":["vue.js","vuejs2","nuxt.js","swiper.js"],"text":"Title: vue-awesome-swiper(swiperjs) on Nuxt js not working in production but works on dev\nTags: vue.js, vuejs2, nuxt.js, swiper.js\nSource: Stack Overflow\n\nQuestion:\nI am using vue-awesome-swiper and have followed the steps here: https://github.com/surmon-china/vue-awesome-swiper. I have opted to register this plugin globally in Nuxt js. \n\n**PROBLEM**: The Dev works perfectly fine, the slides are on each page and the navigation works. The production, on the other hand, has all the slides on page one, the navigation works here leaving the other pages blank as all slides are on the first page. \n\nOn dev:\nhttps://i.sstatic.net/55AN8.png\n\nOn production:\nhttps://i.sstatic.net/poz3h.png\n\nThese are my files:\n\nplugins/VueAwesomeSwiper.js\n\n```\nimport Vue from 'vue';\nimport VueAwesomeSwiper from 'vue-awesome-swiper';\n\n// import style\nimport 'swiper/css/swiper.css';\n\nVue.use(VueAwesomeSwiper);\n```\n\nnuxt.config.js\n\n```\n...\ncss: [], TheSlider.vue\n\n```\n\n \n \n Slide 1\n Slide 2\n Slide 3\n Slide 4\n Slide 5\n Slide 6\n Slide 7\n Slide 8\n Slide 9\n Slide 10\n \n \n \n \n\nimport { Component, Vue } from 'vue-property-decorator';\n\n@Component\nexport default class TheSlider extends Vue {\n swiperOption = {\n navigation: {\n nextEl: '.swiper-button-next',\n prevEl: '.swiper-button-prev',\n },\n };\n}\n\n```\n\nI am not sure what I am doing wrong. Could someone help? Thanks!\n\n========================================\n\nTop Answer:\nCheck out swiper version, if you are using Swiper 6.0.0 or higher, import this css file:\n\nplugins/VueAwesomeSwiper.js\n\n```\nimport 'swiper/swiper-bundle.css'\n```\n\nif Swiper version is 5.* or lower import this file:\n\nplugins/VueAwesomeSwiper.js\n\n```\nimport 'swiper/css/swiper.css'\n```\n\nAfter installing, if pagination not working, downgrade your Swiper version to 5.*\n\nCheckout this links:\n\nhttps://github.com/surmon-china/vue-awesome-swiper \n\nhttps://github.com/surmon-china/surmon-china.github.io/tree/source/projects/vue-awesome-swiper/nuxt\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue';\nimport VueAwesomeSwiper from 'vue-awesome-swiper';\n\n// import style\nimport 'swiper/css/swiper.css';\n\nVue.use(VueAwesomeSwiper);\n```\n\n```text\n...\ncss: [], <--- Do I need to add something to add here?\nplugins: [\n { src: '~/plugins/VueAwesomeSwiper.js' },\n ]\n...\n```\n\n```text\n<template>\n <div>\n <swiper class=\"swiper\" :options=\"swiperOption\">\n <swiper-slide>Slide 1</swiper-slide>\n <swiper-slide>Slide 2</swiper-slide>\n <swiper-slide>Slide 3</swiper-slide>\n <swiper-slide>Slide 4</swiper-slide>\n <swiper-slide>Slide 5</swiper-slide>\n <swiper-slide>Slide 6</swiper-slide>\n <swiper-slide>Slide 7</swiper-slide>\n <swiper-slide>Slide 8</swiper-slide>\n <swiper-slide>Slide 9</swiper-slide>\n <swiper-slide>Slide 10</swiper-slide>\n <div slot=\"button-prev\" class=\"swiper-button-prev\"></div>\n <div slot=\"button-next\" class=\"swiper-button-next\"></div>\n </swiper>\n </div>\n</template>\n\n<script lang=\"ts\">\nimport { Component, Vue } from 'vue-property-decorator';\n\n@Component\nexport default class TheSlider extends Vue {\n swiperOption = {\n navigation: {\n nextEl: '.swiper-button-next',\n prevEl: '.swiper-button-prev',\n },\n };\n}\n</script>\n\n<style>\n\n</style>\n```\n\n```text\n<div v-swiper=\"swiperOption\">\n <div class=\"swiper-wrapper\">\n <div class=\"swiper-slide\">\n Render original HTML in server, render Swiper in browser (client)\n </div>\n </div>\n</div>\n```\n\n```text\nimport 'swiper/swiper-bundle.css'\n```\n\n```text\nimport 'swiper/css/swiper.css'\n```\n\n```text\nexport default {\n // some nuxt config...\n plugins: [\n { src: '@/plugins/nuxt-swiper-plugin.js', ssr: false },\n ],\n // some nuxt config...\n css: [\n // swiper style\n 'swiper/css/swiper.css'\n ],\n // some nuxt config...\n}\n```\n\n========================================\n\nComments:\n- did your pagination work? mine doesnt work now\n- SSR link is broken","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":196,"estimatedTokens":988}}645{"id":"stack-67686956","source":"stackoverflow","questionId":67686956,"title":"How to access remote data and write it into a file during Nuxt build?","tags":["json","vue.js","nuxt.js"],"text":"Title: How to access remote data and write it into a file during Nuxt build?\nTags: json, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm new to Nuxt JS. And am trying to figure out how to download a JSON file from a remote URL source to use locally as part of the nuxt build process?\n\nSo, for example, if the JSON file is at:\n\n```\nhttps://path/to/my/json\n```\n\nThen in my nuxt app, I DON'T want to connect to that JSON file remotely, but rather use it locally. So, when I publish my site, I don't want it to be dependent on the external resource.\n\nAt the moment, I'm accomplishing this with gulp, using the `gulp-download-files` plugin.\n\n========================================\n\nCode:\n```text\nhttps://path/to/my/json\n```\n\n```text\ngulp-download-files\n```\n\n```js\nimport fs from 'fs'\nimport axios from 'axios'\n\naxios('https://jsonplaceholder.typicode.com/todos/1').then((response) => {\n fs.writeFile('todos_1.json', JSON.stringify(response.data, null, 2), 'utf-8', (err) => {\n if (err) return console.log('An error happened', err)\n console.log('File fetched from {JSON} Placeholder and written locally!')\n })\n})\n\nexport default {\n target: 'static',\n ssr: false,\n // your usual nuxt.config.js file...\n}\n```\n\n```text\naxios\n```\n\n```text\nyarn add -D axios\n```\n\n```text\n.json\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- Can you download the file and put it locally in your project?\n- Yes, but I don't want to do this manually. Especially as this means each time the JSON file changes, I'd have to remember to download the file manually again. Automating this step into the build process appears to be the more sensible solution\n- But, you told us that you don't want to download it right? I mean, what's the difference between using a remote file and downloading it to use it locally? If it is not available at the time of build, you won't be able to have it locally neither. You can't download it (`axios`) or you don't know how to write a JSON down locally (`node's fs`)? Because you could totally inject the JSON itself into your build step by fetching the file (at build time).\n- Re: \"Because you could totally inject the JSON itself into your build step by fetching the file (at build time)\": That's what I'm trying to do. I don't know how/where to write the node js to fetch the JSON. Does that make sense?","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":73,"estimatedTokens":598}}646{"id":"stack-70225561","source":"stackoverflow","questionId":70225561,"title":"Vue js pass a function from child chile to another child component on a click event","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Vue js pass a function from child chile to another child component on a click event\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to pass a function when a button is clicked, the button is clicked in a child element, then passed through a parent element to another child component, and i dont want to use the store for that, How can i do that?\n\ncomponents/footer/footer.vue\n-- This is where the button is clicked\n\n```\n\n \n \n \n\nexport default {\n methods: {\n showMenu() {\n this.$emit(\"show-menu\");\n }\n }\n}\n\n```\n\nlayouts/default.vue\n--This is the parent component where that receives the click function and is to pass it into the `app-header`\n\n```\n\n \n \n \n \n \n\nimport header from \"~/components/header/header\";\nimport footer from \"~/components/footer/footer\";\n\nexport default {\n components: {\n 'app-header': header,\n 'app-footer': footer\n },\n methods: {\n showMenu() {\n console.log(\"clicked\");\n }\n }\n}\n\n```\n\ncomponents/header/header.vue\n-- I want the click function to perform an action inside this component\n\n```\n\nexport default {\n data() {\n return {\n showMenuBar: false\n }\n },\n}\n\n```\n\n========================================\n\nTop Answer:\nWhy are you worried about passing a function around?\n\nWhen you `emit` the `show-menu` event simply toggle a piece of data in your parent component like this:\n\n```\n\n \n \n \n \n \n\nimport header from \"~/components/header/header\";\nimport footer from \"~/components/footer/footer\";\n\nexport default {\n components: {\n 'app-header': header,\n 'app-footer': footer\n },\n data() {\n return {\n showMenuBar: false;\n };\n },\n methods: {\n showMenu() {\n // I would make this more dynamic than always\n // hardcoding it to true, but you get the idea\n this.showMenuBar = true;\n }\n }\n}\n\n```\n\nThen in your `AppHeader` simply take it in as a prop:\n\n```\n\nexport default {\n props: {\n showMenuBar: { \n type: Boolean, \n default: false,\n },\n}\n\n```\n\n========================================\n\nCode:\n```html\n<template>\n <div class=\"footer-bottom-header-menu-bar mob\" @click=\"showMenu\">\n <img src=\"~/assets/svg/menubar.svg\" alt=\"+\" />\n </div>\n</template>\n\n<script>\nexport default {\n methods: {\n showMenu() {\n this.$emit(\"show-menu\");\n }\n }\n}\n</script>\n```\n\n```html\n<template>\n <div>\n <app-header />\n <Nuxt />\n <app-footer @show-menu=\"showMenu()\"/>\n </div>\n</template>\n\n<script>\nimport header from \"~/components/header/header\";\nimport footer from \"~/components/footer/footer\";\n\nexport default {\n components: {\n 'app-header': header,\n 'app-footer': footer\n },\n methods: {\n showMenu() {\n console.log(\"clicked\");\n }\n }\n}\n</script>\n```\n\n```html\n<script>\nexport default {\n data() {\n return {\n showMenuBar: false\n }\n },\n}\n</script>\n```\n\n```text\napp-header\n```\n\n```text\ndata() {\n return { toBeWatched: 0 };\n}\n```\n\n```text\n<script>\nexport default {\n data() {\n return {\n showMenuBar: false\n };\n },\n props: ['Trigger'],\n watch: {\n Trigger() {\n this.showMenuBar = !this.showMenuBar; // or do whatever you want\n console.log('showMenuBar : ' + this.showMenuBar);\n }\n }\n};\n</script>\n```\n\n```text\n<app-header :Trigger=\"toBeWatched\" />\n```\n\n```text\n@show-menu\n```\n\n```text\n<app-footer @show-menu=\"toBeWatched++\" />\n```\n\n```html\n<template>\n <div>\n <app-header :showMenuBar=\"showMenuBar\" />\n <Nuxt />\n <app-footer @show-menu=\"showMenu\"/>\n </div>\n</template>\n\n<script>\nimport header from \"~/components/header/header\";\nimport footer from \"~/components/footer/footer\";\n\nexport default {\n components: {\n 'app-header': header,\n 'app-footer': footer\n },\n data() {\n return {\n showMenuBar: false;\n };\n },\n methods: {\n showMenu() {\n // I would make this more dynamic than always\n // hardcoding it to true, but you get the idea\n this.showMenuBar = true;\n }\n }\n}\n</script>\n```\n\n```html\n<script>\nexport default {\n props: {\n showMenuBar: { \n type: Boolean, \n default: false,\n },\n}\n</script>\n```\n\n```text\nemit\n```\n\n```text\nshow-menu\n```\n\n```text\nAppHeader\n```\n\n========================================\n\nComments:\n- ... pass it via the event bus?\n- @vector pretty much the same as `store` tbh.\n- If you don't want to use a store for that, you need to do it the other way: `emit` + `listener`, and trigger some methods. PS: passing a function down or up is an anti-pattern in Vue (it is common in React tho).","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":287,"estimatedTokens":1143}}647{"id":"stack-73771557","source":"stackoverflow","questionId":73771557,"title":"Migrating to Nuxt 3 from Vue 2?","tags":["javascript","vue.js","nuxt.js","nuxt3.js"],"text":"Title: Migrating to Nuxt 3 from Vue 2?\nTags: javascript, vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nThere is a medium-sized application written in Vue 2.7 (vuex, vue-router, etc.).\n\nUntil a certain point, we had SSR \"with our own hands.\" Works crookedly and slowly, but works.\n\nRecently, it has ceased to satisfy the needs of the project and we realized that we would be migrating to Nuxt.\n\nRelatively recently, Nuxt 3 was released. It is now in rc state. We are betting on the further development of Nuxt. Therefore, we want to migrate to version 3. In addition, I think that in the near future we will consider switching to TypeScript, and in Nuxt 3 TS support is at a good level.\n\nBut there is an ambiguity: Nuxt 3 works with Vue 3. Also, it is recommended to use pinia instead of Vuex.\n\nIn this regard, questions:\n\n- Will most components work on Vue 2 when using Nuxt 3? I also want to move to Vue 3, but for now we want to speed up the process as much as possible. But I don't want to use crutches like \"Vue 3 Migration Build\" either.\n\n- Is Pinia definitively replacing Vuex? I mean, is Vuex going to be obsolete anytime soon?\n\n- Maybe there are more pitfalls that you should know BEFORE moving?\n\n========================================\n\nCode:\n```text\nuseAsyncData\n```\n\n========================================\n\nComments:\n- I did a Vue 2 => Vue 3 upgrade on a big client project recently. I think the difficulty largely depends on which libraries you are using and whether they are compatible. We had troubles with our extensive dependency on `bootstrap-vue` and `vue-class-component` in particular, which are not Vue 3 friendly.\n- \"Will most components work on Vue 2 when using Nuxt 3\" - your primary concern is Vue 3 compatibility, not Nuxt. No, a lot of them don't work if they aren't written with V2/3 compatibility in mind. \"Is Pinia definitively replacing Vuex\" - it's a replacement for unreleased Vuex 5. Pinia is more TS-friendly than Vuex\n- Read the Pinia documentation, like everything from vuejs, it's thorough and very easy to read, there are a couple of gotchas, though I think I misread the documentation to be honest - I can also tell you the pain in upgrading vue2 to vue3 is mainly other frameworks compatibility - in my case, vuetify\n- @Toggle, We are using a few components from bootstrap-vue: \"^2.15.0\". And also vuelidate. There are others, but they all have a very low of the codebase.\n- @kissu, No, my manager is pulling, because during the migration there will be no introduction of new functionality. However, we are still going to start in a week or two. Will post here when there is news","metadata":{"transformedAt":"2026-08-18T18:33:07.883Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":38,"estimatedTokens":660}}648{"id":"stack-78552115","source":"stackoverflow","questionId":78552115,"title":"Hydration completed but contains mismatches using VeeValidate and Pinia in Nuxt","tags":["nuxt.js","nuxt3.js","pinia","vee-validate","primevue"],"text":"Title: Hydration completed but contains mismatches using VeeValidate and Pinia in Nuxt\nTags: nuxt.js, nuxt3.js, pinia, vee-validate, primevue\nSource: Stack Overflow\n\nQuestion:\nthis week I'm having a weird error into my Nuxt app, it's a small app, it's only a landing page with a register form for an event, I worked on this last week and I published it and it works fine.\nNow, I have to add some modifications into the register form, nothing complex, but when I ran the project locally, without update anything, and I'm getting now a hydration error into the fields 😢.\nAgain, it's too weird for me because I don't update or change anything, Im running the exactly code version that is published, and if I run the build and preview cmd, I'm having the same error.\n\nNow, the code:\n\nInto the form I'm using this stack:\n\n- PrimeVue InputText\n\n- VeeValidate with Zod\n\n- Pinia for store the data because the form has different steps.\n\nIn my component I do this:\n\n```\nconst registerFormStore = useRegisterFormStore();\n\nconst validationSchema = toTypedSchema(\n object({\n [DocumentFormFields.DOCUMENT_ID]: z\n .string({ required_error: 'Ingresa tu documento de identificación' })\n .min(6, 'error message')\n .max(15, 'error message')\n .transform((value) => value.trim().toLocaleUpperCase())\n .default(registerFormStore.personalInfo.documentId || '')\n })\n);\nconst { errors, handleSubmit, defineField, setErrors } = useForm({\n validationSchema\n});\n\nconst formValues = reactive({\n documentId: defineField(DocumentFormFields.DOCUMENT_ID)[0]\n});\n```\n\n```\n\n \n Document Label\n \n \n \n \n \n \n \n {{ errors[DocumentFormFields.DOCUMENT_ID] }}\n \n \n \n \n```\n\nand now I'm having the hydration error:\n\nhttps://i.sstatic.net/zOgmMmR5.png\n\n```\n[Vue warn]: Hydration attribute mismatch on \n - rendered on server: (not rendered)\n - expected on client: value=\"\"\n Note: this mismatch is check-only. The DOM will not be rectified in production due to performance overhead.\n You should fix the source of the mismatch. \n at \n at \n at \n at \n at \n at ref=Ref > \n at \n at \n at \n at \n at \n```\n\nAnd later, all the other steps into my form are broken, for example, when I change to the next step, I load the documentId and the username, and the fields now are broken and don't take the default value:\n\n```\nconst validationSchema = toTypedSchema(\n object({\n [PersonalInfoFormFields.NAME]: z\n .string({ required_error: 'error text' })\n .min(2, 'error text')\n .max(100, 'error text')\n .transform((value) => value.trim())\n .default(registerFormStore.personalInfo.name || ''),\n [PersonalInfoFormFields.EMAIL]: z\n .string({ required_error: 'error text' })\n .email('error text')\n .transform((value) => value.trim().toLocaleLowerCase())\n .default(registerFormStore.personalInfo.email || '')\n```\n\nThe data into the store is OK, but into the fields not\n\nhttps://i.sstatic.net/CxGH16rk.png\n\nLook that all the fields are undefined when it should be with an empty string\n\nI already work and search about this error but I don't have any idea why it's happening. 🥲\nI'm not sure if it's related with Pinia, because the console of store installed\n\nhttps://i.sstatic.net/65Y4C3lB.png\n\nbut the weird think is that I do not update any library version or similar.\n\nAny help is welcome!, thanks in advance.\n\n========================================\n\nTop Answer:\nAfter fixing a hydration mismatch due to `Date.now()`, OP found that the issue was a vee-validate function.\n\n========================================\n\nCode:\n```js\nconst registerFormStore = useRegisterFormStore();\n\n\nconst validationSchema = toTypedSchema(\n object({\n [DocumentFormFields.DOCUMENT_ID]: z\n .string({ required_error: 'Ingresa tu documento de identificación' })\n .min(6, 'error message')\n .max(15, 'error message')\n .transform((value) => value.trim().toLocaleUpperCase())\n .default(registerFormStore.personalInfo.documentId || '')\n })\n);\nconst { errors, handleSubmit, defineField, setErrors } = useForm({\n validationSchema\n});\n\nconst formValues = reactive({\n documentId: defineField<DocumentFormFields.DOCUMENT_ID, string>(DocumentFormFields.DOCUMENT_ID)[0]\n});\n```\n\n```html\n<form class=\"flex flex-col gap-5\" @submit.prevent=\"onSubmitForm\">\n <div class=\"flex flex-col gap-2\">\n <label for=\"documentId\" class=\"font-medium\">Document Label</label>\n <IconField icon-position=\"left\">\n <InputIcon class=\"pi pi-id-card\" />\n <InputText\n id=\"documentId\"\n v-model=\"formValues.documentId\"\n placeholder=\"Placeholder text\"\n class=\"w-full\"\n maxlength=\"15\"\n :disabled=\"isLoading\"\n :invalid=\"Boolean(errors[DocumentFormFields.DOCUMENT_ID])\"\n />\n </IconField>\n \n <transition name=\"fade\">\n <small v-if=\"errors[DocumentFormFields.DOCUMENT_ID]\" class=\"text-sm text-danger\">\n {{ errors[DocumentFormFields.DOCUMENT_ID] }}\n </small>\n </transition>\n </div>\n </form>\n```\n\n```text\n[Vue warn]: Hydration attribute mismatch on <input class=\"p-inputtext p-component w-full\" id=\"documentId\" placeholder=\"Escribe tu documento de identidad\" maxlength=\"15\" data-pc-name=\"inputtext\" data-pc-section=\"root\"> \n - rendered on server: (not rendered)\n - expected on client: value=\"\"\n Note: this mismatch is check-only. The DOM will not be rectified in production due to performance overhead.\n You should fix the source of the mismatch. \n at <InputText id=\"documentId\" modelValue=\"\" onUpdate:modelValue=fn ... > \n at <IconField icon-position=\"left\" > \n at <DocumentValidationForm key=3 > \n at <RegistrationComponent key=2 > \n at <FormSection> \n at <Index onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > \n at <Anonymous key=\"/\" vnode= {__v_isVNode: true, __v_skip: true, type: {…}, props: {…}, key: null, …} route= {fullPath: '/', hash: '', query: {…}, name: 'index', path: '/', …} ... > \n at <RouterView name=undefined route=undefined > \n at <NuxtPage> \n at <App key=3 > \n at <NuxtRoot>\n```\n\n```js\nconst validationSchema = toTypedSchema(\n object({\n [PersonalInfoFormFields.NAME]: z\n .string({ required_error: 'error text' })\n .min(2, 'error text')\n .max(100, 'error text')\n .transform((value) => value.trim())\n .default(registerFormStore.personalInfo.name || ''),\n [PersonalInfoFormFields.EMAIL]: z\n .string({ required_error: 'error text' })\n .email('error text')\n .transform((value) => value.trim().toLocaleLowerCase())\n .default(registerFormStore.personalInfo.email || '')\n```\n\n```js\nconst validationSchema = toTypedSchema(\n object({\n [PersonalInfoFormFields.EMAIL]: z\n .string({ required_error: 'error message' })\n .email('error message')\n .transform((value) => value.trim().toLocaleLowerCase())\n .default(registerFormStore.personalInfo.email || ''),\n [PersonalInfoFormFields.REPEAT_EMAIL]: z\n .string({ required_error: 'error message' })\n .email('error message')\n .transform((value) => value.trim().toLocaleLowerCase())\n .default('')\n }).refine(({ email, repeatEmail }) => email === repeatEmail, {\n message: 'error message',\n path: [PersonalInfoFormFields.REPEAT_EMAIL]\n })\n);\n```\n\n```text\nDate.now()\n```\n\n```text\nref()\n```\n\n```text\nconst myVar = ref(Date.now());\n```\n\n```text\nref\n```\n\n```text\nonMounted\n```\n\n```text\nmyVar.value = Date.now()\n```\n\n```text\nrefine\n```\n\n```text\nrefine\n```\n\n```text\nDate.now()\n```\n\n========================================\n\nComments:\n- There is obviously some difference between the server and the client side of things. Maybe check your code for specific parts of the code that would show that the input is not in the DOM. Maybe you're doing some calls only on client-side too?\n- Nop, only mounting the form section and nothing more\n- Do you know that the mounting lifecycle is a client-side-only lifecycle? There is no DOM to mount on the server.\n- @kissu you are right, I had a `const actualTimeStamp = ref(Date.now());` that maybe causes that error, I set it initial as 0 and latter in onMounted set the real value, it remove the hydratation message, but, now I continue with the error that all the fields are as undefined\n- All the values are OK into pinia (I check it into vue devtools), but in the formValues object, all are in undefined by default\n- Don't use `Date.now()` because its value will be different from the server to the client (few ms for the hydration). I am not sure for the second part and I do not use `reactive` either, I prefer the regular `ref`.\n- It's beause is an object with all the form fields, is the same, but the error seems to be that the pinia store was not instantiated or similar, but in the console I'm not getting any error or warn\n- You need to wait for the Pinia store to be populated. Don't expect your object to have any values if it's not reactive or the store comes later on.\n- I found that the problem is solved if I remove a refine vee-validate function (used for validate that two fields are equal), I really don't know why it was causing the glitch\n- All of this is probably a matter of lifecycles + priority that some packages might have. Might be fixed with a `nextTick` but depending on the context might not be that easy to write either.\n- Yes, it make sense, I'll try to reproduce it in a more simple example and try to report the bug to vee-validate and/or zod\n- I added a more complete answer, but thanks for the help!!\n- Here are some other possible causes for a hydration mismatch: stackoverflow.com/a/67978474/8816585","metadata":{"transformedAt":"2026-08-18T18:33:07.884Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":281,"estimatedTokens":2385}}649{"id":"stack-60862047","source":"stackoverflow","questionId":60862047,"title":"How to include .d.ts file manually(locally)? Or How to use a user defined .d.ts file?","tags":["typescript","vue.js","vuejs2","nuxt.js"],"text":"Title: How to include .d.ts file manually(locally)? Or How to use a user defined .d.ts file?\nTags: typescript, vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm studying nuxt.js and due to some reason I want to extend Vue's instance like this:\n\n```\nimport Vue from 'vue'\n\nVue.prototype.$myProp = 'test'\n\nconst app = new Vue()\n\nconsole.log(app.$myProp)\n```\n\nFollowing the guide at https://v2.vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins, I have create a file at types/test.d.ts with the content bellow:\n\n```\ndeclare module 'vue/types/vue' {\n interface Vue {\n $myProp: string;\n }\n}\n```\n\nHowever, I don't know how to make it works.\n\nI was receiving errors in my VSCode. Also receive errors when I executing tsc(Version 3.7.2):\n\n```\nindex.ts:14:17 - error TS2339: Property '$test' does not exist on type 'CombinedVueInstance>'.\n\n14 console.log(app.$test)\n```\n\nI have tried to using a tsconfig.json in the root directory, but not work:\n\n```\n{\n \"compilerOptions\": {\n \"typeRoots\": [\n \"types/test.d.ts\"\n ]\n }\n}\n```\n\nI have also tried insert a reference like this, but now work:\n\n```\n///\n```\n\nOf course, I don't want to include this declare file in every file. Is there a way to enable the declare in whole project?\n\nI don't know how VSCode works with typescript. Maybe I just make a mistake in config file.\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\n\nVue.prototype.$myProp = 'test'\n\nconst app = new Vue()\n\nconsole.log(app.$myProp)\n```\n\n```text\ndeclare module 'vue/types/vue' {\n interface Vue {\n $myProp: string;\n }\n}\n```\n\n```text\nindex.ts:14:17 - error TS2339: Property '$test' does not exist on type 'CombinedVueInstance<Vue, object, object, object, Record<never, any>>'.\n\n14 console.log(app.$test)\n```\n\n```text\n{\n \"compilerOptions\": {\n \"typeRoots\": [\n \"types/test.d.ts\"\n ]\n }\n}\n```\n\n```text\n///<reference path=\"types/test.d.ts\"/>\n```\n\n```text\n{\n \"include\": [\n \"./types\",\n /* other .ts or .d.ts source code containing folders here */\n ],\n \"compilerOptions\": { ... }\n}\n```\n\n```text\ntypeRoots\n```\n\n```text\n./node_modules/@types\n```\n\n```text\ntypeRoots\n```\n\n```text\ninclude\n```\n\n```text\ntypeRoots\n```\n\n========================================\n\nComments:\n- Thanks a lot! It works when I executing `tsc -p tsconfig.json`. But the editor still shows an error when I attempt to access the property I added. Maybe I have made another mistake in my VSCode config but I don't know how to fix it. This is my first question on stack overflow and I don't know how to use it correctly. Should I open a new question?\n- Just run \"Restart TS Server\" command inside vscode, or try quit and restart vscode might fix it. I encounter this problem quite alot.\n- I have try run \"Restart TS Server\" command and restart vscode. But it doesn't work. Even stranger, it works in another workspace. I don't know how.\n- Probably sth wrong in your local config? Try start a new project to pinpoint the problem. Not much I can do from here. Perhaps you put your tsconfig in wrong place, perhaps your vscode's ts setting is picking up wrong tsconfig file. But i'm pretty sure this solution works.","metadata":{"transformedAt":"2026-08-18T18:33:07.884Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":137,"estimatedTokens":794}}650{"id":"stack-56591941","source":"stackoverflow","questionId":56591941,"title":"how to know when dynamic component has fully loaded","tags":["javascript","vue.js","vuejs2","nuxt.js"],"text":"Title: how to know when dynamic component has fully loaded\nTags: javascript, vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSo I'm loading some components dynamically like so:\n\n```\nconst Page0 = () => import(\"@/components/pages/tutorial/Pages/Page0\")\nconst Page1 = () => import(\"@/components/pages/tutorial/Pages/Page1\")\n```\n\nThere are 10 more pages like this, which will be called depending on the route params.\n\nI was wondering how I would know if a certain Page was loaded, for the purposes of creating a loading screen, and how I would know when it was being switched.\n\nThis is how I'm using it altogether.\n\n```\n\n \n \n \n\n const Page0 = () => import(\"@/components/pages/tutorial/Pages/Page0/index.vue\")\n const Page1 = () => import(\"@/components/pages/tutorial/Pages/Page1/index.vue\")\n\n export default {\n scrollToTop:\n true,\n components:\n {\n Page0,\n Page1,\n },\n computed:\n {\n current_page ()\n {\n return \"Page\" + this.page\n }\n },\n asyncData ({\n route, store, env, params, query, req, res, redirect, error\n })\n {\n return {\n page:\n params.page\n }\n }\n }\n\n```\n\n========================================\n\nCode:\n```text\nconst Page0 = () => import(\"@/components/pages/tutorial/Pages/Page0\")\nconst Page1 = () => import(\"@/components/pages/tutorial/Pages/Page1\")\n```\n\n```text\n<template>\n <div>\n <component :is=\"current_page\"></component>\n </div>\n</template>\n\n<script>\n const Page0 = () => import(\"@/components/pages/tutorial/Pages/Page0/index.vue\")\n const Page1 = () => import(\"@/components/pages/tutorial/Pages/Page1/index.vue\")\n\n export default {\n scrollToTop:\n true,\n components:\n {\n Page0,\n Page1,\n },\n computed:\n {\n current_page ()\n {\n return \"Page\" + this.page\n }\n },\n asyncData ({\n route, store, env, params, query, req, res, redirect, error\n })\n {\n return {\n page:\n params.page\n }\n }\n }\n</script>\n```\n\n```text\n<component :is=\"current_page\" @hook:mounted=\"doSomething\"></component>\n```\n\n```text\n@hook:mounted\n```\n\n========================================\n\nComments:\n- Are you using vue-router?\n- @Phil yes, but I'm changing the pages through the param field, so something like `/tutorial/page/1`, `/tutorial/page/2`, which is in the format of `/tutorial/page/:id`\n- I think `import()` returns a promise, if so usual `.then()` might work.\n- @RichardMatsen I'm calling it in combination with `computed` and `components`. I've updated to show what I'm doing, so I'm not sure how I would fit a `.then` or `await` into there\n- Kewl. I didn't know the lifecycle hooks emit custom events like that. Is that officially documented somewhere?\n- Unfortunately it is not documented somewhere as far as I know.\n- Vue.js Component Hooks as Events\n- @RichardMatsen We're talking about official docs here. Thanks for the link though.\n- I notice your imports aren't dynamic (in codesandbox), switched them over but it's not playing nice so far.\n- @RichardMatsen I was not able to do dynamic imports in code sandbox. I think if you try locally in your machine should work.\n- Cheers, that is a useful feature for managing webpack bundles.","metadata":{"transformedAt":"2026-08-18T18:33:07.884Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":124,"estimatedTokens":839}}651{"id":"stack-53676837","source":"stackoverflow","questionId":53676837,"title":"Registering components globally in Vuejs in subfolders","tags":["javascript","vue.js","webpack","nuxt.js"],"text":"Title: Registering components globally in Vuejs in subfolders\nTags: javascript, vue.js, webpack, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have followed the documentation on the Vuejs website to learn how to register vue components globally.\n\nI have defined that the relative path of the components folder is `./global` and set to look in subfolder to `true` (default false). However, it still doesn't look into subfolders.\n\nI have also console.logged the components keys to see if any vue components are included, but it only returned the components in the global (root) folder.\n\nhttps://v2.vuejs.org/v2/guide/components-registration.html\n\n```\nimport Vue from 'vue'\nimport upperFirst from 'lodash/upperFirst'\nimport camelCase from 'lodash/camelCase'\n\nconst requireComponent = require.context(\n // The relative path of the components folder\n './global',\n // Whether or not to look in subfolders\n true,\n // The regular expression used to match base component filenames\n /[A-Z]\\w+\\.(vue|js)$/\n)\n\nconsole.log(requireComponent.keys())\n\nrequireComponent.keys().forEach(fileName => {\n // Get component config\n const componentConfig = requireComponent(fileName)\n\n // Get PascalCase name of component\n const componentName = upperFirst(\n camelCase(\n // Strip the leading `./` and extension from the filename\n fileName.replace(/^\\.\\/(.*)\\.\\w+$/, '$1')\n )\n )\n\n // Register component globally\n Vue.component(\n componentName,\n // Look for the component options on `.default`, which will\n // exist if the component was exported with `export default`,\n // otherwise fall back to module's root.\n componentConfig.default || componentConfig\n )\n})\n```\n\n========================================\n\nTop Answer:\n@Anson C\n\n```\nconst requireComponent = require.context(\n // The relative path of the components folder\n './global',\n // Whether or not to look in subfolders\n true,\n // The regular expression used to match base component filenames\n /[A-Z]\\w+\\.(vue|js)$/\n)\n```\n\nThis code is exactly working as meant to be. Means it will return you back all files in subfolders as expected (like for `./Base/BaseInput.vue` will return `BaseInput`). But to import those files, You have to add the corresponding path as well.\n\n```\n// Get PascalCase name of component\n const componentName = upperFirst(\n camelCase(\n // Strip the leading `./` and extension from the filename\n fileName.replace(/^\\.\\/(.*)\\.\\w+$/, '$1')\n )\n )\n```\n\nThis will only import `./BaseInput` which is not accurate path it shall be `./Base/BaseInput`.\n\nThere for:\n\n```\n// Get PascalCase name of component\n const componentName = Vue._.upperFirst(\n Vue._.camelCase(\n fileName\n .split('/')\n .pop()\n .replace(/\\.\\w+$/, '')\n )\n )\n```\n\nThis code returns perfect path to the file and folder.\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\nimport upperFirst from 'lodash/upperFirst'\nimport camelCase from 'lodash/camelCase'\n\nconst requireComponent = require.context(\n // The relative path of the components folder\n './global',\n // Whether or not to look in subfolders\n true,\n // The regular expression used to match base component filenames\n /[A-Z]\\w+\\.(vue|js)$/\n)\n\nconsole.log(requireComponent.keys())\n\nrequireComponent.keys().forEach(fileName => {\n // Get component config\n const componentConfig = requireComponent(fileName)\n\n // Get PascalCase name of component\n const componentName = upperFirst(\n camelCase(\n // Strip the leading `./` and extension from the filename\n fileName.replace(/^\\.\\/(.*)\\.\\w+$/, '$1')\n )\n )\n\n // Register component globally\n Vue.component(\n componentName,\n // Look for the component options on `.default`, which will\n // exist if the component was exported with `export default`,\n // otherwise fall back to module's root.\n componentConfig.default || componentConfig\n )\n})\n```\n\n```text\n./global\n```\n\n```text\ntrue\n```\n\n```text\nconst requireComponent = require.context(\n // The relative path of the components folder\n './global',\n // Whether or not to look in subfolders\n true,\n // The regular expression used to match base component filenames\n /[A-Z]\\w+\\.(vue|js)$/\n)\n\nrequireComponent.keys().forEach(fileName => {\n // Get component config\n const componentConfig = requireComponent(fileName)\n // Get PascalCase name of component\n const componentName = Vue._.upperFirst(\n Vue._.camelCase(\n fileName\n .split('/')\n .pop()\n .replace(/\\.\\w+$/, '')\n )\n )\n\n // Register component globally\n Vue.component(\n componentName,\n // Look for the component options on `.default`, which will\n // exist if the component was exported with `export default`,\n // otherwise fall back to module's root.\n componentConfig.default || componentConfig\n )\n})\n```\n\n```text\n<ProgressBar></ProgressBar>\n```\n\n```js\nconst requireComponent = require.context(\n // The relative path of the components folder\n './global',\n // Whether or not to look in subfolders\n true,\n // The regular expression used to match base component filenames\n /[A-Z]\\w+\\.(vue|js)$/\n)\n```\n\n```js\n// Get PascalCase name of component\n const componentName = upperFirst(\n camelCase(\n // Strip the leading `./` and extension from the filename\n fileName.replace(/^\\.\\/(.*)\\.\\w+$/, '$1')\n )\n )\n```\n\n```js\n// Get PascalCase name of component\n const componentName = Vue._.upperFirst(\n Vue._.camelCase(\n fileName\n .split('/')\n .pop()\n .replace(/\\.\\w+$/, '')\n )\n )\n```\n\n```text\n./Base/BaseInput.vue\n```\n\n```text\nBaseInput\n```\n\n```text\n./BaseInput\n```\n\n```text\n./Base/BaseInput\n```\n\n========================================\n\nComments:\n- Are the component files in the subdirectories named correctly? They should start with an uppercase letter.\n- Thanks! How come the one provided in the documentation doesn't work? It should work by default when I change the \"look in the subfolder\" variable to true, no?\n- I'm also confused as to why the provided docs didn't work. This seems like it should be built into the subfolder traversal logic...\n- I will submit a commit to the VueJS docs repo for consideration.","metadata":{"transformedAt":"2026-08-18T18:33:07.884Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":242,"estimatedTokens":1522}}652{"id":"stack-55993170","source":"stackoverflow","questionId":55993170,"title":"Vue.js + Nuxt.js - Why is my computed property undefined when I unit test a head() method?","tags":["javascript","unit-testing","vue.js","nuxt.js"],"text":"Title: Vue.js + Nuxt.js - Why is my computed property undefined when I unit test a head() method?\nTags: javascript, unit-testing, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a Vue.js + Nuxt.js component with a `head()` method:\n\n```\n\n export default {\n name: 'my-page',\n head() {\n return { title: `${this.currentPage}` };\n },\n ...\n }\n\n```\n\n`currentPage` is a computed property.\n\nWhen I run my application, the component runs correctly and it sets the page title to the right value.\n\nWhen I run this code from a Jest + Vue Test Utils unit test, the code fails however:\n\n```\nit('should set the title to \"my page\"', () => {\n\n const options = {\n computed:{\n currentPage: () => {\n return 'My Title';\n }\n }\n };\n\n const target = shallowMount(MyPage, options);\n\n const actual = target.vm.$options.head();\n\n expect(actual.title).to.equal(\"My Title\");\n\n});\n```\n\nThe test fails with the message:\n\n AssertionError: expected undefined to equal 'My Title'\n\nWhy is the computed property undefined even though I mock it? \n\nDoes the fact that I invoke the `head()` method through `target.vm.$options` have anything to do with it?\n\n========================================\n\nCode:\n```text\n<script>\n export default {\n name: 'my-page',\n head() {\n return { title: `${this.currentPage}` };\n },\n ...\n }\n</script>\n```\n\n```text\nit('should set the title to \"my page\"', () => {\n\n const options = {\n computed:{\n currentPage: () => {\n return 'My Title';\n }\n }\n };\n\n const target = shallowMount(MyPage, options);\n\n const actual = target.vm.$options.head();\n\n expect(actual.title).to.equal(\"My Title\");\n\n});\n```\n\n```text\nhead()\n```\n\n```text\ncurrentPage\n```\n\n```text\nhead()\n```\n\n```text\ntarget.vm.$options\n```\n\n```text\nconst actual = target.vm.$options.head.call(target.vm);\n```\n\n========================================\n\nComments:\n- This was doing my head in... Many thanks for this solution.","metadata":{"transformedAt":"2026-08-18T18:33:07.884Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":112,"estimatedTokens":496}}653{"id":"stack-67609324","source":"stackoverflow","questionId":67609324,"title":"Remove leaflet attribution with Vue / Nuxt?","tags":["vue.js","leaflet","nuxt.js","vue2leaflet"],"text":"Title: Remove leaflet attribution with Vue / Nuxt?\nTags: vue.js, leaflet, nuxt.js, vue2leaflet\nSource: Stack Overflow\n\nQuestion:\nI've seen some threads on how to remove the leaflet attribution in the bottom right.\nIt seems like the creators of leaflet have no issue with it, so to save space I'd like to remove mine.\nHere is a thread on it, but no answers relate to Vue unfortunately.\nhttps://gis.stackexchange.com/questions/192088/how-to-remove-attribution-in-leaflet\n\nI'm using nuxt but would greatly appreciate help if it's directed toward Vue.\nThe l-tile-layer has an attribute-prop which indeed helps me add attributions, but removing it made me realize the attribution seem to be connected to the l-map component as it's visible with no tile layer.\n\nTLDR: I want to remove the \"Leaflet\" \n\nhttps://i.sstatic.net/sdFou.png\n\nSuggestions?\n\n========================================\n\nTop Answer:\nWith the Leaflet API, it is removed by this config.\n\nhttps://leafletjs.com/reference-1.7.1.html#map-attributioncontrol\n\n```\nL.map('map', {\n attributionControl: false\n}\n```\n\nWith vue2-leaflet it seems it is possible to do the same with the options prop\n\nhttps://vue2-leaflet.netlify.app/components/LMap.html#props\n\n```\n\n ...\n\n```\n\n========================================\n\nCode:\n```text\n<l-map :zoom=\"8\" :center=\"[59.3293, 18.0686]\" :options=\"{ attributionControl: false }\">\n<l-tile-layer url=\"http://localhost:8080/styles/mytheme/{z}/{x}/{y}.webp\" :attribution=attribution>\n</l-tile-layer>\n<l-control-attribution position=\"bottomright\" prefix=\"\"></l-control-attribution>\n</l-map>\n```\n\n```text\ndata(){\n return{\n attribution: \n '©<a href=\"https://openmaptiles.org/\">OpenMapTiles</a> ©<a href=\"http://osm.org/copyright\">OpenStreetMap</a> contributors'\n }\n }\n```\n\n```text\nL.map('map', {\n attributionControl: false\n}\n```\n\n```html\n<l-map\n :options=\"{attributionControl: false}\"\n>\n ...\n</l-map>\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.884Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":75,"estimatedTokens":482}}654{"id":"stack-64162508","source":"stackoverflow","questionId":64162508,"title":"how to dynamically resize text in a vue component","tags":["javascript","html","css","vue.js","nuxt.js"],"text":"Title: how to dynamically resize text in a vue component\nTags: javascript, html, css, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have built an application with different widgets you can drop into a dashboard. Each widget contains a component that a user would like to see (kind of like grafana if you've ever seen it).\n\nQuestion: When the user drags the grid-item to increase or decrease the size, how do you update the html inside of my component to adjust to the size of the new item?\n\nWhat I've tried:\n\n- attempted to wrap the p tags in an SVG and use viewport.\n\n- attempted to change my size to VW to dynamically scale by the viewport but the viewport is not of the component but of the entire spa.\n\n- I attempted to get the parent size using this.$parent and did some math to get the text size and dynamically assign it to a component but this was very messy. Also, the sizes displayed were not right.\n\nBelow is my code for my grid using the vue-grid-layout package\n\n```\n\n \n \n \n \n \n\n```\n\nMy component that I'm trying to resize the text for is below. It's a vue file and I've included styling.\n\n```\n\n \n \n {{ date }}\n\n {{ time }}\n\n \n \n\nexport default {\n data() {\n return {\n time: '',\n date: '',\n week: ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'],\n ticker: null\n };\n },\n created() {\n this.ticker = setInterval(this.updateTime, 1000);\n },\n mounted() {\n this.showDate =\n this.widgetConfig?.Settings?.find((x) => x.Key === 'ShowDate').Value ||\n false;\n this.showTime =\n this.widgetConfig?.Settings?.find((x) => x.Key === 'ShowTime').Value ||\n false;\n },\n methods: {\n updateTime() {\n let cd = new Date();\n this.time =\n this.zeroPadding(cd.getHours(), 2) +\n ':' +\n this.zeroPadding(cd.getMinutes(), 2) +\n ':' +\n this.zeroPadding(cd.getSeconds(), 2);\n\n this.date =\n this.zeroPadding(cd.getFullYear(), 4) +\n '-' +\n this.zeroPadding(cd.getMonth() + 1, 2) +\n '-' +\n this.zeroPadding(cd.getDate(), 2) +\n ' ' +\n this.week[cd.getDay()];\n },\n zeroPadding(num, digit) {\n let zero = '';\n for (let i = 0; i \n\nhtml,\nbody {\n height: 100%;\n}\nbody {\n background: #0f3854!important;\n background: radial-gradient(ellipse at center, #0a2e38 0%, #000000 70%)!important;\n background-size: 100%;\n}\np {\n margin: 0;\n padding: 0;\n}\n#clock {\n font-family: ' Tech Mono', monospace;\n color: #ffffff;\n text-align: center;\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%);\n color: #daf6ff;\n text-shadow: 0 0 20px rgba(10, 175, 230, 1), 0 0 20px rgba(10, 175, 230, 0);\n .time {\n letter-spacing: 0.05em;\n font-size: 1vw;\n padding: 5px 0;\n }\n .date {\n letter-spacing: 0.1em;\n font-size: 1vw;\n }\n .text {\n letter-spacing: 0.1em;\n font-size: 1vw;\n padding: 20px 0 0;\n }\n}\n\n```\n\nNuxt Config\n\n```\nmodule.exports = {\n head: {\n titleTemplate: '',\n title: 'QVue',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: 'QVue Web UI' },\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],\n },\n css: [],\n plugins: [\n { src: '@/plugins/vueGrid', ssr: false }\n ],\n publicRuntimeConfig: {},\n privateRuntimeConfig: {},\n components: true,\n buildModules: [\n '@nuxtjs/vuetify'\n ],\n modules: [\n '@nuxtjs/axios'\n ],\n axios: {\n },\n build: {\n },\n render: {\n compressor: false,\n },\n srcDir: 'client/',\n};\n```\n\n========================================\n\nCode:\n```text\n<grid-layout\n ref=\"widgetGrid\"\n :layout.sync=\"widgets\"\n :col-num=\"12\"\n :row-height=\"verticalSize\"\n :is-draggable=\"editable\"\n :is-resizable=\"editable\"\n :is-mirrored=\"false\"\n :responsive=\"true\"\n :autoSize=\"editable\"\n :prevent-collision=\"false\"\n :vertical-compact=\"false\"\n :margin=\"[10, 10]\"\n :use-css-transforms=\"true\"\n @layout-updated=\"layoutUpdatedEvent\"\n>\n <grid-item\n :ref=\"`widget_${widget.i}`\"\n v-for=\"widget in widgets\"\n :key=\"widget.i\"\n :x=\"widget.x\"\n :y=\"widget.y\"\n :w=\"widget.w\"\n :h=\"widget.h\"\n :i=\"widget.i\"\n :static=\"!editable\"\n >\n <template>\n <component\n :is=\"widget.WidgetType\"\n :setup=\"false\"\n :widgetConfig=\"widget.WidgetConfig\"\n ></component>\n </template>\n </grid-item>\n</grid-layout>\n```\n\n```text\n<template>\n <div>\n <div id=\"clock\">\n <p class=\"date\">{{ date }}</p>\n <p class=\"time\">{{ time }}</p>\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n time: '',\n date: '',\n week: ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'],\n ticker: null\n };\n },\n created() {\n this.ticker = setInterval(this.updateTime, 1000);\n },\n mounted() {\n this.showDate =\n this.widgetConfig?.Settings?.find((x) => x.Key === 'ShowDate').Value ||\n false;\n this.showTime =\n this.widgetConfig?.Settings?.find((x) => x.Key === 'ShowTime').Value ||\n false;\n },\n methods: {\n updateTime() {\n let cd = new Date();\n this.time =\n this.zeroPadding(cd.getHours(), 2) +\n ':' +\n this.zeroPadding(cd.getMinutes(), 2) +\n ':' +\n this.zeroPadding(cd.getSeconds(), 2);\n\n this.date =\n this.zeroPadding(cd.getFullYear(), 4) +\n '-' +\n this.zeroPadding(cd.getMonth() + 1, 2) +\n '-' +\n this.zeroPadding(cd.getDate(), 2) +\n ' ' +\n this.week[cd.getDay()];\n },\n zeroPadding(num, digit) {\n let zero = '';\n for (let i = 0; i < digit; i++) {\n zero += '0';\n }\n return (zero + num).slice(-digit);\n }\n },\n};\n</script>\n\n<style lang=\"scss\" scoped>\nhtml,\nbody {\n height: 100%;\n}\nbody {\n background: #0f3854!important;\n background: radial-gradient(ellipse at center, #0a2e38 0%, #000000 70%)!important;\n background-size: 100%;\n}\np {\n margin: 0;\n padding: 0;\n}\n#clock {\n font-family: 'Share Tech Mono', monospace;\n color: #ffffff;\n text-align: center;\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%);\n color: #daf6ff;\n text-shadow: 0 0 20px rgba(10, 175, 230, 1), 0 0 20px rgba(10, 175, 230, 0);\n .time {\n letter-spacing: 0.05em;\n font-size: 1vw;\n padding: 5px 0;\n }\n .date {\n letter-spacing: 0.1em;\n font-size: 1vw;\n }\n .text {\n letter-spacing: 0.1em;\n font-size: 1vw;\n padding: 20px 0 0;\n }\n}\n</style>\n```\n\n```text\nmodule.exports = {\n head: {\n titleTemplate: '',\n title: 'QVue',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: 'QVue Web UI' },\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],\n },\n css: [],\n plugins: [\n { src: '@/plugins/vueGrid', ssr: false }\n ],\n publicRuntimeConfig: {},\n privateRuntimeConfig: {},\n components: true,\n buildModules: [\n '@nuxtjs/vuetify'\n ],\n modules: [\n '@nuxtjs/axios'\n ],\n axios: {\n },\n build: {\n },\n render: {\n compressor: false,\n },\n srcDir: 'client/',\n};\n```\n\n```js\nVue.component('v-clock',{\n template:`\n <svg viewBox=\"0 0 100 100\" xmlns=\"http://www.w3.org/2000/svg\">\n <text x=\"0\" y=\"25\" fill=\"red\">{{date}}</text>\n <text x=\"0\" y=\"75\" fill=\"red\">{{time}}</text>\n </svg>\n `,\n data() {\n return {\n time: '',\n date: '',\n week: ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'],\n ticker: null\n };\n },\n created() {\n this.ticker = setInterval(this.updateTime, 1000);\n },\n mounted() {\n this.showDate =\n this.widgetConfig?.Settings?.find((x) => x.Key === 'ShowDate').Value ||\n false;\n this.showTime =\n this.widgetConfig?.Settings?.find((x) => x.Key === 'ShowTime').Value ||\n false;\n },\n methods: {\n updateTime() {\n let cd = new Date();\n this.time =\n this.zeroPadding(cd.getHours(), 2) +\n ':' +\n this.zeroPadding(cd.getMinutes(), 2) +\n ':' +\n this.zeroPadding(cd.getSeconds(), 2);\n\n this.date =\n this.zeroPadding(cd.getFullYear(), 4) +\n '-' +\n this.zeroPadding(cd.getMonth() + 1, 2) +\n '-' +\n this.zeroPadding(cd.getDate(), 2) +\n ' ' +\n this.week[cd.getDay()];\n },\n zeroPadding(num, digit) {\n let zero = '';\n for (let i = 0; i < digit; i++) {\n zero += '0';\n }\n return (zero + num).slice(-digit);\n }\n }\n})\n\nnew Vue ({\n el:'#app',\n data () {\n return {\n size: 100\n }\n }\n})\n```\n\n```html\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js\"></script>\n<div id=\"app\">\n <input v-model.number=\"size\" type=\"range\" min=\"50\" max=\"500\"/>\n <div :style=\"{width: size + 'px', height: size + 'px'}\" style=\"border: solid 1px blue\">\n <v-clock></v-clock>\n </div>\n</div>\n```\n\n```text\nclock\n```\n\n```text\nsvg -> viewbox\n```\n\n```text\n<text>\n```\n\n```text\n<p>\n```\n\n========================================\n\nComments:\n- Don't forget to `clearTimeout` in `destroyed`...\n- @MichalLevý Thanks for the recommendation!\n- Is there anything i need to do outside of what your showing to make an svg element work in nuxt specifically. What your suggestion was one of the first things i tried. When i use vue dev tools to inspect it i see all of the data is set correctly and the component appears but none of the html elements are rendering when i use svg. I literally copied your component html contents and removed everything else that would be in that component.\n- could you add your `nuxt.config.js` into the question? and any error in your terminal or browser console?\n- There are no errors in the console. Nuxt config has been added.\n- I couldn't reproduce the problem you met (check this code sandbox).\n- I was able to implement the vue-grid package and get this working with a combination of our examples but have run into other issues that i'll work on. I think you've provided the right answer just for some reason its not working on my local nuxt server and thats something I have to figure out. Thank's so much for the help today!","metadata":{"transformedAt":"2026-08-18T18:33:07.884Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":447,"estimatedTokens":2484}}655{"id":"stack-59277092","source":"stackoverflow","questionId":59277092,"title":"How to use mapGetters with Vuex Modules","tags":["vue.js","vuex","nuxt.js","vuex-modules"],"text":"Title: How to use mapGetters with Vuex Modules\nTags: vue.js, vuex, nuxt.js, vuex-modules\nSource: Stack Overflow\n\nQuestion:\ni have added modules in `store/index.js`\n\n```\nimport NavMessage from './nav/message/index';\nnew Vuex.Store({\n modules: {\n NavMessage,\n },\n});\n```\n\nmy message/index.js\n\n```\nimport state from './state';\nimport getters from './getters';\nimport mutations from './mutations';\n\nexport default {\n state,\n getters,\n mutations,\n};\n```\n\nhere is getters\n\n```\nconst getters = () => ({\n getCount: state => {\n return state.count;\n },\n});\n\nexport default getters;\n```\n\ni am trying to get data from `NavMessage/getCount` \n\n```\n...mapGetters({\n count: 'NavMessage/getCount',\n }),\n```\n\nbut i am getting error `unknown getter: NavMessage/getCount`\n\nhelp me thank\n\n========================================\n\nCode:\n```text\nimport NavMessage from './nav/message/index';\nnew Vuex.Store({\n modules: {\n NavMessage,\n },\n});\n```\n\n```text\nimport state from './state';\nimport getters from './getters';\nimport mutations from './mutations';\n\nexport default {\n state,\n getters,\n mutations,\n};\n```\n\n```text\nconst getters = () => ({\n getCount: state => {\n return state.count;\n },\n});\n\nexport default getters;\n```\n\n```text\n...mapGetters({\n count: 'NavMessage/getCount',\n }),\n```\n\n```text\nstore/index.js\n```\n\n```text\nNavMessage/getCount\n```\n\n```text\nunknown getter: NavMessage/getCount\n```\n\n```js\nconst mapGetters = Vuex.mapGetters\n\nconst state = {\n count: 6\n}\n\nconst getters = {\n getCount: state => {\n return state.count\n }\n}\n\nconst mutations = {}\n\nconst NavMessage = {\n namespaced: true,\n state,\n getters,\n mutations\n}\n\nconst store = new Vuex.Store({\n modules: {\n NavMessage\n }\n})\n\nconst app = new Vue({\n store,\n\n computed: {\n ...mapGetters({\n count: 'NavMessage/getCount',\n })\n }\n})\n\nconsole.log(app.count)\n```\n\n```html\n<script src=\"https://unpkg.com/vue@2.6.10/dist/vue.js\"></script>\n<script src=\"https://unpkg.com/vuex@3.1.2/dist/vuex.js\"></script>\n```\n\n```text\nnamespaced: true\n```\n\n```text\ngetters\n```\n\n```text\nmapGetters\n```\n\n```text\ncount: 'getCount'\n```\n\n```text\nNavMessage/\n```\n\n```text\ngetters\n```\n\n```text\nnamespaced: true\n```\n\n```text\nnew Vuex.Store\n```\n\n========================================\n\nComments:\n- Do you want to use namespacing? vuex.vuejs.org/guide/modules.html#namespacing You'll need to add `namespaced: true` to the module if you do. I also suggest checking the case of `getCount` as the first letter seems to be in upper-case in the error message.\n- @skirtle thanks for the reply but still getting same error\n- I still need to know whether you want to use namespacing. The correct fix depends on what you are trying to do.\n- thank you for your reply i did with your login in my app now i am getting getters check screenshot prnt.sc/q98ftq but still getting same error","metadata":{"transformedAt":"2026-08-18T18:33:07.884Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":191,"estimatedTokens":708}}656{"id":"stack-57967045","source":"stackoverflow","questionId":57967045,"title":"Cannot read property '$axios' of undefined nuxtjs vuex","tags":["vuex","nuxt.js"],"text":"Title: Cannot read property '$axios' of undefined nuxtjs vuex\nTags: vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI stumbled upon this bug in my codebase and trying to see if anyone can fix it. \n\nfollowing is my listings/actions.js\n\n```\nexport const fetchFeaturedListings = ({ commit }) => {\n this.$axios.get(\"/featured\").then(response => {\n console.log(response.data.data);\n commit(\"listings/setFeaturedListings\", response.data.data);\n });\n};\n```\n\nI am constantly getting the following error.\n\nCannot read property '$axios' of undefined\n\nI've searched everywhere, and still not able to find an answer. Hope someone can help.\n\n========================================\n\nTop Answer:\nYou're using an arrow function, which means `this` comes from the outer scope. If `$axios` doesn't exist in that outer scope, this is why you see this error.\n\n========================================\n\nCode:\n```text\nexport const fetchFeaturedListings = ({ commit }) => {\n this.$axios.get(\"/featured\").then(response => {\n console.log(response.data.data);\n commit(\"listings/setFeaturedListings\", response.data.data);\n });\n};\n```\n\n```text\nexport const fetchFeaturedListings = function({ commit }){\n this.$axios.get(\"/featured\").then(response => {\n console.log(response.data.data);\n commit(\"listings/setFeaturedListings\", response.data.data);\n });\n};\n```\n\n```text\nthis\n```\n\n```text\n$axios\n```\n\n```text\nthis\n```\n\n```text\naxios\n```\n\n========================================\n\nComments:\n- Need more details like what is your environment? Webpack? Node?\n- Yes, to be clear, every time you use an arrow function you override the `this` context.","metadata":{"transformedAt":"2026-08-18T18:33:07.884Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":71,"estimatedTokens":408}}657{"id":"stack-62437862","source":"stackoverflow","questionId":62437862,"title":"Vuelidate requiredUnless - Only one input is required to be filled in","tags":["vue.js","nuxt.js","bootstrap-vue","vuelidate"],"text":"Title: Vuelidate requiredUnless - Only one input is required to be filled in\nTags: vue.js, nuxt.js, bootstrap-vue, vuelidate\nSource: Stack Overflow\n\nQuestion:\nI have three inputs `jobApplyEmail`, `jobApplyPhone`, `jobApplyOther` which I am validating with Vuelidate. Of these three inputs, users are required to enter at least one input. To achieve this I am using `requiredUnless` however it's not working for some reason.\n\n**Template repeated**\n\n```\n// Using bootstrap-vue\n \n \n```\n\n**Script**\n\n```\nimport {\n required,\n email,\n requiredUnless\n } from 'vuelidate/lib/validators'\n data() {\n return {\n form: {\n jobApplyEmail: '',\n jobApplyPhone: '',\n jobApplyOther: ''\n },\n }\n },\n computed: {\n isOptional: () => {\n return (\n this.jobApplyEmail !== '' ||\n this.jobApplyOther !== '' ||\n this.jobApplyPhone !== ''\n )\n }\n },\n \n validations: {\n form: {\n jobApplyEmail: { required: requiredUnless('isOptional'), email },\n jobApplyOther: { required: requiredUnless('isOptional') },\n jobApplyPhone: { required: requiredUnless('isOptional') }\n }\n },\n```\n\n========================================\n\nCode:\n```html\n// Using bootstrap-vue\n <b-form-input\n id=\"jobApplyEmail\"\n v-model=\"form.jobApplyEmail\"\n type=\"email\"\n :class=\"{ 'is-invalid': $v.form.jobApplyEmail.$error }\"\n @blur=\"$v.form.jobApplyEmail.$touch()\">\n </b-form-input>\n```\n\n```js\nimport {\n required,\n email,\n requiredUnless\n } from 'vuelidate/lib/validators'\n data() {\n return {\n form: {\n jobApplyEmail: '',\n jobApplyPhone: '',\n jobApplyOther: ''\n },\n }\n },\n computed: {\n isOptional: () => {\n return (\n this.jobApplyEmail !== '' ||\n this.jobApplyOther !== '' ||\n this.jobApplyPhone !== ''\n )\n }\n },\n \n validations: {\n form: {\n jobApplyEmail: { required: requiredUnless('isOptional'), email },\n jobApplyOther: { required: requiredUnless('isOptional') },\n jobApplyPhone: { required: requiredUnless('isOptional') }\n }\n },\n```\n\n```text\njobApplyEmail\n```\n\n```text\njobApplyPhone\n```\n\n```text\njobApplyOther\n```\n\n```text\nrequiredUnless\n```\n\n```text\njobApplyEmail: {\n requiredIf: requiredUnless(function() {\n return (\n this.form.jobApplyPhone !== '' || this.form.jobApplyOther !== ''\n )\n }),\n email\n },\n\n jobApplyPhone: {\n requiredIf: requiredUnless(function() {\n return (\n this.form.jobApplyOther !== '' || this.form.jobApplyEmail !== ''\n )\n })\n },\n jobApplyOther: {\n requiredIf: requiredUnless(function() {\n return (\n this.form.jobApplyPhone !== '' || this.form.jobApplyEmail !== ''\n )\n })\n }\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.884Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":140,"estimatedTokens":701}}658{"id":"stack-45691469","source":"stackoverflow","questionId":45691469,"title":"How do i add client side js libraries in Nuxt>","tags":["nuxt.js","baqend"],"text":"Title: How do i add client side js libraries in Nuxt>\nTags: nuxt.js, baqend\nSource: Stack Overflow\n\nQuestion:\nFirst time on nuxt. i am trying to add a client side library. \n\nIn a normal html i will just add it to my index.html file. But i have no idea how do i do the same on nuxt.\n\nHow do i add it?\n\nthis is my config\n\n```\nmodule.exports = {\n\n /*\n ** Headers of the page\n */\n head: {\n title: 'digglu',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: 'social media site' },\n { name: 'google-signin-client_id', content:'xxx.apps.googleusercontent.com' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n /*\n ** Customize the progress-bar color\n */\n loading: { color: '#3B8070' },\n /*\n ** Build configuration\n */\n build: {\n /*\n ** Run ESLINT on save\n */\n extend (config, ctx) {\n if (ctx.dev && ctx.isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nAccording to the Nuxt documentation you can use a naming convention or object syntax for that in your `nuxt.config.js`.\n\n### Naming Convention\n\n```\nexport default {\n plugins: [\n '~/plugins/foo.client.js', // only in client side\n '~/plugins/bar.server.js', // only in server side\n '~/plugins/baz.js' // both client & server\n ]\n}\n```\n\n### Object Syntax\n\n```\nexport default {\n plugins: [\n { src: '~/plugins/both-sides.js' },\n { src: '~/plugins/client-only.js', mode: 'client' }, // only on client side\n { src: '~/plugins/server-only.js', mode: 'server' } // only on server side\n ]\n}\n```\n\nSee here: https://nuxtjs.org/guides/directory-structure/plugins#client-or-server-side-only\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n\n /*\n ** Headers of the page\n */\n head: {\n title: 'digglu',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: 'social media site' },\n { name: 'google-signin-client_id', content:'xxx.apps.googleusercontent.com' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n /*\n ** Customize the progress-bar color\n */\n loading: { color: '#3B8070' },\n /*\n ** Build configuration\n */\n build: {\n /*\n ** Run ESLINT on save\n */\n extend (config, ctx) {\n if (ctx.dev && ctx.isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n }\n }\n}\n```\n\n```text\nmodule.exports = {\n plugins: [\n { src: '~/plugins/vue-notifications', ssr: false }\n ]\n}\n```\n\n```text\nimport Vue from 'vue'\nimport VueNotifications from 'vue-notifications'\n\nVue.use(VueNotifications)\n```\n\n```js\nexport default {\n plugins: [\n '~/plugins/foo.client.js', // only in client side\n '~/plugins/bar.server.js', // only in server side\n '~/plugins/baz.js' // both client & server\n ]\n}\n```\n\n```js\nexport default {\n plugins: [\n { src: '~/plugins/both-sides.js' },\n { src: '~/plugins/client-only.js', mode: 'client' }, // only on client side\n { src: '~/plugins/server-only.js', mode: 'server' } // only on server side\n ]\n}\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- how to do it if you are not importing Vue packages? Example paho-mqtt package which works only in browser","metadata":{"transformedAt":"2026-08-18T18:33:07.884Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":176,"estimatedTokens":905}}659{"id":"stack-76199192","source":"stackoverflow","questionId":76199192,"title":"Nuxt 3 composables suddenly undefined","tags":["nuxt.js","vuejs3","nuxt3.js"],"text":"Title: Nuxt 3 composables suddenly undefined\nTags: nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI set up a composable for the currentYear under composables/getCurrentYear.ts\n\n```\nexport const getCurrentYear = () => {\n return new Date().getFullYear();\n }\n```\n\nin my Footer component I defined it as\n\n```\n\nconst currentYear = getCurrentYear()\n\n```\n\nand even though it was importing perfectly fine before, I am not getting:\n\n```\n500\ngetCurrentYear is not defined\n\nat _sfc_main.setup (./components/AppFooter.js:56:23)\nat callWithErrorHandling (./node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:171:22)\nat setupStatefulComponent (./node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7194:29)\nat setupComponent (./node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7149:11)\nat renderComponentVNode (./node_modules/@vue/server-renderer/dist/server-renderer.cjs.js:628:17)\nat Module.ssrRenderComponent (./node_modules/@vue/server-renderer/dist/server-renderer.cjs.js:94:12)\nat _sfc_ssrRender (./components/AppLayout.js:26:31)\nat renderComponentSubTree (./node_modules/@vue/server-renderer/dist/server-renderer.cjs.js:710:17)\nat renderComponentVNode (./node_modules/@vue/server-renderer/dist/server-renderer.cjs.js:644:16)\n```\n\nMy dependencies did not change, so I am slightly lost on why this all of the sudden stopped working:\n\n```\n\"devDependencies\": {\n \"@nuxtjs/i18n\": \"^8.0.0-beta.11\",\n \"autoprefixer\": \"^10.4.13\",\n \"nuxt\": \"^3.4.3\",\n \"nuxt-simple-sitemap\": \"^2.4.23\",\n \"postcss\": \"^8.4.23\",\n \"tailwindcss\": \"^3.3.2\"\n },\n \"dependencies\": {\n \"@csstools/css-parser-algorithms\": \"^2.1.1\",\n \"@nuxtjs/google-fonts\": \"^3.0.0\",\n \"contentful\": \"^10.1.8\",\n \"contentful-rich-text-vue-renderer\": \"^3.1.0\",\n \"gsap\": \"file:gsap-bonus.tgz\",\n \"nuxt-swiper\": \"^1.1.0\",\n \"typescript\": \"^5.0.4\"\n }\n```\n\n========================================\n\nTop Answer:\nFrom Nuxt3 official doc\n\nNuxt 3 uses the `composables/` directory to automatically import your Vue composables into your application using auto-imports!\n\nSo instead of naming `composabled/getCurrentYear.ts` you can try `composables/getCurrentYear.ts`\n\n========================================\n\nCode:\n```text\nexport const getCurrentYear = () => {\n return new Date().getFullYear();\n }\n```\n\n```text\n<script setup>\nconst currentYear = getCurrentYear()\n</script>\n```\n\n```text\n500\ngetCurrentYear is not defined\n\nat _sfc_main.setup (./components/AppFooter.js:56:23)\nat callWithErrorHandling (./node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:171:22)\nat setupStatefulComponent (./node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7194:29)\nat setupComponent (./node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7149:11)\nat renderComponentVNode (./node_modules/@vue/server-renderer/dist/server-renderer.cjs.js:628:17)\nat Module.ssrRenderComponent (./node_modules/@vue/server-renderer/dist/server-renderer.cjs.js:94:12)\nat _sfc_ssrRender (./components/AppLayout.js:26:31)\nat renderComponentSubTree (./node_modules/@vue/server-renderer/dist/server-renderer.cjs.js:710:17)\nat renderComponentVNode (./node_modules/@vue/server-renderer/dist/server-renderer.cjs.js:644:16)\n```\n\n```text\n\"devDependencies\": {\n \"@nuxtjs/i18n\": \"^8.0.0-beta.11\",\n \"autoprefixer\": \"^10.4.13\",\n \"nuxt\": \"^3.4.3\",\n \"nuxt-simple-sitemap\": \"^2.4.23\",\n \"postcss\": \"^8.4.23\",\n \"tailwindcss\": \"^3.3.2\"\n },\n \"dependencies\": {\n \"@csstools/css-parser-algorithms\": \"^2.1.1\",\n \"@nuxtjs/google-fonts\": \"^3.0.0\",\n \"contentful\": \"^10.1.8\",\n \"contentful-rich-text-vue-renderer\": \"^3.1.0\",\n \"gsap\": \"file:gsap-bonus.tgz\",\n \"nuxt-swiper\": \"^1.1.0\",\n \"typescript\": \"^5.0.4\"\n }\n```\n\n```text\nuseBolts > getBolt(diameter: 4mm, length: 30mm)\n\nuseNuts > getNut(diameter: 4mm)\n```\n\n```text\nfixings = useFixings > { bolts = useBolts(), nuts = useNuts() }\n\nfixings.bolts.getBolt(diameter: 4mm, length: 30mm)\n```\n\n```js\n// composables/useDates.ts\n\nexport const useDates = () => { // The named container\n\n // A container method\n const getCurrentYear = () => new Date().getFullYear();\n\n\n return { getCurrentYear } // Expose as public interface\n\n}\n```\n\n```text\n// components/myComponenet.vue\n\n<script setup>\n const { getCurrentYear } = useDates();\n\n console.log(getCurrentYear())\n<script>\n```\n\n```text\nuseDate.d.ts\n```\n\n```text\n.nuxt\n```\n\n```text\n<compsoable-name>.d.ts\n```\n\n```text\n/.nuxt\n```\n\n```text\nreadonly\n```\n\n```text\nwritable\n```\n\n```text\n.nuxt\n```\n\n```text\ndev\n```\n\n```text\nnuxi prepare\n```\n\n```text\n.nuxt\n```\n\n```text\ncomposables/\n```\n\n```text\ncomposabled/getCurrentYear.ts\n```\n\n```text\ncomposables/getCurrentYear.ts\n```\n\n```js\n// composable/ui.js\n\nimport { useState } from '#app';\n\nconst useThemeMode = () => (useState('mode', () => 'dark'));\n\nconst states = {\n themeMode: useThemeMode,\n};\n\n// Execute state change\nexport function toggleDark(value) {\n const themeMode = useThemeMode();\n\n themeMode.value = value;\n}\n\nexport default states;\n```\n\n```html\n<template>\n <!-- components/UiSettings.vue -->\n <div :class=\"themeMode\">\n <button @click=\"switchTheme('light')\">change to light</button>\n <button @click=\"switchTheme('dark')\">change to dark</button>\n </div>\n</template>\n\n<script setup>\nimport ui, { toggleDark } from '@/composables/ui';\n\nconst themeMode = ui.themeMode();\nfunction switchTheme(val) {\n toggleDark(val);\n}\n</script>\n```\n\n========================================\n\nComments:\n- Sorry @nur_riyad, that was a typo, I have it in composables/getCurrentYear.ts\n- thanks so much for such a detailed answer! I tried to implement as you suggested but getting `useDates is not defined` with it. Could something be blocking the auto-import of composables?\n- Strange, try running `nuxi prepare` in your project, aslo make sure that directories are not for some reason `readonly` on your system.\n- How strange, it was indeed a file permission issue. When moving the project to another folder, the composable started coming through again! Thanks so much. That paired with the new composable set-up you suggested works like a charm! I think there is just one slight typo where it should be `const getCurrentYear = new Date().getFullYear();` Really appreciate your help! Thanks","metadata":{"transformedAt":"2026-08-18T18:33:07.884Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":254,"estimatedTokens":1542}}660{"id":"stack-63818416","source":"stackoverflow","questionId":63818416,"title":"Nuxt - Wait after async action (this.$store.dispatch)","tags":["vue.js","vuex","nuxt.js"],"text":"Title: Nuxt - Wait after async action (this.$store.dispatch)\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm new to Nuxt and I'm facing an issue that I don't understand.\n\nIf i code something like:\n\n```\nconst resp1 = await this.$axios.$post('urlCall1', {...dataCall1});\nthis.$axios.$post('urlCall2', {...dataCall2, resp1.id});\n```\n\nThe resp1.id is properly set in the 2nd axios call => we wait for the first call to be completed before doing the 2nd one.\n\nHowever, when I define asyn actions in my vuex store ex:\n\n```\nasync action1({ commit, dispatch }, data) {\n try {\n const respData1 = await this.$axios.$post('urlCall1', { ...data });\n commit('MY_MUTATION1', respData1);\n return respData1;\n } catch (e) {\n dispatch('reset');\n }\n },\n async action2({ commit, dispatch }, data, id) {\n try {\n const respData2 = await this.$axios.$post('urlCall2', { ...data });\n commit('MY_MUTATION2', respData2);\n } catch (e) {\n dispatch('reset');\n }\n }\n```\n\nand then in my vue component I fire those actions like:\n\n```\nconst resp1 = await this.$store.dispatch('store1/action1', data1);\nthis.$store.dispatch('store2/action2', data2, resp1.id);\n```\n\nresp1.id is undefined in action2.\n\nI also tried managing promise the \"old way\":\n\n```\nthis.$store.dispatch('store1/action1', data1).then(resp1 => this.$store.dispatch('store2/action2', data2, resp1.id))\n```\n\nThe result is still the same => id = undefined in action2\n\nCan you guys please tell me where I'm wrong ?\n\nThanks in advance.\n\nLast note: the 2 actions are in different stores\n\n========================================\n\nCode:\n```text\nconst resp1 = await this.$axios.$post('urlCall1', {...dataCall1});\nthis.$axios.$post('urlCall2', {...dataCall2, resp1.id});\n```\n\n```text\nasync action1({ commit, dispatch }, data) {\n try {\n const respData1 = await this.$axios.$post('urlCall1', { ...data });\n commit('MY_MUTATION1', respData1);\n return respData1;\n } catch (e) {\n dispatch('reset');\n }\n },\n async action2({ commit, dispatch }, data, id) {\n try {\n const respData2 = await this.$axios.$post('urlCall2', { ...data });\n commit('MY_MUTATION2', respData2);\n } catch (e) {\n dispatch('reset');\n }\n }\n```\n\n```text\nconst resp1 = await this.$store.dispatch('store1/action1', data1);\nthis.$store.dispatch('store2/action2', data2, resp1.id);\n```\n\n```text\nthis.$store.dispatch('store1/action1', data1).then(resp1 => this.$store.dispatch('store2/action2', data2, resp1.id))\n```\n\n```js\nthis.$store.dispatch('store2/action2', { ...data2, id: resp1.id });\n```\n\n```js\nasync action2({ commit, dispatch }, { id, ...data }) {\n try {\n const respData2 = await this.$axios.$post('urlCall2', { ...data });\n commit('MY_MUTATION2', respData2);\n } catch (e) {\n dispatch('reset');\n }\n}\n```\n\n========================================\n\nComments:\n- and does the request finish successfully? Maybe the catch() activates and no value is returned - that's why you see undefined","metadata":{"transformedAt":"2026-08-18T18:33:07.884Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":117,"estimatedTokens":743}}661{"id":"stack-72100538","source":"stackoverflow","questionId":72100538,"title":"Running an Express server middleware alongside Nuxt","tags":["javascript","node.js","vue.js","express","nuxt.js"],"text":"Title: Running an Express server middleware alongside Nuxt\nTags: javascript, node.js, vue.js, express, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nMy endpoints aren't working, and most likely because the server on which express is isn't running correctly. I run my files with `npm run dev` and my express files are in `/middleware`. The endpoint which I'm trying to fetch data from is in a route in `/middleware/routes/crash.js`. In my vue file I have axios preforming a get request to `localhost:3000/api/crash/:id`, however axios returns a 400 error indicating that the file hasn't been found running on the server.\n\npackage.json:\n\n```\n\"scripts\": {\n \"dev\": \"nuxt\"\n}\n```\n\n/middleware/index.js:\n\n```\nconst express = require('express')\nconst app = express()\n\nconst crash = require('./routes/crash')\napp.use(crash)\n\nmodule.exports = {\n path: '/middleware',\n handler: app\n}\n```\n\n/middleware/routes/crash.js:\n\n```\nconst { Router } = require('express')\nconst router = Router()\nconst crypto = require(\"crypto\");\n...\nrouter.get('/api/crash/:id')\n```\n\n========================================\n\nCode:\n```json\n\"scripts\": {\n \"dev\": \"nuxt\"\n}\n```\n\n```text\nconst express = require('express')\nconst app = express()\n\nconst crash = require('./routes/crash')\napp.use(crash)\n\nmodule.exports = {\n path: '/middleware',\n handler: app\n}\n```\n\n```text\nconst { Router } = require('express')\nconst router = Router()\nconst crypto = require(\"crypto\");\n...\nrouter.get('/api/crash/:id')\n```\n\n```text\nnpm run dev\n```\n\n```text\n/middleware\n```\n\n```text\n/middleware/routes/crash.js\n```\n\n```text\nlocalhost:3000/api/crash/:id\n```\n\n```js\nexport default {\n ssr: true,\n target: 'server',\n modules: [\n '@nuxtjs/axios',\n ],\n serverMiddleware: [\n { path: '/api', handler: '~/server-middleware/rest.js' },\n ],\n}\n```\n\n```js\nconst app = require('express')()\n\napp.get('/what-is-my-name/:name', (req, res) => {\n res.json({ name: req.params.name, age: 12 })\n})\n\nmodule.exports = app\n```\n\n```html\n<template>\n <div>\n <input id=\"name\" v-model=\"name\" type=\"text\" name=\"name\" />\n <button @click=\"callNuxtApi\">try local Nuxt API</button>\n <div>\n Response from the backend:\n <pre>{{ response }}</pre>\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n name: 'AccordionList',\n data() {\n return {\n name: 'bob',\n response: {},\n }\n },\n methods: {\n async callNuxtApi() {\n const response = await this.$axios.$get(\n `/api/what-is-my-name/${this.name}`\n )\n this.response = response\n },\n },\n}\n</script>\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n/server-middleware/rest.js\n```\n\n```text\n.vue\n```\n\n```text\nname\n```\n\n```text\nserver-middleware\n```\n\n========================================\n\nComments:\n- Is it a 400 error or a 404?\n- Do you have a minimal reproducible example or a github repo for this one?\n- Also, did you pay attention to `Do not add serverMiddleware to the middleware/ directory` in the documentation regarding the link I gave you on your latest question? nuxtjs.org/docs/configuration-glossary/…\n- Hi, did my answer helped somehow?\n- @kissu Somehow, yes. I'm still having issues with initializing express.js. Absolutely no clue what the cause of it is. I made a new post and a github repo regarding it.\n- This no longer works in latest Nuxt 3\n- @malix Nuxt3's approach is indeed quite different. Far more powerful and versatile.","metadata":{"transformedAt":"2026-08-18T18:33:07.884Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":172,"estimatedTokens":845}}662{"id":"stack-56014244","source":"stackoverflow","questionId":56014244,"title":"Nuxt and Ag Grid issue SyntaxError Missing stack frames","tags":["vue.js","ag-grid","nuxt.js"],"text":"Title: Nuxt and Ag Grid issue SyntaxError Missing stack frames\nTags: vue.js, ag-grid, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nTrying to add ag-grid in the nuxt app.\n\nI followed the steps from \nhttps://www.ag-grid.com/vue-getting-started/\nand \nHow to use ag-grid in a Nuxt app\n\n- Added the styles in nuxt.config.js\n\n- Made a plugin and included in nuxt.config.js\n\n- Created the component AgGridDemo.vue\n\n- Including component in page index.vue\n\n**Note: Please do not try to run the snippets since I only used them to the source I have.** \n\nMy nuxt.config.js file\n\n\r\n\r\n\n```\nrequire('dotenv').config()\r\nimport pkg from './package'\r\n\r\nexport default {\r\n mode: 'universal',\r\n\r\n /*\r\n ** Headers of the page\r\n */\r\n head: {\r\n title: pkg.name,\r\n meta: [\r\n { charset: 'utf-8' },\r\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\r\n { hid: 'description', name: 'description', content: pkg.description }\r\n ],\r\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]\r\n },\r\n\r\n /*\r\n ** Customize the progress-bar color\r\n */\r\n loading: { color: '#fff' },\r\n\r\n /*\r\n ** Global CSS\r\n */\r\n css: [\r\n { src: '~assets/bulma-modifications.scss', lang: 'scss' },\r\n { src: 'font-awesome/scss/font-awesome.scss', lang: 'scss' },\r\n { src: '~/node_modules/ag-grid-community/dist/styles/ag-grid.css', lang: 'css' },\r\n { src: '~/node_modules/ag-grid-community/dist/styles/ag-theme-dark.css', lang: 'css' }\r\n ],\r\n\r\n /*\r\n ** Plugins to load before mounting the App\r\n */\r\n plugins: [\r\n {\r\n src: '~/plugins/plugin-ag-grid.js',\r\n ssr: false\r\n },\r\n {\r\n src: '~plugins/plugin-vue-chartjs.js',\r\n ssr: false\r\n }\r\n ],\r\n\r\n /*\r\n ** Nuxt.js modules\r\n */\r\n modules: [\r\n // Doc: https://axios.nuxtjs.org/usage\r\n '@nuxtjs/axios',\r\n // Doc: https://buefy.github.io/#/documentation\r\n 'nuxt-buefy',\r\n '@nuxtjs/pwa',\r\n '@nuxtjs/dotenv'\r\n ],\r\n /*\r\n ** Axios module configuration\r\n */\r\n axios: {\r\n // See https://github.com/nuxt-community/axios-module#options\r\n },\r\n\r\n /*\r\n ** Build configuration\r\n */\r\n build: {\r\n /*\r\n ** You can extend webpack config here\r\n */\r\n extend(config, ctx) {\r\n config.resolve.alias['vue'] = 'vue/dist/vue.common'\r\n // Run ESLint on save\r\n if (ctx.isDev && ctx.isClient) {\r\n config.module.rules.push({\r\n enforce: 'pre',\r\n test: /\\.(js|vue)$/,\r\n loader: 'eslint-loader',\r\n exclude: /(node_modules)/\r\n })\r\n }\r\n config.node = {\r\n fs: 'empty'\r\n }\r\n }\r\n },\r\n env: {\r\n baseUrl: process.env.BASE_URL || 'http://localhost:3000'\r\n }\r\n}\n```\n\n\r\n\r\n\r\n\nMy Plugin plugin-ag-grid.js:\n\n\r\n\r\n\n```\nimport * as agGridEnterpise from 'ag-grid-enterprise/main'\r\nrequire('dotenv').config()\r\nagGridEnterpise.LicenseManager.setLicenseKey([process.env.AG_LICENSE_KEY])\n```\n\n\r\n\r\n\r\n\nMy Component AgGridDemo.vue:\n\n\r\n\r\n\n```\n\r\n \r\n\r\n\r\nimport { AgGridVue } from 'ag-grid-vue'\r\n\r\nexport default {\r\n name: 'AgGridDemo',\r\n data() {\r\n return {\r\n columnDefs: null,\r\n rowData: null\r\n }\r\n },\r\n components: {\r\n AgGridVue\r\n },\r\n beforeMount() {\r\n this.columnDefs = [\r\n { headerName: 'Make', field: 'make' },\r\n { headerName: 'Model', field: 'model' },\r\n { headerName: 'Price', field: 'price' }\r\n ]\r\n\r\n this.rowData = [\r\n { make: 'Toyota', model: 'Celica', price: 35000 },\r\n { make: 'Ford', model: 'Mondeo', price: 32000 },\r\n { make: 'Porsche', model: 'Boxter', price: 72000 }\r\n ]\r\n }\r\n}\r\n\n```\n\n\r\n\r\n\r\n\nFinally My Page:\n\n\r\n\r\n\n```\n\r\n \r\n Welcome to test page\r\n \r\n \r\n\r\n\r\n\r\nimport AgGridDemo from '~/components/AgGridDemo'\r\nexport default {\r\n name: 'IndexPage',\r\n components: {\r\n AgGridDemo\r\n }\r\n}\r\n\n```\n\n\r\n\r\n\r\n\nI am getting Error on the Screen but not on my console, console says Compiled successfully but on screen I get:\n\nSyntaxError Missing \n\nstack frames\n\nhttps://i.sstatic.net/CVf6L.png\n\nAny Ideas on why is this happening and how to fix this ?\n\n========================================\n\nTop Answer:\nFirstly, although would likely not cause this error, the component in your template should be kebab case. ``. From vue docs\n\nThe error you are getting is probably an ssr issue, and although you have specified `ssr: false` in your nuxt.config.js this doesn't always get the point across.\n\nCould you try this:\n\n```\n\n \n Welcome to test page\n \n \n \n \n\n \n\nlet AgGridDemo = {}\nif (process.browser) {\n AgGridDemo = require('~/components/AgGridDemo')\n}\nexport default {\n components: {\n 'ag-grid-demo': AgGridDemo\n }\n}\n\n```\n\nAlso, as an aside, the modern way to import plugins in nuxt.config.js is as follows.\n\n```\nplugins: [\n '~/plugins/plugin-ag-grid.client.js'\n //Note the .client.js This is shorthand for the following which you can also use\n src: { '~/plugins/plugin-ag-grid.js', mode: client }\n]\n```\n\nThe use of `ssr: false` will be deprecated in the next major release. See docs\n\n**Edit**\n\nIf this is still causing errors you may need to add the plugin to `build-transpile` in nuxt.config.js. Like so:\n\n```\nbuild: {\n ...\n transpile: [\n '/plugins',\n ],\n}\n```\n\nThis will transpile all your plugins but see how you go. Unfortunately the docs don't give us a lot about this.\n\nIf you can't get that to work the old fashioned approach was to add the component to a whitelist like this:\n\n```\n//nuxt.config.js\nconst nodeExternals = require('webpack-node-externals')\n\nmodule.exports = {\n /**\n * All other config code\n */\n build: {\n extend(config, ctx) {\n if (ctx.isServer) {\n config.externals = [\n nodeExternals({\n whitelist: [/^@components\\\\AgGridDemo.vue/] \n // or however you regex a windows path\n })\n ]\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```js\nrequire('dotenv').config()\nimport pkg from './package'\n\nexport default {\n mode: 'universal',\n\n /*\n ** Headers of the page\n */\n head: {\n title: pkg.name,\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: pkg.description }\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]\n },\n\n /*\n ** Customize the progress-bar color\n */\n loading: { color: '#fff' },\n\n /*\n ** Global CSS\n */\n css: [\n { src: '~assets/bulma-modifications.scss', lang: 'scss' },\n { src: 'font-awesome/scss/font-awesome.scss', lang: 'scss' },\n { src: '~/node_modules/ag-grid-community/dist/styles/ag-grid.css', lang: 'css' },\n { src: '~/node_modules/ag-grid-community/dist/styles/ag-theme-dark.css', lang: 'css' }\n ],\n\n /*\n ** Plugins to load before mounting the App\n */\n plugins: [\n {\n src: '~/plugins/plugin-ag-grid.js',\n ssr: false\n },\n {\n src: '~plugins/plugin-vue-chartjs.js',\n ssr: false\n }\n ],\n\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://axios.nuxtjs.org/usage\n '@nuxtjs/axios',\n // Doc: https://buefy.github.io/#/documentation\n 'nuxt-buefy',\n '@nuxtjs/pwa',\n '@nuxtjs/dotenv'\n ],\n /*\n ** Axios module configuration\n */\n axios: {\n // See https://github.com/nuxt-community/axios-module#options\n },\n\n /*\n ** Build configuration\n */\n build: {\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {\n config.resolve.alias['vue'] = 'vue/dist/vue.common'\n // Run ESLint on save\n if (ctx.isDev && ctx.isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n config.node = {\n fs: 'empty'\n }\n }\n },\n env: {\n baseUrl: process.env.BASE_URL || 'http://localhost:3000'\n }\n}\n```\n\n```js\nimport * as agGridEnterpise from 'ag-grid-enterprise/main'\nrequire('dotenv').config()\nagGridEnterpise.LicenseManager.setLicenseKey([process.env.AG_LICENSE_KEY])\n```\n\n```js\n<template>\n <ag-grid-vue\n style=\"width: 500px; height: 500px;\"\n class=\"ag-theme-balham\"\n :columnDefs=\"columnDefs\"\n :rowData=\"rowData\"\n ></ag-grid-vue>\n</template>\n<script>\nimport { AgGridVue } from 'ag-grid-vue'\n\nexport default {\n name: 'AgGridDemo',\n data() {\n return {\n columnDefs: null,\n rowData: null\n }\n },\n components: {\n AgGridVue\n },\n beforeMount() {\n this.columnDefs = [\n { headerName: 'Make', field: 'make' },\n { headerName: 'Model', field: 'model' },\n { headerName: 'Price', field: 'price' }\n ]\n\n this.rowData = [\n { make: 'Toyota', model: 'Celica', price: 35000 },\n { make: 'Ford', model: 'Mondeo', price: 32000 },\n { make: 'Porsche', model: 'Boxter', price: 72000 }\n ]\n }\n}\n</script>\n```\n\n```js\n<template>\n <section class=\"section\">\n Welcome to test page\n <aggriddemo></aggriddemo>\n </section>\n</template>\n<script>\n\nimport AgGridDemo from '~/components/AgGridDemo'\nexport default {\n name: 'IndexPage',\n components: {\n AgGridDemo\n }\n}\n</script>\n```\n\n```js\n<template>\n <ag-grid-vue\n style=\"width: 500px; height: 500px;\"\n class=\"ag-theme-balham\"\n :columnDefs=\"columnDefs\"\n :rowData=\"rowData\"\n ></ag-grid-vue>\n</template>\n<script>\nimport { AgGridVue } from 'ag-grid-vue'\n\nexport default {\n name: 'ag-grid-demo',\n data() {\n return {\n columnDefs: null,\n rowData: null\n }\n },\n components: {\n AgGridVue\n },\n beforeMount() {\n this.columnDefs = [\n { headerName: 'Make', field: 'make' },\n { headerName: 'Model', field: 'model' },\n { headerName: 'Price', field: 'price' }\n ]\n\n this.rowData = [\n { make: 'Toyota', model: 'Celica', price: 35000 },\n { make: 'Ford', model: 'Mondeo', price: 32000 },\n { make: 'Porsche', model: 'Boxter', price: 72000 }\n ]\n }\n}\n</script>\n\n<style lang=\"scss\">\n @import \"~/node_modules/ag-grid-community/dist/styles/ag-grid.css\";\n @import \"~/node_modules/ag-grid-community/dist/styles/ag-theme-balham.css\";\n</style>\n```\n\n```text\n<template>\n <section>\n <comAgGridDemo v-if=\"mostrarGrid \" ></comAgGridDemo>\n </section>\n</template>\n\n<script lang=\"ts\">\nimport { Component, Vue } from \"nuxt-property-decorator\";\n// import comAgGridDemo from '~/components/comAgGridDemo.vue'\nconst comAgGridDemo = () => import('~/components/comAgGridDemo.vue');\n\n@Component({\n components: {\n comAgGridDemo\n }\n})\nexport default class extends Vue {\n mostrarGrid: boolean = false;\n\n mounted() {\n this.mostrarGrid = true\n }\n\n}\n</script>\n```\n\n```js\n<template>\n <section>\n <no-ssr>\n <comAgGridDemo ></comAgGridDemo>\n </no-ssr>\n </section>\n</template>\n\n<script lang=\"ts\">\nimport { Component, Vue } from \"nuxt-property-decorator\";\n// import comAgGridDemo from '~/components/comAgGridDemo.vue'\nconst comAgGridDemo = () => import('~/components/comAgGridDemo.vue');\n\n@Component({\n components: {\n comAgGridDemo\n }\n})\nexport default class extends Vue {\n\n}\n</script>\n```\n\n```js\n<template>\n <section class=\"section\">\n Welcome to test page\n <no-ssr>\n <ag-grid-demo></ag-grid-demo>\n </no-ssr>\n </section>\n</template>\n \n<script>\nlet AgGridDemo = {}\nif (process.browser) {\n AgGridDemo = require('~/components/AgGridDemo')\n}\nexport default {\n components: {\n 'ag-grid-demo': AgGridDemo\n }\n}\n</script>\n```\n\n```js\nplugins: [\n '~/plugins/plugin-ag-grid.client.js'\n //Note the .client.js This is shorthand for the following which you can also use\n src: { '~/plugins/plugin-ag-grid.js', mode: client }\n]\n```\n\n```js\nbuild: {\n ...\n transpile: [\n '/plugins',\n ],\n}\n```\n\n```js\n//nuxt.config.js\nconst nodeExternals = require('webpack-node-externals')\n\nmodule.exports = {\n /**\n * All other config code\n */\n build: {\n extend(config, ctx) {\n if (ctx.isServer) {\n config.externals = [\n nodeExternals({\n whitelist: [/^@components\\\\AgGridDemo.vue/] \n // or however you regex a windows path\n })\n ]\n }\n }\n }\n}\n```\n\n```text\n<ag-grid-demo/>\n```\n\n```text\nssr: false\n```\n\n```text\nssr: false\n```\n\n```text\nbuild-transpile\n```\n\n```text\nconst paths = ['/hear is the name of the page'] // hear is the name of the page\n // A very simple check\n if (paths.includes(req.originalUrl)) {\n // Will trigger the \"traditional SPA mode\"\n res.spa = true\n }\n // Don't forget to call next in all cases!\n // Otherwise, your app will be stuck forever :|\n next()\n }\n```\n\n========================================\n\nComments:\n- Thanks for the response Andrew! I think this fixed it. I am not getting Syntax Error anymore now, however few other issues are still preventing me to render ag-grid. Looking into this and will mark your answer as correct as soon as I make sure this fixed it!\n- I am getting now [Vue warn]: Failed to mount component: template or render function not defined. found in ---> If I replace back the line where we have is browser with import AgGridDemo from '~/components/AgGridDemo' and save, grid works when the dev auto reload occurs, but If I reload the page manually cntrl+f5 on pc I get again : Missing Stack Frames.\n- @Nesha8x8 I've added an edit that might help. You're not using IE11 by any chance are you?\n- No, testing in chrome and brave (chromium)","metadata":{"transformedAt":"2026-08-18T18:33:07.885Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":669,"estimatedTokens":3230}}663{"id":"stack-74414309","source":"stackoverflow","questionId":74414309,"title":"How to use @heroicons/vue in Nuxt3?","tags":["javascript","vue.js","nuxt.js","nuxt3.js","heroicons"],"text":"Title: How to use @heroicons/vue in Nuxt3?\nTags: javascript, vue.js, nuxt.js, nuxt3.js, heroicons\nSource: Stack Overflow\n\nQuestion:\ni want to import `@heroicons/vue` in Nuxt 3 but my icon not appear in frontend.\n\nmy setup:\n\n```\nimport { HomeIcon, FilmIcon, PlusIcon } from \"@heroicons/vue/solid\"\n```\n\nmy html:\n\n```\n\n \n \n \n \n \n\n```\n\nthe variable `profile.Item.icon` has a string value of \"HomeIcon\"\n\nhttps://i.sstatic.net/hrtVg.png\n\nI have tried to pass the value directly to the child component \"ProfileItem.vue\" but i receive the same error message.\n\nWhen i pass the value directly as string (\"HomeIcon\" instead of `profile.Item.icon`) than it works because it mentioned the attribute from `import { HomeIcon, FilmIcon, PlusIcon } from \"@heroicons/vue/solid`\n\n```\n\n```\n\nDid anyone know how to load the icons dynamically?\n\n========================================\n\nTop Answer:\nYou can also use it without `` and register the icon as a component. Should also work with the composition api.\n\n```\n\n \n\nimport { CheckCircleIcon } from \"@heroicons/vue/24/solid\";\n\nexport default {\n components: {\n CheckCircleIcon,\n }\n}\n\n```\n\n========================================\n\nCode:\n```js\nimport { HomeIcon, FilmIcon, PlusIcon } from \"@heroicons/vue/solid\"\n```\n\n```html\n<template v-for=\"(profileItem, i) in accountSetFields\" :key=\"i\">\n <ProfileItems :user=\"user\" :item=\"profileItem\" />\n <template v-slot:icon>\n <component :is=\"profileItem.icon\"></component>\n </template>\n </ProfileItems>\n</template>\n```\n\n```html\n<component :is=\"HomeIcon\"></component>\n```\n\n```text\n@heroicons/vue\n```\n\n```text\nprofile.Item.icon\n```\n\n```text\nprofile.Item.icon\n```\n\n```text\nimport { HomeIcon, FilmIcon, PlusIcon } from \"@heroicons/vue/solid\n```\n\n```html\n<script setup>\nimport { HomeIcon, FilmIcon, PlusIcon } from \"@heroicons/vue/24/solid\"\n\nconst icons = reactive({\n home: HomeIcon,\n film: FilmIcon,\n plus: PlusIcon,\n})\n</script>\n\n<template>\n <component :is=\"icons.home\"></component>\n</template>\n```\n\n```text\n24\n```\n\n```text\n<template>\n <CheckCircleIcon />\n</template>\n\n<script>\nimport { CheckCircleIcon } from \"@heroicons/vue/24/solid\";\n\nexport default {\n components: {\n CheckCircleIcon,\n }\n}\n</script>\n```\n\n```text\n<component/>\n```\n\n========================================\n\nComments:\n- perfect! this works for me.. in my case i cannot add \"24\" to the import package because is not supported in nuxt 3 but i can add the class to the component.. thank you a lot!\n- When building nuxt3 with yarn build and heroicons 1.0.6 this will result in the following error: Unexpected token (Note that you need plugins to import files that are not JavaScript). Also added '@heroicons/vue' in nuxt.config.tx build transpile.","metadata":{"transformedAt":"2026-08-18T18:33:07.885Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":140,"estimatedTokens":676}}664{"id":"stack-66470164","source":"stackoverflow","questionId":66470164,"title":"How to use TinyMCE in Nuxt?","tags":["javascript","vue.js","tinymce","nuxt.js","script-tag"],"text":"Title: How to use TinyMCE in Nuxt?\nTags: javascript, vue.js, tinymce, nuxt.js, script-tag\nSource: Stack Overflow\n\nQuestion:\nI want to add this script to my Nuxt code:\n\n```\n\n tinymce.init({\n selector: \"#mytextarea\",\n plugins: \"emoticons\",\n toolbar: \"emoticons\",\n toolbar_location: \"bottom\",\n menubar: false\n });\n\n```\n\nI can just throw it into my component's template body (**This script has to be inside `` not ``)** like this:\n\nhttps://i.sstatic.net/3a4xS.png\n\nand interestingly enough it works but there are two issues here:\n\n- It looks ugly\n\n- It's not dynamic. For example I can't bind `selector` dynamically to a prop or a data property! It has to be hardcoded.\n\nSo I was wondering if anybody knows how can I integrate such scripts into my Nuxt project properly?\n\n========================================\n\nTop Answer:\nAs mentioned in the accepted answer, the official vue package is the way to go. Even with the official package, there were a number of issues once I pulled it into Nuxt.\n\nHere's a step by step of how I got it working. Here are the versions of everything involved:\n\n```\n\"tinymce\": \"^5.10.3\",\n \"@tinymce/tinymce-vue\": \"^3.2.8\",\n \"vue\": \"^2.6.11\",\n \"nuxt\": \"2.15.8\",\n```\n\nThe tinymce-vue package requires a tinymce to be available. You can either install it via npm like above, or use the cloud-hosted version (see Prerequisites here).\n\n### Nuxt-specific Issues\n\nYou'll need to ensure the component is wrapped in the `` tag to avoid SSR errors.\n\nAdditionally, if self-hosting the tinymce package, you'll want to only import it on the client-side. Otherwise you will see errors like:\n`[Vue warn]: Failed to resolve async component: ... Reason: ReferenceError: navigator is not defined`\n\nYou can do this by using `require` and `if (process.client) {` around them.\n\nEx:\n\n```\nif (process.client) {\n require('tinymce/tinymce')\n require('tinymce/themes/silver')\n require('tinymce/icons/default')\n require('tinymce/plugins/lists') // do this for any plugins you use on the editor\n}\n\nimport Editor from '@tinymce/tinymce-vue'\n```\n\nAt this point the editor should be loading on your page, but styles are probably not loading.\n\nYou can fix this by adding `require('tinymce/skins/ui/oxide/skin.min.css')` below the other `require`s.\n\nNow the styles will be fixed but the tinymce theme will still look for other CSS files like mobile, min versions on its own, and cause network errors.\n\nEx:\n\n```\n404 http://localhost:3000/_nuxt/skins/ui/oxide/content.min.css\n404 http://localhost:3000/_nuxt/skins/ui/oxide/skin.min.css\n```\n\n**For content:**\nYou can either copy that file to the static folder with the same path, or override them with the content_css setting (in the Vue component `init` options).\n\n**For skin:**\nSince you already provided it as a module, set `skin: false` in the Vue component `init` options.\n\nUPDATED 2022-11-29: Fixed Typo\n\n========================================\n\nCode:\n```text\n<script>\n tinymce.init({\n selector: \"#mytextarea\",\n plugins: \"emoticons\",\n toolbar: \"emoticons\",\n toolbar_location: \"bottom\",\n menubar: false\n });\n</script>\n```\n\n```text\n<body>\n```\n\n```text\n<head>\n```\n\n```text\nselector\n```\n\n```js\nconst ed = Vue.component(\"MyEditor\", {\n props: [\"id\", \"value\"],\n template: `\n <div>\n <textarea :id=\"id\" :value=\"value\"></textarea>\n </div>\n `,\n mounted() {\n const me = this;\n window.tinymce.init({\n selector: \"#\" + this.id,\n plugins: \"emoticons\",\n toolbar: \"emoticons\",\n toolbar_location: \"bottom\",\n menubar: false,\n setup: function (editor) {\n editor.on(\"change input undo redo\", function () {\n me.$emit('input', editor.getContent({format: 'text'}))\n });\n }\n });\n }\n});\n```\n\n```text\n<script>\n```\n\n```text\n<script>\n```\n\n```text\n<keep-alive>\n```\n\n```text\nwindow\n```\n\n```text\n<client-only>\n```\n\n```text\nmounted\n```\n\n```text\n<client-only>\n```\n\n```text\n\"tinymce\": \"^5.10.3\",\n \"@tinymce/tinymce-vue\": \"^3.2.8\",\n \"vue\": \"^2.6.11\",\n \"nuxt\": \"2.15.8\",\n```\n\n```text\nif (process.client) {\n require('tinymce/tinymce')\n require('tinymce/themes/silver')\n require('tinymce/icons/default')\n require('tinymce/plugins/lists') // do this for any plugins you use on the editor\n}\n\nimport Editor from '@tinymce/tinymce-vue'\n```\n\n```text\n404 http://localhost:3000/_nuxt/skins/ui/oxide/content.min.css\n404 http://localhost:3000/_nuxt/skins/ui/oxide/skin.min.css\n```\n\n```text\n<client-only>\n```\n\n```text\n[Vue warn]: Failed to resolve async component: ... Reason: ReferenceError: navigator is not defined\n```\n\n```text\nrequire\n```\n\n```text\nif (process.client) {\n```\n\n```text\nrequire('tinymce/skins/ui/oxide/skin.min.css')\n```\n\n```text\nrequire\n```\n\n```text\ninit\n```\n\n```text\nskin: false\n```\n\n```text\ninit\n```\n\n========================================\n\nComments:\n- It actually worked. Thanks. However could you please give me an explanation for the `setup: function (editor)` part? What does it do and why do we need to add it there?\n- Yes I know it works but as I said, don't use my code. It is missing very important part - destroying editor when component is destroyed. I could add it but it seems as waste of time if there is official integration for Vue from the authors of TinyMCE. The know their editor better....\n- setup is a function called by TinyMCE. It is useful for setting up event handlers. In my example I handle events emitted when content of editor is changed in order to emit Vue `input` event - this makes `v-model` on the component work...\n- Aha makes sense. There are more scripts from other sources I want to integrate most of which don't have official integration for Vue. How do you suggest I go on about integrating them?","metadata":{"transformedAt":"2026-08-18T18:33:07.885Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":237,"estimatedTokens":1417}}665{"id":"stack-68384675","source":"stackoverflow","questionId":68384675,"title":"Nuxt.js - Google Analytics setup not tracking any activity","tags":["vue.js","google-analytics","nuxt.js"],"text":"Title: Nuxt.js - Google Analytics setup not tracking any activity\nTags: vue.js, google-analytics, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to setup Google Analytics tracking for a Nuxt.js application but I'm not getting any data at all. I feel like I must be missing something obvious.\n\nI have looked at https://google-analytics.nuxtjs.org/ and gone through the first setup page. Do I need to do anything more? The documentation promises that the router instance is added out of the box during installation, so it should handle page tracking automatically, but this has not been my experience.\n\nI have added the Google Analytics module twice, as seen below, to nuxt.config.js just looking for a pulse but no such luck. I have also tried each individually. The ID I am passing in is already being used on another website, and my application builds without errors:\n\n```\nbuildModules : [\n '@nuxtjs/eslint-module',\n '@nuxtjs/style-resources',\n '@nuxtjs/google-analytics'\n],\ngoogleAnalytics: {\n id: 'GTM-MYIDHERE',\n layer: 'dataLayer',\n pageTracking: true\n},\nmodules : [\n ['nuxt-modernizr',\n {\n 'feature-detects' : ['touchevents', 'img/webp'],\n options : ['setClasses']\n }],\n ['@nuxtjs/google-analytics', { \n id: 'MYIDHERE',\n layer: 'dataLayer',\n pageTracking: true\n }]\n],\n```\n\nAny help here would be greatly appreciated.\n\n========================================\n\nCode:\n```js\nbuildModules : [\n '@nuxtjs/eslint-module',\n '@nuxtjs/style-resources',\n '@nuxtjs/google-analytics'\n],\ngoogleAnalytics: {\n id: 'GTM-MYIDHERE',\n layer: 'dataLayer',\n pageTracking: true\n},\nmodules : [\n ['nuxt-modernizr',\n {\n 'feature-detects' : ['touchevents', 'img/webp'],\n options : ['setClasses']\n }],\n ['@nuxtjs/google-analytics', { \n id: 'MYIDHERE',\n layer: 'dataLayer',\n pageTracking: true\n }]\n],\n```\n\n```js\ngoogleAnalytics: {\n id: 'GTM-MYIDHERE', // <-- GTM- is Google Tag Manager ID\n layer: 'dataLayer',\n pageTracking: true\n},\n```\n\n```text\nUA-XXXXXX-XX\n```\n\n========================================\n\nComments:\n- You should probably remove the `@nuxtjs/google-analytics` to prevent any issues. And if Michele's solution is not working, you should probably have an error in your browser's console.\n- @kissu - Do you mean remove it from the buildModules or remove it from the modules?\n- In the setup, it never mentions `modules`, so yeah: remove it from `modules`. google-analytics.nuxtjs.org/setup\n- If your Nuxt version is `< v2.9`, let it in modules yeah. But I hope it's not that old.\n- Thanks. In addition, I had to specify that I wanted to log events in debug. Adding debug: { sendHitTask: true } to googleAnalytics and changing the ID so it's the right ID did the trick.","metadata":{"transformedAt":"2026-08-18T18:33:07.885Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":86,"estimatedTokens":679}}666{"id":"stack-61593710","source":"stackoverflow","questionId":61593710,"title":"Accessing Nuxt plugin function in vuex getter","tags":["javascript","plugins","vuex","nuxt.js"],"text":"Title: Accessing Nuxt plugin function in vuex getter\nTags: javascript, plugins, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am getting started with nuxtjs and vuex. I just encountered an issue accessing a combined injected plugin function from a getter. E.g.:\n\n*nuxt.config.js*\n\n```\n...\nplugins: [\n '~/plugins/myplugin.js' \n ],\n...\n```\n\n*~/plugins/myplugin.js*\n\n```\nfunction doSomething(string) {\n console.log(\"done something: \" + string)\n }\n\nexport default ({ app }, inject) => {\n inject('doSomething', (string) => doSomething(string))\n }\n```\n\n*~/store/index.js*\n\n```\nexport const actions = {\n someAction({commit}) {\n this.$doSomething(\"Called from Action\") // works\n }\n}\n\nexport const getters = {\n someGetter: state => {\n this.$doSomething(\"Called from Getter\") // throws error\n }\n}\n```\n\nThe code works for the action `someAction` but the call in getter `someGetter` will result in a error suggesting `this` is undefined. \n\nThe nuxt documentation only shows examples for accessing injected plugin functions from mutations and actions but does not explicitly mention that getters can not access plugin functions. Is this even possible in nuxt or is there a good reason not to call a plugin method in a getter? Any help appreciated.\n\n========================================\n\nTop Answer:\nI faced the same issue and I was able to get around it by doing \n\n```\nexport const getters = {\n someGetter: state => {\n $nuxt.$doSomething(\"Called from Getter\") // Grab $nuxt from the global scope\n }\n}\n```\n\nNot sure if this works in SSR mode however\n\n========================================\n\nCode:\n```text\n...\nplugins: [\n '~/plugins/myplugin.js' \n ],\n...\n```\n\n```text\nfunction doSomething(string) {\n console.log(\"done something: \" + string)\n }\n\nexport default ({ app }, inject) => {\n inject('doSomething', (string) => doSomething(string))\n }\n```\n\n```text\nexport const actions = {\n someAction({commit}) {\n this.$doSomething(\"Called from Action\") // works\n }\n}\n\nexport const getters = {\n someGetter: state => {\n this.$doSomething(\"Called from Getter\") // throws error\n }\n}\n```\n\n```text\nsomeAction\n```\n\n```text\nsomeGetter\n```\n\n```text\nthis\n```\n\n```text\ndo_something\n```\n\n```text\ncompletedTasks: state => state.tasks.filter(task => task.completed)\n```\n\n```text\nthis.$do_something\n```\n\n```text\nexport const getters = {\n someGetter: state => {\n $nuxt.$doSomething(\"Called from Getter\") // Grab $nuxt from the global scope\n }\n}\n```\n\n========================================\n\nComments:\n- It might work and of course I don't know your use case, but I don't think you should be doing this :-) Like I highlighted in my answer, I think getters should just be used to derive state from the store's state.\n- You certainly have a good point. In my case the \"derived\" state depended on a parameter and I needed to do something with that parameter. for example getSeries: (state) => (parameter) => { return state[getKeyFromParameter(parameter)] } Not sure if having getters with parameters is a good idea after all\n- Yeah then you use a getter that returns a function, like your `getSeries`. But if you need something out of Nuxt, I'd pass it to the getter function at the call site instead of fishing it out of $nuxt in the getter. That keeps your getters nicely decoupled from Nuxt and anything else except the state.\n- Thanks for the answer, I guessed that it is considered a bad practice, but could not find any explicit statement about it. Your answer made that point clear. My use case was the following: The getter would be used to retrieve some data from the state and format it for further usage (getter may be named `getDataFormatted`). Since the code doing the formatting may be used in other places/stores I thought it would be best to provide it via plugin keeping everything dry. But I can see your point and guess the formatting should preferably be done where the data is used in the end.","metadata":{"transformedAt":"2026-08-18T18:33:07.885Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":138,"estimatedTokens":983}}667{"id":"stack-72133224","source":"stackoverflow","questionId":72133224,"title":"How to prerender a Vue3 application?","tags":["vue.js","nuxt.js","vuejs3","prerender","nuxt3.js"],"text":"Title: How to prerender a Vue3 application?\nTags: vue.js, nuxt.js, vuejs3, prerender, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI try without success to apply a prerendering (or a SSG) to my Vue3 application to make it more SEO friendly.\n\nI found the vue-cli-plugin-prerender-spa, and when I try it with the command line: `vue add prerender-spa` I have the error:\n\nERROR TypeError: Cannot read properties of undefined (reading 'endsWith')\n\nAfter that I tried `prerender-spa-plugin` but I have an error when I make a `npm run build`:\n\n[prerender-spa-plugin] Unable to prerender all routes!\nERROR Error: Build failed with errors.\nError: Build failed with errors.\nat /Users/myusername/Workspace/myproject/node_modules/@vue/cli-service/lib/commands/build/index.js:207:23\nat /Users/myusername/Workspace/myproject/node_modules/webpack/lib/webpack.js:148:8\nat /Users/myusername/Workspace/myproject/node_modules/webpack/lib/HookWebpackError.js:68:3\n\nWhat do you think about this? Do you have any idea?\n\n========================================\n\nTop Answer:\nI struggled with the same error output until I found the prerender-spa-plugin-next. Then I notice the latest version of prerender-spa-plugin was published 4 years ago and prerender-spa-plugin-next is continually updating. It seems like that prerender-spa-plugin-next is a new version of prerender-spa-plugin with the same functions. So I use prerender-spa-plugin-next instead of prerender-spa-plugin then everything works fine!\n\nHere is my step:\n\n- install the package\n\n```\nnpm i -D prerender-spa-plugin-next\n```\n\n- modify vue.config.js like\n\n```\nconst plugins = [];\n\nif (process.env.NODE_ENV === 'production') {\n const { join } = require('path');\n const PrerenderPlugin = require('prerender-spa-plugin-next');\n\n plugins.unshift(\n new PrerenderPlugin({\n staticDir: join(__dirname, 'dist'),\n routes: ['/'], //the page route you want to prerender\n })\n );\n}\n\nmodule.exports = {\n transpileDependencies: true,\n configureWebpack(config) {\n config.plugins = [...config.plugins, ...plugins];\n },\n};\n```\n\n- build\n\n```\nnpm run build\n```\n\nThen check the index.html under the dist folder you can see the page is prerendered.\n\nFurther usage refers to the homepage of prerender-spa-plugin-next\n\n========================================\n\nCode:\n```text\nvue add prerender-spa\n```\n\n```text\nprerender-spa-plugin\n```\n\n```text\nnpm run build\n```\n\n```text\nvite: {\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: `\n @import \"@/assets/scss/_variables.scss\";\n @import \"@/assets/scss/my-style.scss\";\n `\n }\n },\n },\n}\n```\n\n```text\nnpm i -D prerender-spa-plugin-next\n```\n\n```text\nconst plugins = [];\n\nif (process.env.NODE_ENV === 'production') {\n const { join } = require('path');\n const PrerenderPlugin = require('prerender-spa-plugin-next');\n\n plugins.unshift(\n new PrerenderPlugin({\n staticDir: join(__dirname, 'dist'),\n routes: ['/'], //the page route you want to prerender\n })\n );\n}\n\n\nmodule.exports = {\n transpileDependencies: true,\n configureWebpack(config) {\n config.plugins = [...config.plugins, ...plugins];\n },\n};\n```\n\n```text\nnpm run build\n```\n\n========================================\n\nComments:\n- The package you're using here got his latest commit in 26 September 2019, so it's safe to say that it's not really relevant anymore. Did you gave a look to Vitesse or even Nuxt3? Those are probably one of the best solutions available to date regarding SSG.\n- If you purely want to pre-render and nothing else, you can also use this service but I rather use any of the 2 solutions above. Or even this one.\n- Hi @kissu thanks for these ideas. If I understand, the first step will be to migrate my code in Vite or Nuxt ? It seems to be difficult with my App in VueCli ? Thanks.\n- It's not that difficult. It can even be as simple as just copy pasting some of your files there (I'm assuming your project is not super huge overall).\n- Yes sure, I was just to confirm that it's the fisrt step to do ;) thanks\n- Mind if I post a simple answer basically saying \"just use nuxt :p\"?\n- No problem, I was just going to ask you a last tips. What is the best between Vitesse and Nuxt, in case of a small project (I have only 10 pages, maybe 15 in the futur).\n- This is not an answer\n- Does not seem to work .... github.com/vuejs/vue-cli/issues/5985#issuecomment-712091677","metadata":{"transformedAt":"2026-08-18T18:33:07.885Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":144,"estimatedTokens":1110}}668{"id":"stack-52710866","source":"stackoverflow","questionId":52710866,"title":"Nuxt - manipulating class properties in the document bodyattrs class","tags":["vuejs2","nuxt.js"],"text":"Title: Nuxt - manipulating class properties in the document bodyattrs class\nTags: vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI've been searching for a good solution to dynamically modify the class that can be attached to the bodyAttrs, with no success. I have found no posts that specifically address/answer my situation. I hope someone can help.\n\nI have a project I am working on and in the project I am using Nuxt with SSR functionality, The site has properties that can be manipulated with user configuration. Setting the scene... the user can manipulate the body tag, and can change background colors. \n\nI have set up the app.html page defined in the documentation (https://nuxtjs.org/guide/views#document). I have then set the head like so:\n\n```\nhead() {\n return {\n bodyAttrs: {\n class: this.dataLoaded ? \"bodyAttr\" : \"\"\n }\n };\n}\n```\n\nHere is what the bodyAttr class looks like. This is a default value at startup:\n\n```\n.bodyAttr {\n background: linear-gradient(#0098db, #0046ad);\n}\n```\n\nWhen the data is loaded, I need to dynamically change the background property colors to the values selected by the user configuration.\n\nIs there a way to do this... or am I approaching this from the wrong direction? \nThanks.\n\n========================================\n\nCode:\n```text\nhead() {\n return {\n bodyAttrs: {\n class: this.dataLoaded ? \"bodyAttr\" : \"\"\n }\n };\n}\n```\n\n```text\n.bodyAttr {\n background: linear-gradient(#0098db, #0046ad);\n}\n```\n\n```text\nexport default {\n data() {\n return {\n darkMode: false\n }\n },\n head() {\n return {\n bodyAttrs: {\n class: this.darkMode ? 'my-gradient' : 'normal-mode'\n }\n }\n },\n\n}\n```\n\n```text\n.my-gradient {\n background: linear-gradient(#0098db, #0046ad);\n}\n.normal-mode {\n background: none;\n}\n```\n\n```text\nmy-gradient\n```\n\n```text\nnormal-mode\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.885Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":87,"estimatedTokens":479}}669{"id":"stack-56376653","source":"stackoverflow","questionId":56376653,"title":"Nuxt + Vue + Vuetify: this.$vuetify.breakpoint incorrectly initialized as 'xs'","tags":["vue.js","vuetify.js","nuxt.js"],"text":"Title: Nuxt + Vue + Vuetify: this.$vuetify.breakpoint incorrectly initialized as 'xs'\nTags: vue.js, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nUsing vuetify breakpoints to switch between mobile and desktop layouts for a website\n\nMy code is (shrinked(\n\n```\n\n .\n .\n components and stuff\n .\n .\n \n\n \n .\n .\n computed: {\n mobile: function () {\n return ['xs', 'sm'].includes(this.$vuetify.breakpoint.name)\n }\n }\n .\n .\n \n```\n\nSo Im using a computed function to determine if the client has a small screen\n\nMy problem is that the `this.$vuetify.breakpoint.name` is initially set as `xs` \n\nMy workaround currently is having a `loaded` method and on the top level doing \n\n```\n\n .\n \n .\n .\n\n```\n\nBut now I also have to wrap the entire thing with ``\n\nIs there a more correct way to load the components correctly so that they dont jump from mobie version to full size version after the page fully loads?\n\n========================================\n\nCode:\n```text\n<v-layout wrap :column=\"mobile\">\n .\n .\n components and stuff\n .\n .\n <v-layout>\n\n <script>\n .\n .\n computed: {\n mobile: function () {\n return ['xs', 'sm'].includes(this.$vuetify.breakpoint.name)\n }\n }\n .\n .\n </script>\n```\n\n```text\n<v-app v-if=\"loaded\"\n .\n .\n <v-layout>\n .\n </v-layout>\n .\n .\n<v-app>\n```\n\n```text\nthis.$vuetify.breakpoint.name\n```\n\n```text\nxs\n```\n\n```text\nloaded\n```\n\n```text\n<NoSsr>\n```\n\n```js\ndata: () => ({\n // ...\n isMounted: false\n }),\n mounted() {\n this.isMounted = true;\n },\n // ...\n computed: {\n mobile: function () {\n return this.isMounted && ['xs', 'sm'].includes(this.$vuetify.breakpoint.name);\n }\n }\n```\n\n```text\nmounted()\n```\n\n```text\ncomputed\n```\n\n```text\nmobile detection\n```\n\n========================================\n\nComments:\n- This works great. Do you have a suggestion on how to have the mobile var application wide? Commit it to vuex store inside the root component?","metadata":{"transformedAt":"2026-08-18T18:33:07.885Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":135,"estimatedTokens":524}}670{"id":"stack-60134881","source":"stackoverflow","questionId":60134881,"title":"Nuxt js - window or document is not defined","tags":["nuxt.js"],"text":"Title: Nuxt js - window or document is not defined\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have seen many questions related to this topic. But none of them solved my problem. \n\nI have a situation, where I've to check the `innerWidth` of the window, to check if the device is mobile or not using the `isMobile` variable.\n\n```\n\n \n ...\n \n\n```\n\nBelow is my script code. I'm checking `process.client` but it is coming as `false`. I don't know if I've missed something which I need to add somewhere *(maybe nuxt.config.js)*.\n\n```\ndata() {\n return {\n isMobile: false,\n };\n },\n mounted() {\n if (process.client) {\n console.log(\"Hello from the client!\");\n this.isMobile = window.innerWidth https://i.sstatic.net/NK4b1.png\n\n========================================\n\nCode:\n```text\n<div v-if=\"isMobile\" class=\"stores\">\n <p class=\"text-uppercase text-muted mb-0 mt-4\">\n ...\n </p>\n</div>\n```\n\n```text\ndata() {\n return {\n isMobile: false,\n };\n },\n mounted() {\n if (process.client) {\n console.log(\"Hello from the client!\");\n this.isMobile = window.innerWidth < 768;\n }\n console.log('process', process.client); // Logs as false\n },\n```\n\n```text\ninnerWidth\n```\n\n```text\nisMobile\n```\n\n```text\nprocess.client\n```\n\n```text\nfalse\n```\n\n```text\ncreated() {\n if (process.client) {\n console.log(\"Hello from the client!\")\n }\n console.log(\"Hello from the server... and also the client!\")\n}\n```\n\n```text\nNuxt SSR\n```\n\n```text\nconsole.log\n```\n\n```text\nNuxt SSR\n```\n\n```text\nprocess false\n```\n\n```text\nprocess true\n```\n\n```text\ncreated()\n```\n\n```text\nmounted()\n```\n\n```text\ncreated()\n```\n\n```text\nmounted()\n```\n\n```text\nprocess.client\n```\n\n```text\ntrue\n```\n\n```text\nfalse\n```\n\n========================================\n\nComments:\n- I have changed and checked under `mounted` as well, but I can't see any log from `Hello from client`","metadata":{"transformedAt":"2026-08-18T18:33:07.885Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":133,"estimatedTokens":470}}671{"id":"stack-77022535","source":"stackoverflow","questionId":77022535,"title":"How to fix CORS error on 3rd party API call in Nuxt 3?","tags":["vue.js","cors","nuxt.js","nuxt3.js"],"text":"Title: How to fix CORS error on 3rd party API call in Nuxt 3?\nTags: vue.js, cors, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am working on Nuxt 3 with `useFetch` hook to call API. When I call the 3rd party API post `https://apitest.bankfeeds.com.au/v1/customer/data` using useFetch hook, it returns the CORS error\n\nCORS Missing Allow Origin\n\nI have the ssr: false in my `nuxt.config.ts` file\n\nhttps://i.sstatic.net/hD1dk.png\n\nI have tried to set cors on nuxt config file but not working and returns the same error.\n\n========================================\n\nTop Answer:\nUse server/api folder to avoid such problems. This way you don't have to lose the benefits of useFetch composable. Make your requests server-to-server via Nitro.\n\napi/server/auth.post.js\n\n```\nexport default defineEventHandler(async (event) => {\n const body = await readBody(event);\n const runtimeConfig = useRuntimeConfig();\n\n try {\n await $fetch(`${runtimeConfig.public.apiBase}/login`, {\n method: \"POST\",\n body: { username: body.username, password: body.password },\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (err) {\n throw createError({\n message: \"Authorization Failed\",\n statusCode: 401,\n });\n }\n\n return {\n message: \"success\",\n };\n});\n```\n\n========================================\n\nCode:\n```text\nuseFetch\n```\n\n```text\nhttps://apitest.bankfeeds.com.au/v1/customer/data\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nexport default defineEventHandler(async (event) => {\n const body = await readBody(event);\n const runtimeConfig = useRuntimeConfig();\n\n try {\n await $fetch(`${runtimeConfig.public.apiBase}/login`, {\n method: \"POST\",\n body: { username: body.username, password: body.password },\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (err) {\n throw createError({\n message: \"Authorization Failed\",\n statusCode: 401,\n });\n }\n\n return {\n message: \"success\",\n };\n});\n```\n\n========================================\n\nComments:\n- Does this answer your question? No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API\n- looks like makes sense but I want this on nuxt 3 so how can I configure the origin proxy policy to call 3rd party API with front end only? Please help me with this\n- Yes in postmen it working fine. but I am using useFetch without any backend can you help me how can I sort out this without backend?\n- You have to call the `useFetch` in backend. You can the docs here on how to make it server-side.\n- seems there is vue or nuxt 2 code not the nuxt 3 latest versions. Do you mean that I need to use server side rendering to use this?\n- Yes. You have to use ssr or choose to integrate a different/separate backend. Sorry for the reference to the guide (didn’t notice it’s outdated)\n- ok thanks for your revert on this. I'll use the backend API and call this from the backend.","metadata":{"transformedAt":"2026-08-18T18:33:07.885Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":95,"estimatedTokens":729}}672{"id":"stack-56569793","source":"stackoverflow","questionId":56569793,"title":"Syntax error setting up nuxt/vue debugging with vs code","tags":["node.js","vue.js","visual-studio-code","git-bash","nuxt.js"],"text":"Title: Syntax error setting up nuxt/vue debugging with vs code\nTags: node.js, vue.js, visual-studio-code, git-bash, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to set up debugging of a nuxt/vue project in vs code on win 10 . I'm using git-bash. I've found https://medium.com/@justin.ramel/nuxt-js-debugging-in-visual-studio-code-822ff9d51c77\n\nFollowing the directions I've changed my package.json to \n\n```\n{\n \"name\": \"nuxt4\",\n \"version\": \"1.0.0\",\n \"description\": \"My classy Nuxt.js project\",\n \"author\": \"hh\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"dev-debug\": \"node --inspect node_modules/.bin/nuxt\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"cross-env\": \"^5.2.0\",\n \"glob\": \"^7.1.3\",\n \"nuxt\": \"^2.0.0\",\n \"vue2-google-maps\": \"^0.10.6\",\n \"vuetify\": \"^1.2.4\",\n \"vuex\": \"^3.0.1\"\n },\n \"devDependencies\": {\n \"nodemon\": \"^1.11.0\",\n \"stylus\": \"^0.54.5\",\n \"stylus-loader\": \"^3.0.2\"\n }\n}\n```\n\nLaunch.json:\n\n```\n{\n \"configurations\": [\n{\n \"type\": \"node\",\n \"request\": \"attach\",\n \"name\": \"Attach to Nuxt\",\n \"port\": 9229\n }\n]\n\n}\n```\n\nHowever:\n\n```\n$ npm run dev-debug\n\n> nuxt4@1.0.0 dev-debug E:\\ENVS\\js\\nuxt4\n> node --inspect=0.0.0.0 node_modules/.bin/nuxt\n\nDebugger listening on ws://0.0.0.0:9229/4eda468d-39a4-4ddb-9a73-23e4fa60ed8e\nFor help, see: https://nodejs.org/en/docs/inspector\nE:\\ENVS\\js\\nuxt4\\node_modules\\.bin\\nuxt:2\nbasedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n ^^^^^^^\n\nSyntaxError: missing ) after argument list\n at new Script (vm.js:83:7)\n at createScript (vm.js:267:10)\n at Object.runInThisContext (vm.js:319:10)\n at Module._compile (internal/modules/cjs/loader.js:684:28)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)\n at Module.load (internal/modules/cjs/loader.js:620:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:560:12)\n at Function.Module._load (internal/modules/cjs/loader.js:552:3)\n at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)\n at executeUserCode (internal/bootstrap/node.js:342:17)\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\nnpm ERR! nuxt4@1.0.0 dev-debug: `node --inspect=0.0.0.0 node_modules/.bin/nuxt`\nnpm ERR! Exit status 1\nnpm ERR!\nnpm ERR! Failed at the nuxt4@1.0.0 dev-debug script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n```\n\nThe nuxt file giving the error is:\n\n```\n#!/bin/sh\n basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n\n case $(uname) in\n *CYGWIN*) basedir=$(cygpath -w \"$basedir\");;\n esac\n\n if [ -x \"$basedir/node\" ]; then\n \"$basedir/node\" \"$basedir/../nuxt/bin/nuxt.js\" \"$@\"\n ret=$?\n else \n node \"$basedir/../nuxt/bin/nuxt.js\" \"$@\"\n ret=$?\n fi\n exit $ret\n```\n\nHow can I get this working?\n\nedit:\n\nI eventually found that\n\n```\n\"dev-debug\": \"node --inspect ./node_modules/nuxt/bin/nuxt\",\n```\n\ngot me past that error. However I have a new problem: when I try to debug I get:\n\nhttps://i.sstatic.net/Szln6.jpg\n\nIt looks like im trying to run package.json. Any Idea how to fix this?\n\nedit2:\n\nafter editing the launch json the following based on the articles:\n\n```\n{\n \"type\": \"node\",\n \"request\": \"launch\",\n \"name\": \"Launch via NPM\",\n \"runtimeExecutable\": \"npm\",\n \"runtimeArgs\": [\n \"run-script\",\n \"dev-debug\"\n ],\n\n \"program\": \"${workspaceFolder}\\\\node_modules\\\\.bin\\\\nuxt\",\n \"args\": [\n \"invoke\",\n \"local\",\n \"-f\",\n \"\",\n \"--data\",\n \"{}\" // You can use this argument to pass data to the function to help with the debug\n],\n // \"program\": \"E:\\\\ENVS\\\\js\\\\nuxt4\\\\node_modules\\\\.bin\\\\nuxt\",\n \"port\": 9229\n}\n```\n\nI'm getting \n\nhttps://i.sstatic.net/NWpVA.jpg\n\nany thoughts?\n\nedit: \n\nGetting a little closer with launch.json changed to:\n\n```\n{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"type\": \"node\",\n \"request\": \"launch\",\n \"name\": \"npm run dev\",\n \"runtimeExecutable\": \"npm\",\n \"windows\": {\n \"runtimeExecutable\": \"npm.cmd\"\n },\n \"runtimeArgs\": [\n \"run\",\n \"dev-debug\"\n ],\n \"port\": 9229\n },\n {\n \"type\": \"node\",\n \"request\": \"launch\",\n \"name\": \"Launch Program\",\n \"program\": \"${workspaceRoot}/start\"\n },\n {\n \"type\": \"node\",\n \"request\": \"attach\",\n \"name\": \"Attach to Port\",\n \"address\": \"localhost\",\n \"port\": 9229\n }\n ]\n}\n```\n\nI'm now able to attach debugger to process.it does not appear to stop at breakpoints though.\n\n========================================\n\nCode:\n```text\n{\n \"name\": \"nuxt4\",\n \"version\": \"1.0.0\",\n \"description\": \"My classy Nuxt.js project\",\n \"author\": \"hh\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"dev-debug\": \"node --inspect node_modules/.bin/nuxt\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"cross-env\": \"^5.2.0\",\n \"glob\": \"^7.1.3\",\n \"nuxt\": \"^2.0.0\",\n \"vue2-google-maps\": \"^0.10.6\",\n \"vuetify\": \"^1.2.4\",\n \"vuex\": \"^3.0.1\"\n },\n \"devDependencies\": {\n \"nodemon\": \"^1.11.0\",\n \"stylus\": \"^0.54.5\",\n \"stylus-loader\": \"^3.0.2\"\n }\n}\n```\n\n```text\n{\n \"configurations\": [\n{\n \"type\": \"node\",\n \"request\": \"attach\",\n \"name\": \"Attach to Nuxt\",\n \"port\": 9229\n }\n]\n\n}\n```\n\n```text\n$ npm run dev-debug\n\n> nuxt4@1.0.0 dev-debug E:\\ENVS\\js\\nuxt4\n> node --inspect=0.0.0.0 node_modules/.bin/nuxt\n\nDebugger listening on ws://0.0.0.0:9229/4eda468d-39a4-4ddb-9a73-23e4fa60ed8e\nFor help, see: https://nodejs.org/en/docs/inspector\nE:\\ENVS\\js\\nuxt4\\node_modules\\.bin\\nuxt:2\nbasedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n ^^^^^^^\n\nSyntaxError: missing ) after argument list\n at new Script (vm.js:83:7)\n at createScript (vm.js:267:10)\n at Object.runInThisContext (vm.js:319:10)\n at Module._compile (internal/modules/cjs/loader.js:684:28)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)\n at Module.load (internal/modules/cjs/loader.js:620:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:560:12)\n at Function.Module._load (internal/modules/cjs/loader.js:552:3)\n at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)\n at executeUserCode (internal/bootstrap/node.js:342:17)\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\nnpm ERR! nuxt4@1.0.0 dev-debug: `node --inspect=0.0.0.0 node_modules/.bin/nuxt`\nnpm ERR! Exit status 1\nnpm ERR!\nnpm ERR! Failed at the nuxt4@1.0.0 dev-debug script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n```\n\n```text\n#!/bin/sh\n basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n\n case $(uname) in\n *CYGWIN*) basedir=$(cygpath -w \"$basedir\");;\n esac\n\n if [ -x \"$basedir/node\" ]; then\n \"$basedir/node\" \"$basedir/../nuxt/bin/nuxt.js\" \"$@\"\n ret=$?\n else \n node \"$basedir/../nuxt/bin/nuxt.js\" \"$@\"\n ret=$?\n fi\n exit $ret\n```\n\n```text\n\"dev-debug\": \"node --inspect ./node_modules/nuxt/bin/nuxt\",\n```\n\n```text\n{\n \"type\": \"node\",\n \"request\": \"launch\",\n \"name\": \"Launch via NPM\",\n \"runtimeExecutable\": \"npm\",\n \"runtimeArgs\": [\n \"run-script\",\n \"dev-debug\"\n ],\n\n \"program\": \"${workspaceFolder}\\\\node_modules\\\\.bin\\\\nuxt\",\n \"args\": [\n \"invoke\",\n \"local\",\n \"-f\",\n \"<function-name>\",\n \"--data\",\n \"{}\" // You can use this argument to pass data to the function to help with the debug\n],\n // \"program\": \"E:\\\\ENVS\\\\js\\\\nuxt4\\\\node_modules\\\\.bin\\\\nuxt\",\n \"port\": 9229\n}\n```\n\n```text\n{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"type\": \"node\",\n \"request\": \"launch\",\n \"name\": \"npm run dev\",\n \"runtimeExecutable\": \"npm\",\n \"windows\": {\n \"runtimeExecutable\": \"npm.cmd\"\n },\n \"runtimeArgs\": [\n \"run\",\n \"dev-debug\"\n ],\n \"port\": 9229\n },\n {\n \"type\": \"node\",\n \"request\": \"launch\",\n \"name\": \"Launch Program\",\n \"program\": \"${workspaceRoot}/start\"\n },\n {\n \"type\": \"node\",\n \"request\": \"attach\",\n \"name\": \"Attach to Port\",\n \"address\": \"localhost\",\n \"port\": 9229\n }\n ]\n}\n```\n\n```text\n\"dev-debug\": \"node_modules/.bin/nuxt --inspect\"\n```\n\n```text\n{\n \"type\": \"node\",\n \"request\": \"launch\",\n \"name\": \"Launch via NPM\",\n \"runtimeExecutable\": \"npm\",\n \"runtimeArgs\": [\n \"run-script\",\n \"dev-debug\"\n ],\n \"port\": 9229\n }\n\n\"dev-debug\": \"node --inspect node_modules/.bin/nuxt\"\n```\n\n```text\n\"dev-debug\": \"node --inspect node_modules/nuxt/bin/nuxt\",\n```\n\n```text\n\"dev-debug\": \"node --inspect ./node_modules/nuxt/bin/nuxt\",\n```\n\n```text\n\"program\": \"${workspaceFolder}\\\\node_modules\\\\serverless\\\\bin\\\\serverless\",\n```\n\n```text\ndebugger // eslint-disable-line\n\nor:\n\n/* eslint-disable no-debugger */\n```\n\n```text\nnuxt/nuxt.js\n```\n\n```text\noutFiles\n```\n\n```text\nnode_modules/serverless/bin\n```\n\n```text\nstandard/standard\n```\n\n========================================\n\nComments:\n- try node --inspect=0.0.0.0 node_modules/nuxt/bin/nuxt\n- sorry, I'm getting the same output , please see edit.\n- You cant get the same output. node_modules/nuxt/bin/nuxt is a js file that is totally different from the one in your post\n- But you see the error : basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\") i don't understand\n- this error cant happen if u use node_modules/nuxt/bin/nuxt because its js file with totally different content\n- @user61629 I have edited my answer to address your edited question.\n- @user61629 From what I understand, using the serverless framework is key, in order to avoid that specific error message.\n- @user61629 Would `--debug-brk` help, as in stackoverflow.com/questions/34835082/…\n- @user61629 Sorry, I meant `node --inspect-brk` (stackoverflow.com/questions/43210203/…)\n- that didn't work for me , but debugger // eslint-disable-line - from the article - helped.\n- @user61629 Great! I have included that in the answer (with additional links) for more visibility.","metadata":{"transformedAt":"2026-08-18T18:33:07.885Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":432,"estimatedTokens":2434}}673{"id":"stack-77508188","source":"stackoverflow","questionId":77508188,"title":"Pass a computed property to css url() with v-bind in Vue 3","tags":["html","nuxt.js","vuejs3"],"text":"Title: Pass a computed property to css url() with v-bind in Vue 3\nTags: html, nuxt.js, vuejs3\nSource: Stack Overflow\n\nQuestion:\nI' trying to pass a computed property value to a url() in css using v-bind with Vue 3 and Nuxt:\n\n```\n\n \n\nconst props = defineProps ( {\n maskImage: { type: String, default: ''},\n width: { type: Number, default: 100 }\n})\n\nconst width = computed(()=> props.width + 'px')\nconst maskImage = computed(() => `assets/sprite/svg/${props.maskImage}.svg`)\n\n.box-container\n background-color: blue\n width: v-bind(width)\n -webkit-mask-image: url(v-bind(maskImage))\n -webkit-mask-position: center\n -webkit-mask-repeat: no-repeat\n\n```\n\nWith this code, the computed width is working right, but the mask url isn't. In the inspector I can see that a kind hashed value is seted in mask-image: `-webkit-mask-image: url(var(--20ff1bb8-maskImage))`\n\nHow can I pass the value in the right way?\n\n========================================\n\nCode:\n```text\n<template>\n <div class=\"box-container\"></div>\n</template>\n\n<script lang=\"ts\" setup>\n\nconst props = defineProps ( {\n maskImage: { type: String, default: ''},\n width: { type: Number, default: 100 }\n})\n\n\nconst width = computed(()=> props.width + 'px')\nconst maskImage = computed(() => `assets/sprite/svg/${props.maskImage}.svg`)\n\n</script>\n\n\n<style lang=\"sass\" scoped>\n\n.box-container\n background-color: blue\n width: v-bind(width)\n -webkit-mask-image: url(v-bind(maskImage))\n -webkit-mask-position: center\n -webkit-mask-repeat: no-repeat\n</style>\n```\n\n```text\n-webkit-mask-image: url(var(--20ff1bb8-maskImage))\n```\n\n```js\nconst maskImage = computed(() => 'url(https://mdn.github.io/css-examples/masking/star.svg)');\n```\n\n```text\nurl()\n```\n\n========================================\n\nComments:\n- ¡Thanks! The kind of answer that makes understand many things.","metadata":{"transformedAt":"2026-08-18T18:33:07.885Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":81,"estimatedTokens":457}}674{"id":"stack-54473003","source":"stackoverflow","questionId":54473003,"title":"nuxt.js generate stuck at 'generated'","tags":["vue.js","netlify","nuxt.js"],"text":"Title: nuxt.js generate stuck at 'generated'\nTags: vue.js, netlify, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nThis is my first time building a Nuxt App and I'm trying to deploy it to netlify, now whats happening is I run\n\n`yarn run generate`\n\nI don't get any errors or anything but I get stuck here\n\n```\nBuilt at: 2019-02-01 15:16:38\n Asset Size Chunks Chunk Names\n53deff7cce1c2de4cfa5.js 59 KiB 1 [emitted] pages_index\n server.js 36.9 KiB 0 [emitted] app\n server.manifest.json 243 bytes [emitted]\n + 2 hidden assets\nEntrypoint app = server.js server.js.map\ni Generating pages \n15:16:38\n√ Generated /\n```\n\nand then nothing? \n\nThe same thing happens when I run the command in my terminal, It just stays on generated and nothing happens\n\nMy site is pretty basic and I have not added any other config excpet for the ability to use scss\n\nMy site is never deployed Its been sitting like that for an hour is there something I'm doing wrong??\n\n**EDIT**\n\nFinally something happened\n\n`Build exceeded maximum allowed runtime`\n\nHow can I solve this issue??\n\nAny help would be appreciated!\n\n========================================\n\nTop Answer:\nIn addition to the `setInterval` calls in the accepted answer, this can also happen if you have any other asynchronous code that will get evaluated at build time. For me that was an `await` inside one of my plugin files, that wasn't ever getting completed.\n\nWrapping it in an `if (process.client) {}` to make sure it doesn't run at build time fixed it for me.\n\n========================================\n\nCode:\n```text\nBuilt at: 2019-02-01 15:16:38\n Asset Size Chunks Chunk Names\n53deff7cce1c2de4cfa5.js 59 KiB 1 [emitted] pages_index\n server.js 36.9 KiB 0 [emitted] app\n server.manifest.json 243 bytes [emitted]\n + 2 hidden assets\nEntrypoint app = server.js server.js.map\ni Generating pages \n15:16:38\n√ Generated /\n```\n\n```text\nyarn run generate\n```\n\n```text\nBuild exceeded maximum allowed runtime\n```\n\n```text\nsetInterval\n```\n\n```text\nif (process.client) { /* ... */ }\n```\n\n```text\nsetInterval\n```\n\n```text\ngenerate\n```\n\n```text\nsetInterval\n```\n\n```text\nawait\n```\n\n```text\nif (process.client) {}\n```\n\n========================================\n\nComments:\n- ...omg I do have a setInterval call in two of my components! Is there anyway around this whilst still keeping the intervals?\n- the main thing to keep in mind is that Netlify's CD environment needs your build process to not only finish (return you to the prompt) but also and harder to debug ALL PROCESSES STARTED DURING BUILD MUST EXIT! Processes like a browser-sync that would watch the build directory and reload a page in your browser don't make sense in Netlify's build env - but you can run them, and they can block Netlify's system from realizing your build is finished. So - that's the goal - all processes exit, and the main one exits with status 0 so Netlify knows the build was a success.\n- @SmokeyDawson yeah, I just edited the answer! Just use `process.client` to ensure that the intervals are only ran on the client side.\n- Does that apply to `setTimeout` too? I do not have `setInterval` anywhere in my code but I do have `setTimeout`. I am stuck with Building Nitro Server.\n- @JovanniG I guess... I suggest doing a quick test by removing your timeouts and trying to build it.\n- I confirm that setTimeout are also causing the issue.\n- It also occurs if you use a `BroadcastChannel` anywhere without `if(process.client) {...}` wrapping it.","metadata":{"transformedAt":"2026-08-18T18:33:07.886Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":111,"estimatedTokens":900}}675{"id":"stack-75115935","source":"stackoverflow","questionId":75115935,"title":"How to disable the default routing and specify manual one in Nuxt 3?","tags":["nuxt.js"],"text":"Title: How to disable the default routing and specify manual one in Nuxt 3?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nFirst of all, please don't waste your time to overpersuade mе to use Nuxt default directory-based routing: I need the manual routing and that's it.\n\nNo updates in \"Vue router 4 support\" issue of @nuxtjs/router since May 30, 2022 - looks like no way except dealing with manual routing myself if I need it.\n\nI have checked the source code of **@nuxtjs/router** - the is no much code, but I have not understood where the manual routing has been set to Nuxt.\n\nIt is required to do 2 things:\n\n- Disable the default routing\n\n- Set the new routing\n\nFor the Nuxt 2.X, the disabling part was\n\n```\nif (!options.parsePages) {\n this.nuxt.hook('build:before', () => {\n this.nuxt.options.build.createRoutes = () => {\n return []\n }\n })\n}\n```\n\nIn the Nuxt 3.X case, there is no `createRoutes` property anymore.\n\nThen, how I can to specify the new routing?\nThere is the dedicated property?\n\nWe can start with inline plugin definition:\n\n```\nimport { defineNuxtConfig, NuxtConfig } from \"nuxt/config\";\n\nexport default defineNuxtConfig({\n // ...\n modules: [\n async (inlineOptions: unknown, nuxt: NuxtConfig) => {\n\n }\n ]\n});\n```\n\nBy the way, if to try to use the current **@nuxtjs/router** for Nuxt 3, it will be this error.\n\n========================================\n\nTop Answer:\nin Nuxt3, you can use RouterConfig for activating manual routing, these steps:\n\n- create ./app/router.options.ts file\n\n- create ./pages/login.vue file for testing\n\n- insert this code on ./app/router.options.ts:\n\n```\nimport type { RouterConfig } from '@nuxt/schema'\n\nexport default {\n routes: (_routes) => [\n {\n name: 'login',\n path: '/login',\n component: () => import('~/pages/login.vue'),\n }\n ],\n}\n```\n\nnow you can access http://localhost:3000/login using manual routing.\n\n========================================\n\nCode:\n```text\nif (!options.parsePages) {\n this.nuxt.hook('build:before', () => {\n this.nuxt.options.build.createRoutes = () => {\n return []\n }\n })\n}\n```\n\n```js\nimport { defineNuxtConfig, NuxtConfig } from \"nuxt/config\";\n\n\nexport default defineNuxtConfig({\n // ...\n modules: [\n async (inlineOptions: unknown, nuxt: NuxtConfig) => {\n\n }\n ]\n});\n```\n\n```text\ncreateRoutes\n```\n\n```text\nrouter.options.ts\n```\n\n```text\n/app\n```\n\n```js\nimport type { RouterConfig } from '@nuxt/schema'\n\nexport default <RouterConfig>{\n routes: (_routes) => [\n {\n name: 'login',\n path: '/login',\n component: () => import('~/pages/login.vue'),\n }\n ],\n}\n```\n\n```text\napp/router.options.ts\n```\n\n```text\n<NuxtPage />\n```\n\n```text\napp.vue\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.886Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":142,"estimatedTokens":664}}676{"id":"stack-73352670","source":"stackoverflow","questionId":73352670,"title":"How to fetch folder structure from Nuxt content?","tags":["vue.js","nuxt.js","nuxt-content"],"text":"Title: How to fetch folder structure from Nuxt content?\nTags: vue.js, nuxt.js, nuxt-content\nSource: Stack Overflow\n\nQuestion:\nI'm trying to fetch my content structure to display the list on the homepage:\nmy folder is like that :\n\n```\ncontent /\n-- | A /\n---- | an_article.md\n-- | B /\n---- | another_one.md\n-- | C /\n---- | etc.md\n```\n\nAnd I would like to use these folders as categories for my website. So later **they are displayed as a list (A, B, C) on the homepage**. I know I can fetch articles but I don't know for folders...\n\nHere is an exemple on how it looks in html, css, jquery. It will look something like that:\n\n\r\n\r\n\n```\n$('.sub-menu ul').hide();\n$(\".sub-menu a\").click(function () {\nevent.preventDefault();\n $(this).parent(\".sub-menu\").children(\"ul\").slideToggle(200);\n $(this).parent('.sub-menu').siblings().find('ul').slideUp(200);\n});\n```\n\n\r\n\n```\nbody {\n font-size: 1em;\n font-family: arial;\n}\na {\n text-decoration: none;\n}\n\n.menu {\n width: 50%;\n}\nul {\n list-style-type: none;\n margin: 0;\n padding: 0;\n}\n\nli {\n}\n\nli:not(.sub-menu):last-child {\n\n}\n\n.sub-menu li {\n border-top: 1px solid black;\n}\n\nli.sub-menu {\n margin-left: 20px;\n}\n```\n\n\r\n\n```\n\n \n A\n\n \n \n \n\n Project related to A\n \n \n B\n\n \n \n \n\n Another project related to B\n \n \n C\n\n \n \n \n\n Again another project related to C\n \n \n \n\n```\n\n\r\n\r\n\r\n\nThis is what I use so far to fetch the articles published.\n\n```\nexport default {\n async asyncData ({ $content, params }) {\n const articles = await $content('A', params.slug)\n .only(['title', 'description', 'img', 'slug'])\n .sortBy('createdAt', 'asc')\n .fetch()\n\n return {\n articles\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\ncontent /\n-- | A /\n---- | an_article.md\n-- | B /\n---- | another_one.md\n-- | C /\n---- | etc.md\n```\n\n```js\n$('.sub-menu ul').hide();\n$(\".sub-menu a\").click(function () {\nevent.preventDefault();\n $(this).parent(\".sub-menu\").children(\"ul\").slideToggle(200);\n $(this).parent('.sub-menu').siblings().find('ul').slideUp(200);\n});\n```\n\n```css\nbody {\n font-size: 1em;\n font-family: arial;\n}\na {\n text-decoration: none;\n}\n\n.menu {\n width: 50%;\n}\nul {\n list-style-type: none;\n margin: 0;\n padding: 0;\n}\n\nli {\n}\n\nli:not(.sub-menu):last-child {\n\n}\n\n.sub-menu li {\n border-top: 1px solid black;\n}\n\nli.sub-menu {\n margin-left: 20px;\n}\n```\n\n```html\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<body>\n <ul class=\"menu\">\n <li class='sub-menu'> <a href='#'>A</a>\n\n <ul>\n <li class='sub-menu'>\n <img src=\"https://picsum.photos/200/100\" alt=\"\"> <br>\n <a href='#'>Project related to A</a>\n </ul>\n </li>\n <li class='sub-menu'> <a href='#'>B</a>\n\n <ul>\n <li class='sub-menu'>\n <img src=\"https://picsum.photos/200/200\" alt=\"\"> <br>\n <a href='#'>Another project related to B</a>\n </ul>\n </li>\n <li class='sub-menu'> <a href='#'>C</a>\n\n <ul>\n <li class='sub-menu'> \n <img src=\"https://picsum.photos/210/200\" alt=\"\"> <br>\n <a href='#'>Again another project related to C</a>\n </ul>\n </li>\n </ul>\n</body>\n```\n\n```js\nexport default {\n async asyncData ({ $content, params }) {\n const articles = await $content('A', params.slug)\n .only(['title', 'description', 'img', 'slug'])\n .sortBy('createdAt', 'asc')\n .fetch()\n\n return {\n articles\n }\n }\n}\n```\n\n```html\n<template>\n <div class=\"container\">\n <div v-for=\"(filteredArticles, categoryKey) in groupedCategories\" :key=\"categoryKey\">\n <h2>{{ categoryKey }}</h2>\n <list-item v-for=\"article in filteredArticles\" :key=\"article.slug\">\n <template #title>\n {{ article.title }}\n </template>\n <template #content>\n <div> {{ article.description }}</div>\n </template>\n <br>\n </list-item>\n <hr>\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n async asyncData ({ $content }) {\n const articles = await $content('', { deep: true })\n .only(['title', 'description', 'img', 'slug', 'cat', 'dir'])\n .sortBy('createdAt', 'asc')\n .fetch()\n\n return { articles }\n },\n computed: {\n groupedCategories () {\n return this.articles.reduce((finalObject, obj) => {\n const directory = obj.dir\n finalObject[directory] ?? (finalObject[directory] = [])\n finalObject[directory].push(obj)\n return finalObject\n }, {})\n }\n }\n}\n</script>\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.886Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":272,"estimatedTokens":1117}}677{"id":"stack-72836661","source":"stackoverflow","questionId":72836661,"title":"TypeError: _this.$content is not a function - Nuxt.js Content","tags":["javascript","typescript","vue.js","nuxt.js"],"text":"Title: TypeError: _this.$content is not a function - Nuxt.js Content\nTags: javascript, typescript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to use Nuxt.js Content in my project.\nThe problem is that when I try to use $content method in my project the `TypeError: _this.$content is not a function` occurs:\n\n```\nasync fetch() {\n this.content = await this.$content('data').fetch()\n},\n```\n\nI imported the `@nuxt/content` in Nuxt config and in typescript config.\n\n`nuxt.config.js`\n\n```\nexport default {\n modules: ['@nuxt/content']\n}\n```\n\n`tsconfig.json`\n\n```\n{\n \"compilerOptions\": {\n \"types\": [\"@nuxt/types\", \"@types/node\", \"@nuxt/content\"]\n }\n}\n```\n\n========================================\n\nCode:\n```js\nasync fetch() {\n this.content = await this.$content('data').fetch()\n},\n```\n\n```js\nexport default {\n modules: ['@nuxt/content']\n}\n```\n\n```json\n{\n \"compilerOptions\": {\n \"types\": [\"@nuxt/types\", \"@types/node\", \"@nuxt/content\"]\n }\n}\n```\n\n```text\nTypeError: _this.$content is not a function\n```\n\n```text\n@nuxt/content\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- Which version of content do you use? The latest requires Nuxt3.\n- @kissu I officially love you man. It is working now after changing to ^1. Thank you very much <333","metadata":{"transformedAt":"2026-08-18T18:33:07.886Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":78,"estimatedTokens":330}}678{"id":"stack-69076488","source":"stackoverflow","questionId":69076488,"title":"How to rename a namespaced mapGetter in Vuex?","tags":["vue.js","vuejs2","nuxt.js","vuex"],"text":"Title: How to rename a namespaced mapGetter in Vuex?\nTags: vue.js, vuejs2, nuxt.js, vuex\nSource: Stack Overflow\n\nQuestion:\nIn my `nuxt` project I'm trying to use `mapGetters` with the rename object syntax as described in the docs. Getters are namespaced in a module called `currentTournament`.\n\nThis is the computed property inside a mixin:\n\n```\ncomputed: {\n ...mapGetters('currentTournament', [{ tAllowedBaskets: 'allowedBaskets' }]),\n}\n```\n\nIf I log component's `this`, instead of the `tAllowedBaskets` property a new property appears `[object Object]: undefined`. However, if I use the 'simple' string syntax:\n\n```\n...mapGetters('currentTournament', ['allowedBaskets'])\n```\n\n`allowedBaskets` property appears correctly.\n\nWhy can the object syntax be not working?\n\n========================================\n\nCode:\n```js\ncomputed: {\n ...mapGetters('currentTournament', [{ tAllowedBaskets: 'allowedBaskets' }]),\n}\n```\n\n```js\n...mapGetters('currentTournament', ['allowedBaskets'])\n```\n\n```text\nnuxt\n```\n\n```text\nmapGetters\n```\n\n```text\ncurrentTournament\n```\n\n```text\nthis\n```\n\n```text\ntAllowedBaskets\n```\n\n```text\n[object Object]: undefined\n```\n\n```text\nallowedBaskets\n```\n\n```js\n...mapGetters('currentTournament', { tAllowedBaskets: 'allowedBaskets' }),\n```\n\n```text\n[]\n```\n\n========================================\n\nComments:\n- Thanks, but what if I'd like to map multiple getters at once? I put only one getter in the example to keep it simple. Does the array syntax not support the object syntax?\n- Never saw it and I doubt it does (may be wrong but nothing related in the documentation). I'd still recommend to write one per line for clarity reasons and simpler more understandable code @Eggon","metadata":{"transformedAt":"2026-08-18T18:33:07.886Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":79,"estimatedTokens":425}}679{"id":"stack-69937776","source":"stackoverflow","questionId":69937776,"title":"V-Binding Booleans with Radio Buttons","tags":["vue.js","nuxt.js","vuetify.js","vue-composition-api"],"text":"Title: V-Binding Booleans with Radio Buttons\nTags: vue.js, nuxt.js, vuetify.js, vue-composition-api\nSource: Stack Overflow\n\nQuestion:\nI was trying to set the value of a radio button as a boolean and store this value, but when I did, it didn't seem to work.\n\n```\n\n \n \n\n```\n\nI finally was able to get it to work when using V-Binding for the `value`:\n\n```\n\n \n \n\n```\n\nCan someone explain why this is the case? I feel like I am missing something in the documentation: https://v2.vuejs.org/v2/guide/forms.html#Radio-1\n\nWe are using the composition API, Nuxt framework, and Vuetify (not sure if that matters)\n\n========================================\n\nCode:\n```html\n<v-radio-group v-model=\"test\" class=\"pl-2\">\n <v-radio\n label=\"Yes\"\n value=\"true\"\n >\n </v-radio>\n</v-radio-group>\n```\n\n```html\n<v-radio-group v-model=\"test\" class=\"pl-2\">\n <v-radio\n label=\"Yes\"\n :value=\"true\"\n >\n </v-radio>\n</v-radio-group>\n```\n\n```text\nvalue\n```\n\n```html\n<v-radio value=\"true\">\n```\n\n```html\n<v-radio :value=\"true\">\n```\n\n```text\nvalue\n```\n\n```text\n\"true\"\n```\n\n```text\nv-bind\n```\n\n```text\ntrue\n```\n\n```text\nBoolean\n```\n\n```text\nvalue\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.886Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":85,"estimatedTokens":284}}680{"id":"stack-72787826","source":"stackoverflow","questionId":72787826,"title":"Typescript Element implicitly has an 'any' type because expression of type 'number' can't be used to index","tags":["javascript","nuxt.js"],"text":"Title: Typescript Element implicitly has an 'any' type because expression of type 'number' can't be used to index\nTags: javascript, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nMy work environment is\nNuxt.js Vue works with some typescript.\n\nThis problem occurs when for looping inside methods.\n\nI refer to the _id in Objects\nreservatsions[i].I got the result from the _id\n\n```\nmethods: {\nasync tripdone() {\n try {\n const legnth = this.myObject.length;\n for (let i = 0; i Vetur's errors in the current syntax are as follows:\n\n`(property) reservations: ObjectConstructor`\n\nElement implicitly has an 'any' type because expression of type 'number' can't be used to index type 'ObjectConstructor'.\nNo index signature with a parameter of type 'number' was found on type 'ObjectConstructor'.Vetur(7053)\n\nI don't know what type of error this is\nI tried to understand it while looking at the `typescript`, but I couldn't solve it.\n\nThe syntax for the error is as follows\n\nconst status = this.myObject[i].status; // string\n\nconst tripDate = this.myObject[i].date; // string\n\nconst id = this.myObject[i]._id; // number\n\nIn dev build, ERROR is generated, but the result was calculated and the desired result was obtained\nAt pm2 start,\n\n```\nERROR in index/myObject/index.vue:360:26\nTS7053: Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'ObjectConstructor'.\n No index signature with a parameter of type 'number' was found on type 'ObjectConstructor'.\n 358 | const legnth = this.myObject.length\n 359 | for (let i = 0; i 360 | const status = this.myObject[i].status\n | ^^^^^^^^^^^^^^^^^^^^\n 361 | // const legnth = this.myObject.length\n 362 | // for (let t = 0; t 363 | const tripDate = this.myObject[i].date\n | ^^^^^^^^^^^^^^^^^^^^\n 364 | const today = new Date()\n 365 |\n 366 | var year = today.getFullYear();\n\nERROR in index/myObject/index.vue:377:24\nTS7053: Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'ObjectConstructor'.\n No index signature with a parameter of type 'number' was found on type 'ObjectConstructor'.\n 375 | // return tripDate 377 | const id = this.myObject[i]._id\n | ^^^^^^^^^^^^^^^^^^^^\n 378 | const payload = {\n 379 | status: \"tripOver\"\n 380 | }\n```\n\nI seek advice on the reasons and solutions for this phenomenon\n\nadd myOject define below\n\n```\ndata () {\n return{\n myObject: Object \n }\n }\n```\n\n========================================\n\nCode:\n```text\nmethods: {\nasync tripdone() {\n try {\n const legnth = this.myObject.length;\n for (let i = 0; i < legnth; i++) {\n const status = this.myObject[i].status;\n\n const tripDate = this.myObject[i].date;\n const today = new Date();\n\n var year = today.getFullYear();\n var month = (\"0\" + (today.getMonth() + 1)).slice(-2);\n var day = (\"0\" + today.getDate()).slice(-2);\n\n var todayString = year + \"-\" + month + \"-\" + day;\n\n if (tripDate < todayString && status === \"confirmed\") {\n const id = this.myObject[i]._id;\n const payload = {\n status: \"tripOver\",\n };\n\n this.$axios.put(`/api/myObject/${id}`, payload);\n const message = id;\n const type = \"success\";\n this.$message({ message, type });\n }\n }\n } catch (e) {\n const message = \"error\";\n const type = \"error\";\n this.$message({ message, type });\n }\n}\n```\n\n```text\nERROR in index/myObject/index.vue:360:26\nTS7053: Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'ObjectConstructor'.\n No index signature with a parameter of type 'number' was found on type 'ObjectConstructor'.\n 358 | const legnth = this.myObject.length\n 359 | for (let i = 0; i < legnth; i++) {\n > 360 | const status = this.myObject[i].status\n | ^^^^^^^^^^^^^^^^^^^^\n 361 | // const legnth = this.myObject.length\n 362 | // for (let t = 0; t < legnth; t++) {\n 363 | const tripDate = this.myObject[i].date\n\nERROR in index/myObject/index.vue:363:28\nTS7053: Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'ObjectConstructor'.\n No index signature with a parameter of type 'number' was found on type 'ObjectConstructor'.\n 361 | // const legnth = this.myObject.length\n 362 | // for (let t = 0; t < legnth; t++) {\n > 363 | const tripDate = this.myObject[i].date\n | ^^^^^^^^^^^^^^^^^^^^\n 364 | const today = new Date()\n 365 |\n 366 | var year = today.getFullYear();\n\nERROR in index/myObject/index.vue:377:24\nTS7053: Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'ObjectConstructor'.\n No index signature with a parameter of type 'number' was found on type 'ObjectConstructor'.\n 375 | // return tripDate < todayString\n 376 | if ( tripDate < todayString && status ==='confirmed') {\n > 377 | const id = this.myObject[i]._id\n | ^^^^^^^^^^^^^^^^^^^^\n 378 | const payload = {\n 379 | status: \"tripOver\"\n 380 | }\n```\n\n```text\ndata () {\n return{\n myObject: Object \n }\n }\n```\n\n```text\n(property) reservations: ObjectConstructor\n```\n\n```text\ntypescript\n```\n\n```text\n(this.myobject as YourType)[i]._id;\n```\n\n```text\n(this.myobject as any)[i]._id;\n```\n\n```text\nany\n```\n\n```text\nany\n```\n\n========================================\n\nComments:\n- You can put your type inline `(this.myobject as YourType)[i]._id;`\n- It causes other errors. Conversion of type 'ObjectConstructor' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.Vetur(2352)\n- Saved by day! Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:07.886Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":188,"estimatedTokens":1485}}681{"id":"stack-72077976","source":"stackoverflow","questionId":72077976,"title":"How to build vue component library with vite and tailwind? (tailwind classes not working when importing to other project)","tags":["vue.js","nuxt.js","tailwind-css","vite"],"text":"Title: How to build vue component library with vite and tailwind? (tailwind classes not working when importing to other project)\nTags: vue.js, nuxt.js, tailwind-css, vite\nSource: Stack Overflow\n\nQuestion:\n### Current\n\nI have two repositories:\n\n- Main Web App - simple nuxt3 web app\n\n- Component Library - simple vite/vue app\n\n### Goal\n\nBuild my own component library using vite, vue3 and tailwindcss\n\n### Problem\n\nWhen I use `npm run dev` I can se my components working fine (from the vite app) but when I build my library `npm run build:watch` and import them in another project (nuxt app) tailwind classes/styles are not working\n\nThis is mi vite app (all good)\n\nThis is the nuxt app where I imported the component (no style)\n\nRepositories:\n\n- Main Web App: https://github.com/fro-systems/clau-web\n\n- Component Library: https://github.com/fro-systems/clau-components\n\n========================================\n\nCode:\n```text\nnpm run dev\n```\n\n```text\nnpm run build:watch\n```\n\n```text\n\"exports\": {\n \"./dist/style.css\": \"./dist/style.css\"\n },\n```\n\n```text\ncss: [\n \"clau-components/dist/style.css\"\n],\n```\n\n```text\npackage.json\n```\n\n```text\nnuxt.config.ts\n```\n\n========================================\n\nComments:\n- Can I ask if there is a way to fix this **without explicitly importing css in the host project** (in this case, `nuxt.config.ts`)? Cos if we have a lot of custom libraries then importing the bundled css is going to need a lot of manual work. Pls advice if I should post a separate qn\n- Were you are to resolve this without an explicit import to the host project?","metadata":{"transformedAt":"2026-08-18T18:33:07.886Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":67,"estimatedTokens":395}}682{"id":"stack-71980035","source":"stackoverflow","questionId":71980035,"title":"How to create 404 page on dynamic routes Nuxt js Fetch method","tags":["vue.js","nuxt.js"],"text":"Title: How to create 404 page on dynamic routes Nuxt js Fetch method\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI've dynamic route `http://localhost:3000/sections/slug-name`. I want to display or redirect to the 404 page if the URL is invalid. trying to do something like this but with the fetch method.\n\nI know we can do `404 Invalid Section\n\n` but is there any better way to show 404 page.\n\nfollowing is my code for your reference\n\n```\n\nexport default {\n data() {\n return {\n posts: {},\n loader: false,\n }\n },\n head() {\n return {\n title: this.posts.category_name ,\n\n }\n },\n \n\n methods: {\n getResults(page = 1) {\n if (this.$route.query.page != page) {\n this.$router.push({\n query: {\n page: page,\n },\n })\n }\n },\n\n loadPosts(page) {\n this.loader = true\n this.$axios\n .$get(`category/${this.$route.params.category}?page=${page}`)\n .then((response) => {\n this.posts = response\n this.loader = false\n })\n },\n },\n watch: {\n $route(to, from) {\n this.loadPosts(to.query.page)\n },\n },\n async fetch() {\n let page = this.$route.query.page ? this.$route.query.page : 1\n this.posts = await this.$axios\n .$get(`category/${this.$route.params.category}?page=${page}`)\n .catch((e) => {\n this.$router.push({ name: 'fallback-page' })\n })\n },\n}\n\n```\n\n========================================\n\nTop Answer:\nyou must use `error({ statusCode: 404})` in `catch` of fetch or asyncData method to redirect client to 404 page\n\n========================================\n\nCode:\n```html\n<script>\nexport default {\n data() {\n return {\n posts: {},\n loader: false,\n }\n },\n head() {\n return {\n title: this.posts.category_name ,\n\n }\n },\n \n\n methods: {\n getResults(page = 1) {\n if (this.$route.query.page != page) {\n this.$router.push({\n query: {\n page: page,\n },\n })\n }\n },\n\n loadPosts(page) {\n this.loader = true\n this.$axios\n .$get(`category/${this.$route.params.category}?page=${page}`)\n .then((response) => {\n this.posts = response\n this.loader = false\n })\n },\n },\n watch: {\n $route(to, from) {\n this.loadPosts(to.query.page)\n },\n },\n async fetch() {\n let page = this.$route.query.page ? this.$route.query.page : 1\n this.posts = await this.$axios\n .$get(`category/${this.$route.params.category}?page=${page}`)\n .catch((e) => {\n this.$router.push({ name: 'fallback-page' })\n })\n },\n}\n</script>\n```\n\n```text\nhttp://localhost:3000/sections/slug-name\n```\n\n```text\n<p v-if=\"$fetchState.error\">404 Invalid Section</p>\n```\n\n```js\nthis.$nuxt.context.error({\n status: 500,\n message: 'Something bad happened',\n})\n```\n\n```js\nexport default {\n generate: {\n fallback: '404.html',\n },\n}\n```\n\n```html\n<template>\n <p>some error here {{ error }}</p>\n</template>\n\n<script>\nexport default {\n props: ['error'],\n}\n</script>\n```\n\n```js\n.catch((e) => { this.$router.push({ name: 'fallback-page' }) })\n```\n\n```text\nfetch()\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n/layouts/error.vue\n```\n\n```text\n/hello-word\n```\n\n```text\ncatch\n```\n\n```text\nerror({ statusCode: 404})\n```\n\n```text\ncatch\n```\n\n========================================\n\nComments:\n- client.js?06a0:56 Error in fetch(): ReferenceError: error is not defined\n- Put the codes you wrote to guide you exactly\n- I've updated the question with the code\n- It should be `throw createError({ statusCode: 404 });`\n- hey, I cant use `$router.push` because I'm using the fetch method, it seems to be rendering component first that's why I'm getting `Cannot read property 'category_name' of undefined`\n- @KunalRajput this is some other issue. Your template is sync, if you have something like `object.category_name` but `object` is async, it will throw this error. Nothing related to a 404. Wrap your template into a `$fetchState.pending` while your API call is done, then display the rest of your template.\n- yeah in the head() I'm using `title: this.post.category_name` , how can I use `fetchState.pending` in the head method\n- @KunalRajput I've updated my initial answer with what you were looking for (regarding the `fetch()` hook). Meanwhile, regarding the SEO thing, this is a totally unrelated question. I've answered something similar here.\n- I'm not using SSG, I end up using asynData for this and it worked. Thanks for rescuing me again\n- can you update your old answer `this.$router.push({ name: 'fallback-page' })` will work if I am not using head method,if I click on a link which does not exist it will redirect me to the 404 page `Click here`\n- Not sure what you mean, mind suggesting an edit? @KunalRajput\n- `.catch((e) => { this.$router.push({ name: 'fallback-page' }) })` this code works like a charge if I like with the internal links in my nuxt application and page does not exist , So I was suggesting to put this catch code in the original answer","metadata":{"transformedAt":"2026-08-18T18:33:07.886Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":213,"estimatedTokens":1217}}683{"id":"stack-72609269","source":"stackoverflow","questionId":72609269,"title":"Using vue-chartjs (4.1.1) in Nuxt (3.0.0-rc.4) doesn't build | How can I use a simple pie chart in a nuxt project?","tags":["vue.js","nuxt.js","pie-chart","es6-modules","vue-chartjs"],"text":"Title: Using vue-chartjs (4.1.1) in Nuxt (3.0.0-rc.4) doesn't build | How can I use a simple pie chart in a nuxt project?\nTags: vue.js, nuxt.js, pie-chart, es6-modules, vue-chartjs\nSource: Stack Overflow\n\nQuestion:\nI want to use a reactive pie chart for my Nuxt app. For simplicity I thought chart.js is the most productive and easiest way to get fast results. Now I am stuck for a couple of days. GitHub repos and other stackoverflow posts relate to older releases than mine.\n\nThis is a minimal version of my app to reproduce the error I am trying to fix.\n\n```\n# installation\nnpx nuxi init repro-chartjs\ncd repro-chartjs\nyarn add vue-chartjs chart.js\nyarn install\n```\n\nOpen the project in an editor and add the pieChart.ts code from the official examples as a component into the project, e.g. components/pieChart.ts.\n\n```\nimport { defineComponent, h, PropType } from 'vue'\n\nimport { Pie } from 'vue-chartjs'\nimport {\n Chart as ChartJS,\n Title,\n Tooltip,\n Legend,\n ArcElement,\n CategoryScale,\n Plugin\n} from 'chart.js'\n\nChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale)\n\nexport default defineComponent({\n name: 'PieChart',\n components: {\n Pie\n },\n props: {\n chartId: {\n type: String,\n default: 'pie-chart'\n },\n width: {\n type: Number,\n default: 400\n },\n height: {\n type: Number,\n default: 400\n },\n cssClasses: {\n default: '',\n type: String\n },\n styles: {\n type: Object as PropType>,\n default: () => {}\n },\n plugins: {\n type: Array as PropType[]>,\n default: () => []\n }\n },\n setup(props) {\n const chartData = {\n labels: ['VueJs', 'EmberJs', 'ReactJs', 'AngularJs'],\n datasets: [\n {\n backgroundColor: ['#41B883', '#E46651', '#00D8FF', '#DD1B16'],\n data: [40, 20, 80, 10]\n }\n ]\n }\n\n const chartOptions = {\n responsive: true,\n maintainAspectRatio: false\n }\n\n return () =>\n h(Pie, {\n chartData,\n chartOptions,\n chartId: props.chartId,\n width: props.width,\n height: props.height,\n cssClasses: props.cssClasses,\n styles: props.styles,\n plugins: props.plugins\n })\n }\n})\n```\n\nUse the PieChart component in app.vue.\n\n```\n\n \n \n \n\nimport PieChart from './components/pieChart'\n\n```\n\nRun the code.\n\n```\n# dev build works\nyarn dev -o\n\n# production build doesn't work\nyarn build\nyarn preview\n```\n\nAs commented, the development build runs perfectly fine. But as soon as I try to test the production build, the terminal repeatedly throws me that error:\n\n```\n[nuxt] [request error] Named export 'ArcElement' not found. The requested module 'chart.js' is a CommonJS module, which may not support all module.exports as named exports.\nCommonJS modules can always be imported via the default export, for example using:\n\nimport pkg from 'chart.js';\nconst { Chart, Title: Title$1, Tooltip, Legend, ArcElement, CategoryScale } = pkg;\n\n at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)\n at async ModuleJob.run (node:internal/modules/esm/module_job:181:5)\n at async Promise.all (index 0)\n at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n at async /C:/Users/panda/.00_Web-Dev/00%20Portfolio/repro-chartjs/.output/server/chunks/renderer.mjs:11158:24\n at async /C:/Users/panda/.00_Web-Dev/00%20Portfolio/repro-chartjs/.output/server/chunks/renderer.mjs:11213:64\n at async /C:/Users/panda/.00_Web-Dev/00%20Portfolio/repro-chartjs/.output/server/node_modules/h3/dist/index.mjs:420:19\n\n at async nodeHandler (/C:/Users/panda/.00_Web-Dev/00%20Portfolio/repro-chartjs/.output/server/node_modules/h3/dist/index.mjs:370:7)\n at async ufetch (/C:/Users/panda/.00_Web-Dev/00%20Portfolio/repro-chartjs/.output/server/node_modules/unenv/runtime/fetch/index.mjs:9:17)\n at async $fetchRaw2 (/C:/Users/panda/.00_Web-Dev/00%20Portfolio/repro-chartjs/.output/server/node_modules/ohmyfetch/dist/chunks/fetch.mjs:131:20)\n```\n\nIs it possible to have a working pie chart? In my app the pie chart is fed with props and reacts nicely to user inputs. I just can't deploy it for some reason, since the build doesn't work.\n\nMy package.json:\n\n```\n{\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\"\n },\n \"devDependencies\": {\n \"nuxt\": \"3.0.0-rc.4\"\n },\n \"dependencies\": {\n \"chart.js\": \"^3.8.0\",\n \"vue-chartjs\": \"^4.1.1\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nGenerates fine for me\n\nPackage.json\n\n```\n{\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\"\n },\n \"devDependencies\": {\n \"nuxt\": \"3.0.0-rc.4\",\n \"sass\": \"^1.53.0\",\n \"sass-loader\": \"^13.0.2\",\n \"vite-svg-loader\": \"^3.4.0\",\n \"webpack\": \"^5.73.0\"\n },\n \"dependencies\": {\n \"@pinia/nuxt\": \"^0.3.1\",\n \"chart.js\": \"^3.9.1\",\n \"chartjs-plugin-datalabels\": \"^2.1.0\",\n \"vue-chart-3\": \"^3.1.8\",\n \"vue-chartjs\": \"^4.1.1\"\n }\n}\n```\n\nMy nuxt.config.js file\n\n```\nimport { defineNuxtConfig } from 'nuxt'\nimport svgLoader from 'vite-svg-loader'\n\n// https://v3.nuxtjs.org/api/configuration/nuxt.config\nexport default defineNuxtConfig({\n vite: {\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: `\n @import \"@/assets/styles.scss\";\n @import \"@/assets/functions.scss\";\n @import \"@/assets/variables.scss\";\n @import \"@/assets/neumorphism.scss\";\n @import \"@/assets/components.scss\";\n `,\n },\n },\n },\n plugins: [\n svgLoader({})\n ],\n },\n typescript: {\n shim: false\n },\n modules: [\n '@pinia/nuxt',\n ],\n build: {\n transpile: ['chart.js']\n }\n})\n```\n\n========================================\n\nCode:\n```bash\n# installation\nnpx nuxi init repro-chartjs\ncd repro-chartjs\nyarn add vue-chartjs chart.js\nyarn install\n```\n\n```js\nimport { defineComponent, h, PropType } from 'vue'\n\nimport { Pie } from 'vue-chartjs'\nimport {\n Chart as ChartJS,\n Title,\n Tooltip,\n Legend,\n ArcElement,\n CategoryScale,\n Plugin\n} from 'chart.js'\n\nChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale)\n\nexport default defineComponent({\n name: 'PieChart',\n components: {\n Pie\n },\n props: {\n chartId: {\n type: String,\n default: 'pie-chart'\n },\n width: {\n type: Number,\n default: 400\n },\n height: {\n type: Number,\n default: 400\n },\n cssClasses: {\n default: '',\n type: String\n },\n styles: {\n type: Object as PropType<Partial<CSSStyleDeclaration>>,\n default: () => {}\n },\n plugins: {\n type: Array as PropType<Plugin<'pie'>[]>,\n default: () => []\n }\n },\n setup(props) {\n const chartData = {\n labels: ['VueJs', 'EmberJs', 'ReactJs', 'AngularJs'],\n datasets: [\n {\n backgroundColor: ['#41B883', '#E46651', '#00D8FF', '#DD1B16'],\n data: [40, 20, 80, 10]\n }\n ]\n }\n\n const chartOptions = {\n responsive: true,\n maintainAspectRatio: false\n }\n\n return () =>\n h(Pie, {\n chartData,\n chartOptions,\n chartId: props.chartId,\n width: props.width,\n height: props.height,\n cssClasses: props.cssClasses,\n styles: props.styles,\n plugins: props.plugins\n })\n }\n})\n```\n\n```html\n<template>\n <div>\n <PieChart />\n </div>\n</template>\n\n<script setup>\nimport PieChart from './components/pieChart'\n</script>\n```\n\n```bash\n# dev build works\nyarn dev -o\n\n# production build doesn't work\nyarn build\nyarn preview\n```\n\n```bash\n[nuxt] [request error] Named export 'ArcElement' not found. The requested module 'chart.js' is a CommonJS module, which may not support all module.exports as named exports.\nCommonJS modules can always be imported via the default export, for example using:\n\nimport pkg from 'chart.js';\nconst { Chart, Title: Title$1, Tooltip, Legend, ArcElement, CategoryScale } = pkg;\n\n at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)\n at async ModuleJob.run (node:internal/modules/esm/module_job:181:5)\n at async Promise.all (index 0)\n at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n at async /C:/Users/panda/.00_Web-Dev/00%20Portfolio/repro-chartjs/.output/server/chunks/renderer.mjs:11158:24\n at async /C:/Users/panda/.00_Web-Dev/00%20Portfolio/repro-chartjs/.output/server/chunks/renderer.mjs:11213:64\n at async /C:/Users/panda/.00_Web-Dev/00%20Portfolio/repro-chartjs/.output/server/node_modules/h3/dist/index.mjs:420:19\n\n at async nodeHandler (/C:/Users/panda/.00_Web-Dev/00%20Portfolio/repro-chartjs/.output/server/node_modules/h3/dist/index.mjs:370:7)\n at async ufetch (/C:/Users/panda/.00_Web-Dev/00%20Portfolio/repro-chartjs/.output/server/node_modules/unenv/runtime/fetch/index.mjs:9:17)\n at async $fetchRaw2 (/C:/Users/panda/.00_Web-Dev/00%20Portfolio/repro-chartjs/.output/server/node_modules/ohmyfetch/dist/chunks/fetch.mjs:131:20)\n```\n\n```json\n{\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\"\n },\n \"devDependencies\": {\n \"nuxt\": \"3.0.0-rc.4\"\n },\n \"dependencies\": {\n \"chart.js\": \"^3.8.0\",\n \"vue-chartjs\": \"^4.1.1\"\n }\n}\n```\n\n```js\n// nuxt.config.ts\nimport { defineNuxtConfig } from 'nuxt'\n\nexport default defineNuxtConfig({\n build: {\n transpile: ['chart.js']\n }\n})\n```\n\n```text\nbuild.transpile\n```\n\n```text\n{\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\"\n },\n \"devDependencies\": {\n \"nuxt\": \"3.0.0-rc.4\",\n \"sass\": \"^1.53.0\",\n \"sass-loader\": \"^13.0.2\",\n \"vite-svg-loader\": \"^3.4.0\",\n \"webpack\": \"^5.73.0\"\n },\n \"dependencies\": {\n \"@pinia/nuxt\": \"^0.3.1\",\n \"chart.js\": \"^3.9.1\",\n \"chartjs-plugin-datalabels\": \"^2.1.0\",\n \"vue-chart-3\": \"^3.1.8\",\n \"vue-chartjs\": \"^4.1.1\"\n }\n}\n```\n\n```text\nimport { defineNuxtConfig } from 'nuxt'\nimport svgLoader from 'vite-svg-loader'\n\n// https://v3.nuxtjs.org/api/configuration/nuxt.config\nexport default defineNuxtConfig({\n vite: {\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: `\n @import \"@/assets/styles.scss\";\n @import \"@/assets/functions.scss\";\n @import \"@/assets/variables.scss\";\n @import \"@/assets/neumorphism.scss\";\n @import \"@/assets/components.scss\";\n `,\n },\n },\n },\n plugins: [\n svgLoader({})\n ],\n },\n typescript: {\n shim: false\n },\n modules: [\n '@pinia/nuxt',\n ],\n build: {\n transpile: ['chart.js']\n }\n})\n```\n\n========================================\n\nComments:\n- @kissu is the GOAT\n- This still didn't work for me. Using `\"chart.js\": \"^3.9.1\",\"chartjs-plugin-datalabels\": \"^2.1.0\",\"vue-chartjs\": \"^4.1.1\"` with `nuxt3@3.0.0-rc.6-27667279.0b22079`.\n- @Smolikas please put more effort into your comment (and essentially create a real question) than casually listing some package versions. Not gonna help.","metadata":{"transformedAt":"2026-08-18T18:33:07.886Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":468,"estimatedTokens":2723}}684{"id":"stack-55531516","source":"stackoverflow","questionId":55531516,"title":"Package nuxt app in different environment","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: Package nuxt app in different environment\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI would like to run `npm run generate` with environment\n\nfor example: \n\n**package.json**\n\n```\n\"scripts\": {\n \"staging\": \"NODE_ENV=staging nuxt generate\"\n}\n```\n\nGenerate a `dist/` with staging environment using\n\n```\nnpm run staging\n```\n\nthen when requesting to an API I would like to determine what URL I'm going to use depends on the the environment I'm running\n\n```\nlet baseURL = () => {\n switch (process.env.NODE_ENV) {\n case \"it\":\n return \"https://example-url.com/it\";\n case \"staging\":\n return \"https://example-url.com/staging\";\n }\n};\n\nconst axiosClient = axios.create({\n baseURL: baseURL(),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n \"X-Api-Key\": state().token\n }\n});\n```\n\nthe `baseURL()` should return the staging since I packaged the app in staging env\n\n========================================\n\nCode:\n```text\n\"scripts\": {\n \"staging\": \"NODE_ENV=staging nuxt generate\"\n}\n```\n\n```text\nnpm run staging\n```\n\n```text\nlet baseURL = () => {\n switch (process.env.NODE_ENV) {\n case \"it\":\n return \"https://example-url.com/it\";\n case \"staging\":\n return \"https://example-url.com/staging\";\n }\n};\n\nconst axiosClient = axios.create({\n baseURL: baseURL(),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n \"X-Api-Key\": state().token\n }\n});\n```\n\n```text\nnpm run generate\n```\n\n```text\ndist/\n```\n\n```text\nbaseURL()\n```\n\n```text\n\"generate\": \"NUXT_ENV_STAGE=it nuxt generate\",\n```\n\n========================================\n\nComments:\n- so what the problem with your code? Keep in mind that env variables are set build time\n- Works for \"npm run build\" and \"npm run start\" as well.","metadata":{"transformedAt":"2026-08-18T18:33:07.886Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":101,"estimatedTokens":444}}685{"id":"stack-68159486","source":"stackoverflow","questionId":68159486,"title":"Where are the Nuxtjs logs on production?","tags":["vue.js","nuxt.js"],"text":"Title: Where are the Nuxtjs logs on production?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI got an error which only occurred in online prod mode.\n\nhttps://i.sstatic.net/GI0Y8.png\n\nWhere is the `your logs` for prod Nuxt.js?\n\nI checked the document but it didn't mentioned it.\n\n========================================\n\nCode:\n```text\nyour logs\n```\n\n========================================\n\nComments:\n- Thanks a lot! Finally, I figure out that it was caused by wrong nginx configs. But I still wonder if errors occurred in prod mode Nuxt.js, where the errors will be logged?","metadata":{"transformedAt":"2026-08-18T18:33:07.886Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":24,"estimatedTokens":147}}686{"id":"stack-60353759","source":"stackoverflow","questionId":60353759,"title":"How do I resolve Cannot stringify a function error in Nuxt?","tags":["javascript","nuxt.js"],"text":"Title: How do I resolve Cannot stringify a function error in Nuxt?\nTags: javascript, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to the steps in this lesson: https://regenrek.com/posts/create-a-frontmatter-markdown-powered-blog-with-nuxt.js/\n\nAnd I believe I have configured everything correctly, but something about my configuration is not working. I am getting a very uninformative error message:\n\n In the server console\n\n```\nWARN Cannot stringify a function data 15:30:31\n\n WARN Cannot stringify a function render 15:30:31\n\n WARN Cannot stringify a function created 15:30:31\n\n WARN Cannot stringify a function VueComponent\n```\n\n In the client\n\n```\nRangeError\nMaximum call stack size exceeded\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:207:20\nstringifyPrimitive\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:92:20\nstringify\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:98\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:49\nstringify\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:98\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:49\nstringify\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:98\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:49\nstringify\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:98\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:49\nstringify\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:98\n```\n\nI do not understand the source of this error, or how to resolve it. Everything I have in this sandbox matches with the demo sandbox and should work as far as I can tell.\n\nHow do I debug this error? Why does frontmatter-markdown-loader not work for me?\n\n========================================\n\nCode:\n```text\nWARN Cannot stringify a function data 15:30:31\n\n\n WARN Cannot stringify a function render 15:30:31\n\n\n WARN Cannot stringify a function created 15:30:31\n\n\n WARN Cannot stringify a function VueComponent\n```\n\n```text\nRangeError\nMaximum call stack size exceeded\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:207:20\nstringifyPrimitive\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:92:20\nstringify\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:98\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:49\nstringify\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:98\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:49\nstringify\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:98\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:49\nstringify\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:98\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:49\nstringify\nnode_modules/@nuxt/devalue/dist/devalue.cjs.js:129:98\n```\n\n========================================\n\nComments:\n- Anyone wrestling this, search the net for \"nuxt reducers revivers\"; may give you some solutions.","metadata":{"transformedAt":"2026-08-18T18:33:07.886Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":91,"estimatedTokens":712}}687{"id":"stack-63503743","source":"stackoverflow","questionId":63503743,"title":"Resolving @import .css in SCSS from node modules in Nuxt.js vs PhpStorm","tags":["webpack","sass","phpstorm","nuxt.js","node-modules"],"text":"Title: Resolving @import .css in SCSS from node modules in Nuxt.js vs PhpStorm\nTags: webpack, sass, phpstorm, nuxt.js, node-modules\nSource: Stack Overflow\n\nQuestion:\nLets say I'd like to import some stylesheets from a node module in my main `app.scss`:\n\n`@import '~bootstrap/scss/bootstrap';`\n\nThis will be correctly resolved by PhpStorm, and built by Nuxt.js as well, all good.\n\nNow if I want to do the same for a scoped node module (a node module with a name in the format of `@scope/module`) Nuxt.js and PhpStorm diverges:\n\n`@import '@fortawesome/fontawesome-svg-core/styles.css';`\n\nThis works fine in Nuxt.js, build goes on without issues, but PhpStorm underlines the whole thing saying `Cannot resolve directory '@fortawesome'`\n\n`@import '~@fortawesome/fontawesome-svg-core/styles.css';`\n\nThis is understood by PhpStorm and can be resolved just fine, however causes Nuxt.js build to fail with:\n\n```\nERROR in ./client/assets/sass/app.scss\nModule build failed (from ./node_modules/extract-css-chunks-webpack-plugin/dist/loader.js):\nModuleBuildError: Module build failed (from ./node_modules/postcss-loader/src/index.js):\nError: Can't resolve '~@fortawesome/fontawesome-svg-core/styles.css'\n```\n\nSo my question is: Which syntax would be considered correct, and is it possible to make both PhpStorm and Nuxt.js happy at the same time?\n\nFor me the `~@` seems to make more sense, as `~` resolves to the path of my `node_modules` and the actual folder name in there starts with a `@`. Using only `@` kind of breaks the pattern compared to non-scoped node modules, for which `~` prefix is needed according to both PhpStorm and Nuxt.js.\n\n========================================\n\nTop Answer:\nIt's also possible to click right button and Mark directory as → Source root\n\nhttps://i.sstatic.net/hl5WD.png\n\n========================================\n\nCode:\n```text\nERROR in ./client/assets/sass/app.scss\nModule build failed (from ./node_modules/extract-css-chunks-webpack-plugin/dist/loader.js):\nModuleBuildError: Module build failed (from ./node_modules/postcss-loader/src/index.js):\nError: Can't resolve '~@fortawesome/fontawesome-svg-core/styles.css'\n```\n\n```text\napp.scss\n```\n\n```text\n@import '~bootstrap/scss/bootstrap';\n```\n\n```text\n@scope/module\n```\n\n```text\n@import '@fortawesome/fontawesome-svg-core/styles.css';\n```\n\n```text\nCannot resolve directory '@fortawesome'\n```\n\n```text\n@import '~@fortawesome/fontawesome-svg-core/styles.css';\n```\n\n```text\n~@\n```\n\n```text\n~\n```\n\n```text\nnode_modules\n```\n\n```text\n@\n```\n\n```text\n@\n```\n\n```text\n~\n```\n\n```text\n.css\n```\n\n```text\n@import '~@fortawesome/fontawesome-svg-core/styles';\n```\n\n```text\n.css\n```\n\n```text\n@import\n```\n\n```text\nsass-loader\n```\n\n```text\n@import url('~@fortawesome/fontawesome-svg-core/styles.css')\n```\n\n```text\nurl()\n```\n\n```text\n~\n```\n\n```text\n@import '@fortawesome/fontawesome-svg-core/styles.css';\n```\n\n```text\n@import url('@fortawesome/fontawesome-svg-core/styles.css')\n```\n\n```text\n@import '~@fortawesome/fontawesome-svg-core/styles';\n```\n\n```text\nsass-loader\n```\n\n```text\nnode_modules/@fortawesome/fontawesome-svg-core/styles.css\n```\n\n```text\n.scss\n```\n\n```text\n.css\n```\n\n========================================\n\nComments:\n- Apparently Nuxt.js includes the given `styles.css` file as inline in the final `app.*.css` file in both cases. My assumption is that in the first case `@import '@fortawesome/fontawesome-svg-core/styles.css';` results in `@import url('@fortawesome/fontawesome-svg-core/styles.css')` which in turn inlined by webpack at some point, so both works from the build perspective, but it seems to be more like another loader or mechanism after `sass-loader` fixes the messed up `@import url()` part, so the 2nd one still seems to be cleaner solution. But these are just assumptions. Correct me, if I'm wrong!","metadata":{"transformedAt":"2026-08-18T18:33:07.886Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":161,"estimatedTokens":952}}688{"id":"stack-58780816","source":"stackoverflow","questionId":58780816,"title":"I have a problem with understanding the event system","tags":["javascript","node.js","vue.js","nuxt.js"],"text":"Title: I have a problem with understanding the event system\nTags: javascript, node.js, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have this code: \n\n\r\n\r\n\n```\n\r\n\r\n \r\n\r\n \r\n \r\n end -->\r\n\r\n \r\n end -->\r\n\r\n\r\n\r\n\r\n import axios from 'axios';\r\n\r\nexport default{\r\n\r\ncreated () {\r\n},\r\n\r\ndata () {\r\n return {\r\n ticket: null,\r\n\r\n chartStyleObject: {\r\n width: '500px',\r\n widthWrapper: '1600px',\r\n heightWrapper: '500px',\r\n height: '247px',\r\n marginTop: '15px',\r\n marginRight: '0px',\r\n marginBottom: '0px',\r\n marginLeft: '15px',\r\n },\r\n\r\n XCoord: null,\r\n YCoord: null,\r\n\r\n }\r\n},\r\n\r\nmethods: {\r\n\r\n initHandleMousedown(event) {\r\n this.startMousedownXCoord = event.clientX;\r\n this.startMousedownYCoord = event.clientY;\r\n this.XCoord = event.clientX;\r\n this.YCoord = event.clientY;\r\n\r\n console.log('XCoord', this.XCoord);\r\n console.log('YCoord', this.YCoord);\r\n\r\n window.addEventListener('mousemove', this.initHandleMouseMove);\r\n },\r\n\r\n initHandleMouseMove(event) {\r\n\r\n this.XCoord = event.clientX;\r\n this.YCoord = event.clientY;\r\n\r\n console.log('XCoord', this.XCoord);\r\n console.log('YCoord', this.YCoord);\r\n\r\n },\r\n\r\n initHandleMouseup() {\r\n window.removeEventListener('mousemove', this.initHandleMouseMove);\r\n },\r\n\r\n },\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\n.chart{\r\n position: relative;\r\n border-radius: 10px;\r\n padding: 27px 10px 10px 10px;\r\n background-color: #45788b;\r\n box-sizing: border-box;\r\n cursor: move;\r\n}\r\n.chart .chartContent{\r\n position: relative;\r\n top: 0;\r\n left: 0;\r\n height: 100%;\r\n width: 100%;\r\n margin: 0 0 0 0;\r\n background-color: #2f2c8b;\r\n}\r\n\r\n\r\n\r\n\n```\n\n\r\n\r\n\r\n\n```\nHTML design consists of 2 blocks:\n(parent and child)\nThe event is tied to the parent tag ``\nAlso, the parent block has padding on all 4 sides:\n```\n\nhttps://i.sstatic.net/30bEe.jpg\n\nIf you click on the parent block and drive with the mouse (holding the button pressed) without affecting the padding space, the mousemove event will fire without problems.\nBut as soon as the mouse cursor touches the padding territory, the event ceases to function. \n\nIf you click on the padding, the event also works correctly - but it stops working if I move the mouse cursor over the block space outside the paddings (internal space) \n\nQuestion: \n\nWhy is this happening - and is this behavior normal for js + nuxt.js?\n\n========================================\n\nTop Answer:\nskirtle answer is correct. I am only providing this answer to illustrate how to do it using your own code. The only line I changed was this `v-on:mouseleave=\"initHandleMouseup()`. Notice I changed it to mouseout to mouseleave.\n\nTo summarize: \n\n`mouseleave` is fired once per element regardless of its children\nhover. \n`mouseout` is fired every time the element abandoned (whether\nmoving the mouse away or hovering over its children).\n\n\r\n\r\n\n```\nnew Vue({\r\n el: \"#app\",\r\n template: `\r\n\r\n \r\n\r\n \r\n \r\n end -->\r\n\r\n \r\n end -->\r\n\r\n`,\r\n created: function() {},\r\n\r\n data() {\r\n return {\r\n ticket: null,\r\n\r\n chartStyleObject: {\r\n width: '500px',\r\n widthWrapper: '1600px',\r\n heightWrapper: '500px',\r\n height: '247px',\r\n marginTop: '15px',\r\n marginRight: '0px',\r\n marginBottom: '0px',\r\n marginLeft: '15px',\r\n },\r\n\r\n XCoord: null,\r\n YCoord: null,\r\n\r\n }\r\n },\r\n\r\n methods: {\r\n\r\n initHandleMousedown: function(event) {\r\n this.startMousedownXCoord = event.clientX;\r\n this.startMousedownYCoord = event.clientY;\r\n this.XCoord = event.clientX;\r\n this.YCoord = event.clientY;\r\n\r\n console.log('XCoord', this.XCoord);\r\n console.log('YCoord', this.YCoord);\r\n\r\n window.addEventListener('mousemove', this.initHandleMouseMove);\r\n },\r\n\r\n initHandleMouseMove: function(event) {\r\n\r\n this.XCoord = event.clientX;\r\n this.YCoord = event.clientY;\r\n\r\n console.log('XCoord', this.XCoord);\r\n console.log('YCoord', this.YCoord);\r\n\r\n },\r\n\r\n initHandleMouseup: function() {\r\n window.removeEventListener('mousemove', this.initHandleMouseMove);\r\n }\r\n }\r\n});\n```\n\n\r\n\n```\n.chart {\r\n position: relative;\r\n border-radius: 10px;\r\n padding: 27px 10px 10px 10px;\r\n background-color: #45788b;\r\n box-sizing: border-box;\r\n cursor: move;\r\n}\r\n\r\n.chart .chartContent {\r\n position: relative;\r\n top: 0;\r\n left: 0;\r\n height: 100%;\r\n width: 100%;\r\n margin: 0 0 0 0;\r\n background-color: #2f2c8b;\r\n}\n```\n\n\r\n\n```\n\r\n\n```\n\n\r\n\r\n\r\n\nTo see the different between `mouseout/mouseover` vs `mouseenter/mouseleave` events see this demo (taken from jQuery documentation) :\n\n\r\n\r\n\n```\nvar i = 0;\r\n$(\"div.overout\")\r\n .mouseout(function() {\r\n $(\"p\", this).first().text(\"mouse out\");\r\n $(\"p\", this).last().text(++i);\r\n })\r\n .mouseover(function() {\r\n $(\"p\", this).first().text(\"mouse over\");\r\n });\r\n\r\nvar n = 0;\r\n$(\"div.enterleave\")\r\n .on(\"mouseenter\", function() {\r\n $(\"p\", this).first().text(\"mouse enter\");\r\n })\r\n .on(\"mouseleave\", function() {\r\n $(\"p\", this).first().text(\"mouse leave\");\r\n $(\"p\", this).last().text(++n);\r\n });\n```\n\n\r\n\n```\ndiv.out {\r\n width: 40%;\r\n height: 120px;\r\n margin: 0 15px;\r\n background-color: #d6edfc;\r\n float: left;\r\n}\r\n\r\ndiv.in {\r\n width: 60%;\r\n height: 60%;\r\n background-color: #fc0;\r\n margin: 10px auto;\r\n}\r\n\r\np {\r\n line-height: 1em;\r\n margin: 0;\r\n padding: 0;\r\n}\n```\n\n\r\n\n```\n\r\n\r\n move your mouse\n\n\r\n \r\n move your mouse\n\n\r\n 0\n\n\r\n \r\n 0\n\n\r\n\r\n\r\n\r\n move your mouse\n\n\r\n \r\n move your mouse\n\n\r\n 0\n\n\r\n \r\n 0\n\n\r\n\n```\n\n========================================\n\nCode:\n```js\n<template>\n\n <div class=\"chart\"\n v-bind:style=\"chartStyleObject\"\n v-on:mousedown.left=\"initHandleMousedown($event)\"\n v-on:mouseup.left=\"initHandleMouseup()\"\n v-on:mouseout=\"initHandleMouseup()\">\n\n <div class=\"chartContent\">\n </div>\n <!-- <div class=\"chartContent\"> end -->\n\n </div>\n <!-- <div class=\"chart\"> end -->\n\n</template>\n\n<script>\n import axios from 'axios';\n\nexport default{\n\ncreated () {\n},\n\ndata () {\n return {\n ticket: null,\n\n chartStyleObject: {\n width: '500px',\n widthWrapper: '1600px',\n heightWrapper: '500px',\n height: '247px',\n marginTop: '15px',\n marginRight: '0px',\n marginBottom: '0px',\n marginLeft: '15px',\n },\n\n XCoord: null,\n YCoord: null,\n\n }\n},\n\nmethods: {\n\n initHandleMousedown(event) {\n this.startMousedownXCoord = event.clientX;\n this.startMousedownYCoord = event.clientY;\n this.XCoord = event.clientX;\n this.YCoord = event.clientY;\n\n console.log('XCoord', this.XCoord);\n console.log('YCoord', this.YCoord);\n\n window.addEventListener('mousemove', this.initHandleMouseMove);\n },\n\n initHandleMouseMove(event) {\n\n this.XCoord = event.clientX;\n this.YCoord = event.clientY;\n\n console.log('XCoord', this.XCoord);\n console.log('YCoord', this.YCoord);\n\n },\n\n initHandleMouseup() {\n window.removeEventListener('mousemove', this.initHandleMouseMove);\n },\n\n },\n\n}\n\n</script>\n\n<style scoped>\n\n.chart{\n position: relative;\n border-radius: 10px;\n padding: 27px 10px 10px 10px;\n background-color: #45788b;\n box-sizing: border-box;\n cursor: move;\n}\n.chart .chartContent{\n position: relative;\n top: 0;\n left: 0;\n height: 100%;\n width: 100%;\n margin: 0 0 0 0;\n background-color: #2f2c8b;\n}\n\n\n\n</style>\n```\n\n```text\nHTML design consists of 2 blocks:\n(parent and child)\nThe event is tied to the parent tag `<div class =\" chart \">`\nAlso, the parent block has padding on all 4 sides:\n```\n\n```js\ndocument.getElementById('outer').addEventListener('mouseout', () => {\n document.getElementById('out').innerHTML += 'mouseout\\n'\n})\n```\n\n```css\ndiv {\n border: 1px solid;\n display: inline-block;\n padding: 20px;\n}\n```\n\n```html\n<div id=\"outer\">\n <div></div>\n</div>\n<pre id=\"out\"></pre>\n```\n\n```text\nmouseout\n```\n\n```text\nmousemove\n```\n\n```text\nmouseout\n```\n\n```text\nmouseout\n```\n\n```text\nmouseleave\n```\n\n```text\nmouseout\n```\n\n```text\nmouseout\n```\n\n```text\nmousemove\n```\n\n```js\nnew Vue({\n el: \"#app\",\n template: `\n\n <div class=\"chart\"\n v-bind:style=\"chartStyleObject\"\n v-on:mousedown.left=\"initHandleMousedown($event)\"\n v-on:mouseup.left=\"initHandleMouseup()\"\n v-on:mouseleave=\"initHandleMouseup()\">\n\n <div class=\"chartContent\">\n </div>\n <!-- <div class=\"chartContent\"> end -->\n\n </div>\n <!-- <div class=\"chart\"> end -->\n\n`,\n created: function() {},\n\n data() {\n return {\n ticket: null,\n\n chartStyleObject: {\n width: '500px',\n widthWrapper: '1600px',\n heightWrapper: '500px',\n height: '247px',\n marginTop: '15px',\n marginRight: '0px',\n marginBottom: '0px',\n marginLeft: '15px',\n },\n\n XCoord: null,\n YCoord: null,\n\n }\n },\n\n methods: {\n\n initHandleMousedown: function(event) {\n this.startMousedownXCoord = event.clientX;\n this.startMousedownYCoord = event.clientY;\n this.XCoord = event.clientX;\n this.YCoord = event.clientY;\n\n console.log('XCoord', this.XCoord);\n console.log('YCoord', this.YCoord);\n\n window.addEventListener('mousemove', this.initHandleMouseMove);\n },\n\n initHandleMouseMove: function(event) {\n\n this.XCoord = event.clientX;\n this.YCoord = event.clientY;\n\n console.log('XCoord', this.XCoord);\n console.log('YCoord', this.YCoord);\n\n },\n\n initHandleMouseup: function() {\n window.removeEventListener('mousemove', this.initHandleMouseMove);\n }\n }\n});\n```\n\n```css\n.chart {\n position: relative;\n border-radius: 10px;\n padding: 27px 10px 10px 10px;\n background-color: #45788b;\n box-sizing: border-box;\n cursor: move;\n}\n\n.chart .chartContent {\n position: relative;\n top: 0;\n left: 0;\n height: 100%;\n width: 100%;\n margin: 0 0 0 0;\n background-color: #2f2c8b;\n}\n```\n\n```html\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"></script>\n<div id='app'></div>\n```\n\n```js\nvar i = 0;\n$(\"div.overout\")\n .mouseout(function() {\n $(\"p\", this).first().text(\"mouse out\");\n $(\"p\", this).last().text(++i);\n })\n .mouseover(function() {\n $(\"p\", this).first().text(\"mouse over\");\n });\n\nvar n = 0;\n$(\"div.enterleave\")\n .on(\"mouseenter\", function() {\n $(\"p\", this).first().text(\"mouse enter\");\n })\n .on(\"mouseleave\", function() {\n $(\"p\", this).first().text(\"mouse leave\");\n $(\"p\", this).last().text(++n);\n });\n```\n\n```css\ndiv.out {\n width: 40%;\n height: 120px;\n margin: 0 15px;\n background-color: #d6edfc;\n float: left;\n}\n\ndiv.in {\n width: 60%;\n height: 60%;\n background-color: #fc0;\n margin: 10px auto;\n}\n\np {\n line-height: 1em;\n margin: 0;\n padding: 0;\n}\n```\n\n```html\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div class=\"out overout\">\n <p>move your mouse</p>\n <div class=\"in overout\">\n <p>move your mouse</p>\n <p>0</p>\n </div>\n <p>0</p>\n</div>\n\n<div class=\"out enterleave\">\n <p>move your mouse</p>\n <div class=\"in enterleave\">\n <p>move your mouse</p>\n <p>0</p>\n </div>\n <p>0</p>\n</div>\n```\n\n```text\nv-on:mouseleave=\"initHandleMouseup()\n```\n\n```text\nmouseleave\n```\n\n```text\nmouseout\n```\n\n```text\nmouseout/mouseover\n```\n\n```text\nmouseenter/mouseleave\n```\n\n========================================\n\nComments:\n- @Alex Could you elaborate on exactly what the bounty is for? If you just wanted some links to the relevant sections on MDN you could've just posted a comment on my answer so I assume you're looking for something a bit more than that.","metadata":{"transformedAt":"2026-08-18T18:33:07.887Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":701,"estimatedTokens":2797}}689{"id":"stack-60196590","source":"stackoverflow","questionId":60196590,"title":"*Nuxt JS Auth* Why after success login with loginWith in template sections auth.loggedIn is true, but in middleware file is false?","tags":["vue.js","authentication","nuxt.js"],"text":"Title: *Nuxt JS Auth* Why after success login with loginWith in template sections auth.loggedIn is true, but in middleware file is false?\nTags: vue.js, authentication, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI just started learning NuxtJS and I want to implement authentication by auth module for Nuxt.\nI don't know why, but login with loginWith seems working, on vue files I can get data about logged user and loggedIn variable has true value. But I noticed when I set middleware from auth module, even if I'm logged in, server is redirecting always to login endpoint. I saw that I can make my middleware file, but there loggedIn has value false, so I can't be redirected correctly.\n\n**index.vue**\n\n```\n\n \n \n \n\nimport panel from \"~/components/Panel.vue\"\n\nexport default {\n middleware: ['authenticated'],\n 'components': {\n panel\n },\n\n};\n\n```\n\n**My login component:**\n\n```\n\n \n \n \n \n \n \n \n Login\n{{ $auth.loggedIn }} // here is true after login\n\n \n Login: {{ username }} Hasło: {{ password }}\n\n Send\n \n \n\nimport \"bootstrap-vue\"\nimport axios from \"axios\"\n\nexport default {\n name: \"loginForm\",\n data() {\n return{\n username: '',\n password: '',\n }\n },\n props: {\n\n },\n methods: {\n async loginUser(loginInfo){\n try {\n await this.$auth.loginWith('local', {\n data: loginInfo\n });\n } catch (e) {\n this.$router.push('/');\n }\n }\n\n },\n...\n\n```\n\n**nuxt.config.js for auth**\n\n```\nauth: {\n strategies: {\n local: {\n endpoints: {\n login: { url: '/auth/token/login/', method: 'post', propertyName: 'auth_token' },\n logout: { url: '/auth/token/logout/', method: 'post' },\n user: { url: '/auth/users/me/', method: 'get', propertyName: false }\n },\n tokenRequired: true,\n tokenType: 'Token',\n tokenName: 'Authorization'\n }\n },\n\n redirect: {\n login: \"/\",\n logout: \"/\",\n home: \"/home\"\n },\n\n },\n```\n\n**autenticated.js in middleware**\n\n```\nexport default function ({ store, redirect }) {\n console.log(store.state.auth.loggedIn); // here returns false, even after success login\n if (store.state.auth.loggedIn) {\n return redirect('/home')\n }\n}\n```\n\nWorth to mention is that, it's running on docker. Maybe that's a problem.\n\n**UPDATE**\nI changed nuxt mode from SSR to SPA and now everything works from nuxt auth module.\n\nBut I want to that works on SSR, so if someone have solution, please .\n\n========================================\n\nTop Answer:\nmy nuxt.config.js also:\n\n```\nauth: {\n strategies: {\n local: {\n endpoints: {\n login: { url: '/api/login', method: 'post' },\n logout: false,\n user: false,\n },\n tokenRequired: true,\n },\n},\nrewriteRedirects: false,\n\n redirect: {\n login: '/login',\n logout: '/login',\n home: '/dashboard',\n},}\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div id=\"main-page\">\n <panel />\n </div>\n</template>\n\n<script>\nimport panel from \"~/components/Panel.vue\"\n\n\nexport default {\n middleware: ['authenticated'],\n 'components': {\n panel\n },\n\n};\n</script>\n```\n\n```text\n<template>\n <div id=\"form-wrapper\">\n <b-form-group \n class=\"ml-3 mr-5\"\n label=\"Username\"\n label-for=\"id-username\"\n :invalid-feedback=\"invalidFeedback\"\n :state='state'\n >\n <b-form-input id=\"id-username\" v-model=\"username\" type=\"text\" placeholder=\"elo\"></b-form-input> \n </b-form-group>\n <b-form-group \n class=\"ml-3 mr-5\"\n label=\"Password\"\n label-for=\"id-password\"\n :invalid-feedback=\"invalidFeedbackPass\"\n :state='statePass'\n >\n <b-form-input id=\"id-password\" v-model=\"password\" type=\"password\"></b-form-input> \n </b-form-group>\n <b-button v-b-modal.login-modal class=\"ml-3 mr-5\" variant=\"outline-success\">Login</b-button>\n<div v-if=\"$auth.loggedIn\">{{ $auth.loggedIn }}</div> // here is true after login\n\n <b-modal ref=\"login-modal\" id=\"login-modal\" hide-footer hide-header>\n <p>Login: {{ username }} Hasło: {{ password }}</p>\n <b-button @click=\"loginUser({username, password})\">Send</b-button>\n </b-modal>\n </div> \n</template>\n\n<script>\nimport \"bootstrap-vue\"\nimport axios from \"axios\"\n\nexport default {\n name: \"loginForm\",\n data() {\n return{\n username: '',\n password: '',\n }\n },\n props: {\n\n },\n methods: {\n async loginUser(loginInfo){\n try {\n await this.$auth.loginWith('local', {\n data: loginInfo\n });\n } catch (e) {\n this.$router.push('/');\n }\n }\n\n },\n...\n</script>\n```\n\n```text\nauth: {\n strategies: {\n local: {\n endpoints: {\n login: { url: '/auth/token/login/', method: 'post', propertyName: 'auth_token' },\n logout: { url: '/auth/token/logout/', method: 'post' },\n user: { url: '/auth/users/me/', method: 'get', propertyName: false }\n },\n tokenRequired: true,\n tokenType: 'Token',\n tokenName: 'Authorization'\n }\n },\n\n redirect: {\n login: \"/\",\n logout: \"/\",\n home: \"/home\"\n },\n\n },\n```\n\n```text\nexport default function ({ store, redirect }) {\n console.log(store.state.auth.loggedIn); // here returns false, even after success login\n if (store.state.auth.loggedIn) {\n return redirect('/home')\n }\n}\n```\n\n```text\nexport default{\n mode: 'spa',\n\n modules: [\n '@nuxtjs/axios',\n '@nuxtjs/auth'\n ],\n\n axios: {\n baseURL: 'http://127.0.0.1:8000/api',\n browserBaseURL: 'http://127.0.0.1:8000/api'\n },\n\n auth: {\n\n strategies: {\n local: {\n endpoints: {\n login: { url: '/auth/token/login/', method: 'post', propertyName: 'auth_token' },\n logout: { url: '/auth/token/logout/', method: 'post' },\n user: { url: '/auth/users/me/', method: 'get', propertyName: false }\n },\n tokenRequired: true,\n tokenType: 'Token',\n tokenName: 'Authorization'\n }\n },\n rewriteRedirects: false,\n\n redirect: {\n login: \"/login\",\n logout: \"/login\",\n home: \"/\",\n },\n },\n\n router : {\n middleware: ['auth'],\n }\n}\n```\n\n```text\nauth: {\n strategies: {\n local: {\n endpoints: {\n login: { url: '/api/login', method: 'post' },\n logout: false,\n user: false,\n },\n tokenRequired: true,\n },\n},\nrewriteRedirects: false,\n\n redirect: {\n login: '/login',\n logout: '/login',\n home: '/dashboard',\n},}\n```\n\n========================================\n\nComments:\n- I found how to kinda solve the issue. I changed mode from SSR to SPA and now redirects works. But I think SSR mode is better option than SPA, so if someone will find a solution, please .\n- have you checked answers eg in the thread: github.com/nuxt-community/auth-module/issues/55 ?\n- @Michal_Szulc Yes I checked this. Also I don't use ENV's variables for axios. For now when I'm still learning nuxt I hardcoded baseURL for axios.\n- I read a lot threads about that and a lot of people have same problem. But no one could explain why is this happening exacly. For now when I changed mode to SPA everything work nice, but for bigger projects it could have impact for performance and CEO.\n- Well this didn't solve my problem but gave me hints where the problem was. I've changed it to `spa` to `universal` again and my mistake was in the user request after login. I had `user: { url: '/auth/users/me/', method: 'get', propertyName: 'user' }` in the `endpoints` section and changed it to false, like you did. I noticed that your solution had `rewriteRedirects: false,` but using this prevents the redirect I need to my \"home\" path.\n- After half day i give up and added option ssr: false. `mode: spa` is depreciated now, but srr auth module integration is probably impossible without firebase...","metadata":{"transformedAt":"2026-08-18T18:33:07.887Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":341,"estimatedTokens":1950}}690{"id":"stack-54757867","source":"stackoverflow","questionId":54757867,"title":"How to fix SSL wrong version number error in NuxtJS?","tags":["https","nuxt.js"],"text":"Title: How to fix SSL wrong version number error in NuxtJS?\nTags: https, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using nuxt.js to Server Side Rendering. I have to apply HTTPS onto my nuxt application, so I applied SSL certificate which is generated by Certbot. However, my Nuxt application generates an error which is like the below.\n\n```\nERROR write EPROTO 140118450071360:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:252:\n```\n\nMy server is AWS EC2. and I'm using Ubuntu 16.04, Nginx, and Express. I've tried to change my nginx proxy policy, but it doesn't work.\n\nThe below is my code which runs a server.\n\n```\n/**\n * Module dependencies.\n */\n\nvar app = require('../app');\nvar debug = require('debug')('server:server');\nvar http = require('http');\nvar fs = require('fs');\nvar https = require('https');\nvar tls = require(\"tls\");\nvar db = require('../models');\n\n/**\n * Get port from environment and store in Express.\n */\n\ntls.DEFAULT_ECDH_CURVE = \"auto\";\nconst serverAddress = require('../config').serverAddress\nconst port = 3000\n\nif (serverAddress === '') {\n console.log(\"deploy enter #####\");\n\n // Certificate\n const privateKey = fs.readFileSync(\"\", \"utf8\");\n const certificate = fs.readFileSync(\"\", \"utf8\");\n const ca = fs.readFileSync(\"\", \"utf8\");\n\n const credentials = {\n key: privateKey,\n cert: certificate\n };\n\n /**\n * Create HTTPS server.\n */\n\n https.createServer(credentials, app).listen(port, function() {\n db.sequelize\n .authenticate().then(() => {\n console.log('Connection has been established successfully.');\n db.sequelize.sync();\n\n }).catch((err) => {\n console.error('Unable to connect to the database:', err);\n })\n });\n\n} else {\n console.log(\"local enter #####\");\n\n /**\n * Listen on provided port, on all network interfaces.\n */\n var http = require('http')\n var server = http.createServer(app);\n\n app.set('port', port);\n\n server.listen(port);\n server.on('error', onError);\n server.on('listening', onListening);\n}\n\n/**\n * Normalize a port into a number, string, or false.\n */\n\nfunction normalizePort(val) {\n var port = parseInt(val, 10);\n\n if (isNaN(port)) {\n // named pipe\n return val;\n }\n\n if (port >= 0) {\n // port number\n return port;\n }\n\n return false;\n}\n\n/**\n * Event listener for HTTP server \"error\" event.\n */\n\nfunction onError(error) {\n if (error.syscall !== 'listen') {\n throw error;\n }\n\n var bind = typeof port === 'string'\n ? 'Pipe ' + port\n : 'Port ' + port;\n\n // handle specific listen errors with friendly messages\n switch (error.code) {\n case 'EACCES':\n console.error(bind + ' requires elevated privileges');\n process.exit(1);\n break;\n case 'EADDRINUSE':\n console.error(bind + ' is already in use');\n process.exit(1);\n break;\n default:\n throw error;\n }\n}\n\n/**\n * Event listener for HTTP server \"listening\" event.\n */\n\nfunction onListening() {\n var addr = server.address();\n var bind = typeof addr === 'string'\n ? 'pipe ' + addr\n : 'port ' + addr.port;\n debug('Listening on ' + bind);\n}\n```\n\nand the below is my Nginx Configuration.\n\n```\nserver {\n # Note: You should disable gzip for SSL traffic.\n # See: https://bugs.debian.org/773332\n #\n # Read up on ssl_ciphers to ensure a secure configuration.\n # See: https://bugs.debian.org/765782\n #\n # Self signed certs generated by the ssl-cert package\n # Don't use them in a production server!\n #\n # include snippets/snakeoil.conf;\n\n # Add index.php to the list if you are using PHP\n index index.html index.htm index.nginx-debian.html;\n server_name mysterico.com; # managed by Certbot\n\n location / {\n # First attempt to serve request as file, then\n # as directory, then fall back to displaying a 404.\n try_files $uri $uri/ =404;\n proxy_pass http://127.0.0.1:8080;\n }\n\n listen [::]:443 ssl http2 ipv6only=on; # managed by Certbot\n listen 443 ssl; # managed by Certbot\n gzip off;\n ssl_certificate /etc/letsencrypt/live/.../fullchain.pem; # managed by Certbot\n ssl_certificate_key /etc/letsencrypt/live/.../privkey.pem; # managed by Certbot\n include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot\n ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot\n}\n\nserver {\n if ($host = mysterico.com) {\n return 301 https://$host$request_uri;\n }\n\n listen 80;\n listen [::]:80;\n server_name mysterico.com;\n return 404;\n}\n```\n\n========================================\n\nCode:\n```text\nERROR write EPROTO 140118450071360:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:252:\n```\n\n```text\n/**\n * Module dependencies.\n */\n\nvar app = require('../app');\nvar debug = require('debug')('server:server');\nvar http = require('http');\nvar fs = require('fs');\nvar https = require('https');\nvar tls = require(\"tls\");\nvar db = require('../models');\n\n/**\n * Get port from environment and store in Express.\n */\n\ntls.DEFAULT_ECDH_CURVE = \"auto\";\nconst serverAddress = require('../config').serverAddress\nconst port = 3000\n\nif (serverAddress === '') {\n console.log(\"deploy enter #####\");\n\n // Certificate\n const privateKey = fs.readFileSync(\"\", \"utf8\");\n const certificate = fs.readFileSync(\"\", \"utf8\");\n const ca = fs.readFileSync(\"\", \"utf8\");\n\n const credentials = {\n key: privateKey,\n cert: certificate\n };\n\n /**\n * Create HTTPS server.\n */\n\n https.createServer(credentials, app).listen(port, function() {\n db.sequelize\n .authenticate().then(() => {\n console.log('Connection has been established successfully.');\n db.sequelize.sync();\n\n }).catch((err) => {\n console.error('Unable to connect to the database:', err);\n })\n });\n\n} else {\n console.log(\"local enter #####\");\n\n /**\n * Listen on provided port, on all network interfaces.\n */\n var http = require('http')\n var server = http.createServer(app);\n\n app.set('port', port);\n\n server.listen(port);\n server.on('error', onError);\n server.on('listening', onListening);\n}\n\n/**\n * Normalize a port into a number, string, or false.\n */\n\nfunction normalizePort(val) {\n var port = parseInt(val, 10);\n\n if (isNaN(port)) {\n // named pipe\n return val;\n }\n\n if (port >= 0) {\n // port number\n return port;\n }\n\n return false;\n}\n\n/**\n * Event listener for HTTP server \"error\" event.\n */\n\nfunction onError(error) {\n if (error.syscall !== 'listen') {\n throw error;\n }\n\n var bind = typeof port === 'string'\n ? 'Pipe ' + port\n : 'Port ' + port;\n\n // handle specific listen errors with friendly messages\n switch (error.code) {\n case 'EACCES':\n console.error(bind + ' requires elevated privileges');\n process.exit(1);\n break;\n case 'EADDRINUSE':\n console.error(bind + ' is already in use');\n process.exit(1);\n break;\n default:\n throw error;\n }\n}\n\n/**\n * Event listener for HTTP server \"listening\" event.\n */\n\nfunction onListening() {\n var addr = server.address();\n var bind = typeof addr === 'string'\n ? 'pipe ' + addr\n : 'port ' + addr.port;\n debug('Listening on ' + bind);\n}\n```\n\n```text\nserver {\n # Note: You should disable gzip for SSL traffic.\n # See: https://bugs.debian.org/773332\n #\n # Read up on ssl_ciphers to ensure a secure configuration.\n # See: https://bugs.debian.org/765782\n #\n # Self signed certs generated by the ssl-cert package\n # Don't use them in a production server!\n #\n # include snippets/snakeoil.conf;\n\n # Add index.php to the list if you are using PHP\n index index.html index.htm index.nginx-debian.html;\n server_name mysterico.com; # managed by Certbot\n\n\n location / {\n # First attempt to serve request as file, then\n # as directory, then fall back to displaying a 404.\n try_files $uri $uri/ =404;\n proxy_pass http://127.0.0.1:8080;\n }\n\n listen [::]:443 ssl http2 ipv6only=on; # managed by Certbot\n listen 443 ssl; # managed by Certbot\n gzip off;\n ssl_certificate /etc/letsencrypt/live/.../fullchain.pem; # managed by Certbot\n ssl_certificate_key /etc/letsencrypt/live/.../privkey.pem; # managed by Certbot\n include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot\n ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot\n}\n\nserver {\n if ($host = mysterico.com) {\n return 301 https://$host$request_uri;\n }\n\n listen 80;\n listen [::]:80;\n server_name mysterico.com;\n return 404;\n}\n```\n\n```js\npublicRuntimeConfig: {\n axios: {\n // this is the url used on the server:\n baseURL: \"http://localhost:8080/api/v1\",\n // this is the url used in the browser:\n browserBaseURL: \"https://localhost:8443/api/v1\",\n },\n},\n```\n\n```js\nmethods: {\n getSomeData() {\n const $axios = this.$nuxt.$axios\n return $axios.$post('/my/data').then((result) => {\n // do something with the data\n })\n },\n}\n```\n\n```text\nssl3_get_record:wrong version number\n```\n\n```text\nhttps\n```\n\n```text\nhttp\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n.vue\n```\n\n```text\n.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.887Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":412,"estimatedTokens":2284}}691{"id":"stack-70474176","source":"stackoverflow","questionId":70474176,"title":"tailwind: how to use @apply for custom class in nuxt2?","tags":["css","nuxt.js","tailwind-css"],"text":"Title: tailwind: how to use @apply for custom class in nuxt2?\nTags: css, nuxt.js, tailwind-css\nSource: Stack Overflow\n\nQuestion:\nI am trying to use `@apply` on my custom class in Nuxt.js 2\n\n**nuxt.config.js**\n\n```\nexport default {\n buildModules: [\n '@nuxtjs/tailwindcss',\n ],\n tailwindcss: {\n cssPath: '~/assets/app.css',\n exposeConfig: true\n }\n}\n```\n\n**assets/app.css**\n\n```\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n@layer utilities {\n .btn {\n @apply border-2 p-2 font-bold;\n }\n}\n```\n\nin any vue-single-file or any other scss file\n\n```\n\n .btn-lg {\n @apply btn;\n }\n\n```\n\nhttps://i.sstatic.net/P6XIO.png\n\nThe `btn` class does not exist. If you're sure that `btn` exists, make sure that any `@import` statements are being properly processed before Tailwind CSS sees your CSS, as `@apply` can only be used for classes in the same CSS tree\n\n**So, how to make my custom styles be seen by the Tailwind CSS before processing to make my custom classes work in `@apply`?**\n\nI've tried the solutions in the following questions and document\n\n- adding-custom-utilities\n\n- not able to use custom classes in @apply in scss file tailwind nextjs project?\n\nBut none of them work\n\nI am using:\n\n- Tailwindcss **2.2.19** via @nuxtjs/tailwindcss\n\n- Nuxt.js 2.15.8\n\nThanks a lot for any replies!\n\n========================================\n\nCode:\n```js\nexport default {\n buildModules: [\n '@nuxtjs/tailwindcss',\n ],\n tailwindcss: {\n cssPath: '~/assets/app.css',\n exposeConfig: true\n }\n}\n```\n\n```text\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n@layer utilities {\n .btn {\n @apply border-2 p-2 font-bold;\n }\n}\n```\n\n```js\n<style lang=\"scss\">\n .btn-lg {\n @apply btn;\n }\n</style>\n```\n\n```text\n@apply\n```\n\n```text\nbtn\n```\n\n```text\nbtn\n```\n\n```text\n@import\n```\n\n```text\n@apply\n```\n\n```text\n@apply\n```\n\n```js\nmodule.exports = {\n mode: 'jit'\n}\n```\n\n```js\nconst plugin = require('tailwindcss/plugin')\nconst fs = require('fs')\nmodule.exports = {\n // ... purge, theme, variants, ...\n plugins: [\n plugin(function({ addUtilities, postcss }) {\n const css = fs.readFileSync('./your-custom-style-file-path', 'utf-8')\n addUtilities(postcss.parse(css).nodes)\n }),\n ],\n}\n```\n\n```js\nvite: {\n plugins: [\n {\n name: 'watch-external', // https://stackoverflow.com/questions/63373804/rollup-watch-include-directory/63548394#63548394\n async buildStart(){\n const files = await fg(['assets/**/*']);\n for(let file of files){\n this.addWatchFile(file);\n }\n }\n }\n ]\n}\n```\n\n```text\nmode: \"jit\"\n```\n\n```text\ntailwindcss\n```\n\n```text\n@nuxtjs/tailwindcss\n```\n\n```text\nplugin()\n```\n\n```text\ntailwind.config.css\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt-vite\n```\n\n========================================\n\nComments:\n- Fine, it seems to be a bug in nuxtjs/tailwindcss: Custom utility: @apply can only be used for classes in the same CSS tree., just add a `mode:\"jit\"` can solve this problem\n- Post this as an answer!\n- I am facing similar issue even after using the `mode: jit`. I have posted my question here: stackoverflow.com/q/78792351/7584240 Can you please check and provide some solution?\n- With tailwindcss 3, it comes with a standalone CLI - tailwindcss.com/blog/standalone-cli - can this be used instead of including tailwindcss in node ?\n- I am facing similar issue even after using the `mode: jit`. I have posted my question here: stackoverflow.com/q/78792351/7584240 Can you please check and provide some solution?","metadata":{"transformedAt":"2026-08-18T18:33:07.887Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":198,"estimatedTokens":900}}692{"id":"stack-66292558","source":"stackoverflow","questionId":66292558,"title":"Cannot read property '$options' of undefined making external js file for head options","tags":["javascript","vue.js","nuxt.js","nuxt-i18n"],"text":"Title: Cannot read property '$options' of undefined making external js file for head options\nTags: javascript, vue.js, nuxt.js, nuxt-i18n\nSource: Stack Overflow\n\nQuestion:\nI need to set up global head in Nuxt for my app, which some subpages will overwrite. Those global head needs to contain translated data.\n\nI created `seoHead.js` file with code:\n\n```\nimport Vue from \"vue\";\n\nexport const $t = (sign) => Vue.prototype.$nuxt.$options.i18n.t(sign);\n\nexport default {\n title: $t(\"seoGlobal.title\"),\n meta: [\n { charset: \"utf-8\" },\n { name: \"viewport\", content: \"width=device-width, initial-scale=1\" },\n {\n hid: \"description\",\n name: \"description\",\n content: $t(\"seoGlobal.description\"),\n },\n {\n hid: \"ogSiteName\",\n name: \"og:site_name\",\n content: \"Test Page\",\n },\n {\n hid: \"ogTitle\",\n name: \"og:title\",\n content: $t(\"seoGlobal.ogTitle\"),\n },\n (...)\n ],\n};\n```\n\nI import and use this data in my `index.vue` and other pages like this:\n\n```\nimport seoHead from \"~/constants/seoHead\";\n\nexport default {\n head() {\n const metaI18n = this.$nuxtI18nSeo();\n const currentPath = process.env.LP_URL + this.$router.currentRoute.fullPath;\n return {\n ...seoHead,\n meta: [\n {\n hid: \"ogLocale\",\n name: \"og:locale\",\n content: metaI18n.meta[0].content,\n },\n {\n hid: \"ogLocaleAlternate\",\n name: \"og:locale:alternate\",\n content: metaI18n.meta[1].content,\n },\n {\n hid: \"ogUrl\",\n name: \"og:url\",\n content: currentPath,\n },\n ],\n };\n },\n(...)\n```\n\nUnfortunately, I am facing `Cannot read property '$options' of undefined` error. It's strange for me, because I already used `export const $t = (sign) => Vue.prototype.$nuxt.$options.i18n.t(sign);` code in another js file. Anyone know why this error appears? You know the best way to translate global head options?\n\n========================================\n\nTop Answer:\nI think what you basically need here is a mixin.\n\n```\nexport default {\n title: $t(\"seoGlobal.title\"),\n meta: this.computedMeta,\n computed:{\n computedMeta(){\n return [....] // this contains the array of objects in meta\n }\n }\n methods:{\n yourMethod(sign){\n return this.$nuxt.$options.i18n.t(sign);\n }\n }\n};\n```\n\nthen just import it as a mixin in whatever file you need.\n\n========================================\n\nCode:\n```text\nimport Vue from \"vue\";\n\nexport const $t = (sign) => Vue.prototype.$nuxt.$options.i18n.t(sign);\n\nexport default {\n title: $t(\"seoGlobal.title\"),\n meta: [\n { charset: \"utf-8\" },\n { name: \"viewport\", content: \"width=device-width, initial-scale=1\" },\n {\n hid: \"description\",\n name: \"description\",\n content: $t(\"seoGlobal.description\"),\n },\n {\n hid: \"ogSiteName\",\n name: \"og:site_name\",\n content: \"Test Page\",\n },\n {\n hid: \"ogTitle\",\n name: \"og:title\",\n content: $t(\"seoGlobal.ogTitle\"),\n },\n (...)\n ],\n};\n```\n\n```text\nimport seoHead from \"~/constants/seoHead\";\n\nexport default {\n head() {\n const metaI18n = this.$nuxtI18nSeo();\n const currentPath = process.env.LP_URL + this.$router.currentRoute.fullPath;\n return {\n ...seoHead,\n meta: [\n {\n hid: \"ogLocale\",\n name: \"og:locale\",\n content: metaI18n.meta[0].content,\n },\n {\n hid: \"ogLocaleAlternate\",\n name: \"og:locale:alternate\",\n content: metaI18n.meta[1].content,\n },\n {\n hid: \"ogUrl\",\n name: \"og:url\",\n content: currentPath,\n },\n ],\n };\n },\n(...)\n```\n\n```text\nseoHead.js\n```\n\n```text\nindex.vue\n```\n\n```text\nCannot read property '$options' of undefined\n```\n\n```text\nexport const $t = (sign) => Vue.prototype.$nuxt.$options.i18n.t(sign);\n```\n\n```js\nexport default function() {\n return {\n title: $t(\"seoGlobal.title\"),\n // ...\n }\n}\n```\n\n```js\nreturn {\n ...seoHead(),\n // ...\n```\n\n```js\nconst $t = (sign) => Vue.prototype.$nuxt \n ? Vue.prototype.$nuxt.$options.i18n.t(sign)\n : sign\n```\n\n```text\nseoHead.js\n```\n\n```text\n$nuxt\n```\n\n```text\nVue\n```\n\n```text\n$t\n```\n\n```text\n$nuxt\n```\n\n```text\nindex.vue\n```\n\n```text\nhead\n```\n\n```text\nseoHead\n```\n\n```text\n$nuxt\n```\n\n```text\nseoHead\n```\n\n```text\nhead\n```\n\n```text\nhead\n```\n\n```text\nindex.vue\n```\n\n```js\nexport default {\n title: $t(\"seoGlobal.title\"),\n meta: this.computedMeta,\n computed:{\n computedMeta(){\n return [....] // this contains the array of objects in meta\n }\n }\n methods:{\n yourMethod(sign){\n return this.$nuxt.$options.i18n.t(sign);\n }\n }\n};\n```\n\n========================================\n\nComments:\n- I'm not too acquainted with Nuxt, but your error messages seems to indicate a race condition: `seoHead` is used before Nuxt's setup is complete, so `$nuxt` has not been defined (injected) yet when it is accessed in `$t`. Can you rule out that this is the case here?\n- @dr_barto It could be. I'm not so experienced in Nuxt lifecycle :/\n- Please check if you import `seoHead.js` somewhere else, and try to remove that import if you find any. It's unlikely, but .. well :)\n- Only in described file I imported `seoHead.js`\n- Maybe this workaround works for you: delay the execution of `$t` by changing `seoHead.js` to export a function which simply returns the object you are currently exporting. Then, in `index.vue`, just change the line `...seoHead` to `...seoHead()`.\n- @dr_barto It works\n- @dr_barto Can You give your response as answer, not comment? So I will sign It as problem resolver and You will get bouty :)","metadata":{"transformedAt":"2026-08-18T18:33:07.887Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":278,"estimatedTokens":1350}}693{"id":"stack-69141697","source":"stackoverflow","questionId":69141697,"title":"Unable to deploy nuxt app to digital ocean health checks","tags":["node.js","vue.js","deployment","nuxt.js","digital-ocean"],"text":"Title: Unable to deploy nuxt app to digital ocean health checks\nTags: node.js, vue.js, deployment, nuxt.js, digital-ocean\nSource: Stack Overflow\n\nQuestion:\nI created a simple & basic nuxt app then from the terminal, i did push it to github repo. then i did link my repo to digital ocean app functionality so it deploys it. The build is successful yet the launch doesn't launch and i get the following errors\n\n```\nDeploy Error: Health Checks\nCommon Causes\nApp is running slower than expected\nComponent Issues\napptest - failed to deploy\n```\n\nPlease note that i didn't configure the environnement variables, i left it to default settings. is it important to do so?\n\nhttps://i.sstatic.net/U5QVz.png\n\nEdit : here's nuxt js config\n\n```\nexport default {\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: 'apptest',\n htmlAttrs: {\n lang: 'en'\n },\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: '' },\n { name: 'format-detection', content: 'telephone=no' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\n ],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [\n ],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\n // https://go.nuxtjs.dev/bootstrap\n 'bootstrap-vue/nuxt',\n ],\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {\n }\n}\n```\n\nthe digital ocean log is stuck here\n\n```\n[appnuxt] [2021-09-11 10:47:59] yarn run v1.22.11\n[appnuxt] [2021-09-11 10:47:59] $ nuxt start\n[appnuxt] [2021-09-11 10:48:01] ℹ Listening on: http://localhost:8080/\n```\n\n========================================\n\nCode:\n```text\nDeploy Error: Health Checks\nCommon Causes\nApp is running slower than expected\nComponent Issues\napptest - failed to deploy\n```\n\n```text\nexport default {\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: 'apptest',\n htmlAttrs: {\n lang: 'en'\n },\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: '' },\n { name: 'format-detection', content: 'telephone=no' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\n ],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [\n ],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\n // https://go.nuxtjs.dev/bootstrap\n 'bootstrap-vue/nuxt',\n ],\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {\n }\n}\n```\n\n```text\n[appnuxt] [2021-09-11 10:47:59] yarn run v1.22.11\n[appnuxt] [2021-09-11 10:47:59] $ nuxt start\n[appnuxt] [2021-09-11 10:48:01] ℹ Listening on: http://localhost:8080/\n```\n\n```text\nnpm start -- --hostname 0.0.0.0 --port 8080\n```\n\n========================================\n\nComments:\n- Do you have some env variables? You don't need to set those if you don't have any. Also, is your app building successfully locally? Do you build it with `yarn build` and then `yarn start`?\n- Yes without a single problem !\n- What about the build command? Can you us your `nuxt.config.js` file please?\n- it's frustrating i keep getting errors .... yet i didn't edit the app at all. all i did is nuxt create the app then pushed it to github. after that i went do digital ocean to link the repo\n- @kissu check the post\n- @kissu anything????\n- Everything looks okay so far. Did you tried reaching `www.your-website.com:8080`?\n- @kissu yes , it says this site can't be reached\n- i solved the problem by opening a ticket. the support redirected me to this link digitalocean.com/community/questions/…","metadata":{"transformedAt":"2026-08-18T18:33:07.887Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":154,"estimatedTokens":1070}}694{"id":"stack-52845184","source":"stackoverflow","questionId":52845184,"title":"How can I access data in asyncData with Nuxt","tags":["vue.js","nuxt.js"],"text":"Title: How can I access data in asyncData with Nuxt\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm attempting to build a server-side sortable table with Nuxt, and I'd like to be able to specify the default sort column and direction in my Vue `data`, and access that in my `asyncData` function. Something like this:\n\n```\n\nexport default {\n async asyncData ({ $axios, params }) {\n const things = await $axios.$get(`/api/things`, {\n params: {\n sort_column: this.sortColumn,\n sort_ascending: this.sortAscending,\n }\n });\n return { things };\n },\n data () {\n return {\n sortColumn: 'created_at',\n sortAscending: true\n }\n },\n // ...\n}\n\n```\n\nBut it appears that `data` is not yet available, as `this.sortColumn` and `this.sortAscending` are not defined. How can I access these defaults when `asyncData` runs while also allowing them to be changed when the user interacts with the page. (Alternatively, what's a better way to structure this?)\n\nNote: This question was asked here, but the accepted answer is not relevant to this situation.\n\n========================================\n\nCode:\n```text\n<script>\nexport default {\n async asyncData ({ $axios, params }) {\n const things = await $axios.$get(`/api/things`, {\n params: {\n sort_column: this.sortColumn,\n sort_ascending: this.sortAscending,\n }\n });\n return { things };\n },\n data () {\n return {\n sortColumn: 'created_at',\n sortAscending: true\n }\n },\n // ...\n}\n</script>\n```\n\n```text\ndata\n```\n\n```text\nasyncData\n```\n\n```text\ndata\n```\n\n```text\nthis.sortColumn\n```\n\n```text\nthis.sortAscending\n```\n\n```text\nasyncData\n```\n\n```text\nasync asyncData ({ $axios, params }) {\n const sortColumn = 'created_at'\n const sortAscending = true\n const things = await $axios.$get(`/api/things`, {\n params: {\n sort_column: sortColumn,\n sort_ascending: this.sortAscending,\n }\n });\n return { things, sortColumn, sortAscending };\n },\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.887Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":97,"estimatedTokens":490}}695{"id":"stack-71884737","source":"stackoverflow","questionId":71884737,"title":"Why is the first class more important than the latter?","tags":["vue.js","nuxt.js","tailwind-css"],"text":"Title: Why is the first class more important than the latter?\nTags: vue.js, nuxt.js, tailwind-css\nSource: Stack Overflow\n\nQuestion:\n```\n\n```\n\nWhy does the above show margin `4 px` instead of margin `8 px`\nBecause the last class should be more important.\n\nI'm having a lot of trouble when writing an \"if\" in Vue.js because if writing normally New classes are always appended to the end.\n\n- NuxtJS 2.15.8\n\n- TailwindCSS 3.0.23\n\n- postcss 8.4.5\n\n========================================\n\nTop Answer:\nAfter some works with tailwind and some experiences with styled-components / styled-systems on ReactJS, you can actually force some classes with a custom breakpoint because breakpoints have more priority.\n\nI added this to my tailwind config; we can keep the same system mobile first oriented and add some more priority to properties:\n\n```\ntheme: {\n screens: {\n _: '0px',\n },\n},\n```\n\nYou can use this to define some higher priority properties:\n\n```\n_:text-blue // like lg:text-blue\n```\n\n========================================\n\nCode:\n```html\n<p class=\"mt-1 mt-2\"></p>\n```\n\n```text\n4 px\n```\n\n```text\n8 px\n```\n\n```html\n<button\n class=\"flex items-center w-auto p-4 text-center ...\"\n :class=\"[\n callToAction.types[color][variant], // here is the important part\n { 'opacity-50 cursor-not-allowed shadow-none': disabled },\n ]\"\n>\n Nice flexible button\n</button>\n```\n\n```text\ncn\n```\n\n```text\ntwMerge\n```\n\n```text\nclsx\n```\n\n```text\ntheme: {\n screens: {\n _: '0px',\n },\n},\n```\n\n```text\n_:text-blue // like lg:text-blue\n```\n\n```html\n<script src=\"https://unpkg.com/@tailwindcss/browser@4\"></script>\n\n<p class=\"pt-2 pt-1 w-40 h-20 bg-red-50 border-2\">pt-2 stronger</p>\n<p class=\"pt-1 pt-2 w-40 h-20 bg-red-50 border-2\">pt-2 stronger</p>\n\n<p class=\"pt-12 pt-1 w-40 h-20 bg-red-50 border-2\">pt-12 stronger</p>\n<p class=\"pt-1 pt-12 w-40 h-20 bg-red-50 border-2\">pt-12 stronger</p>\n\n<p class=\"pt-0.5 pt-2.5 w-40 h-20 bg-red-50 border-2\">pt-2.5 stronger</p>\n<p class=\"pt-2.5 pt-0.5 w-40 h-20 bg-red-50 border-2\">pt-2.5 stronger</p>\n\n<p class=\"pt-[0.5rem] pt-24 w-40 h-20 bg-red-50 border-2\">pt-[0.5rem] stronger</p>\n<p class=\"pt-24 pt-[0.5rem] w-40 h-20 bg-red-50 border-2\">pt-[0.5rem] stronger</p>\n```\n\n```css\n.pt-0\\.5 {\n padding-top: calc(var(--spacing) * .5);\n}\n\n.pt-1 {\n padding-top: calc(var(--spacing) * 1);\n}\n\n.pt-2 {\n padding-top: calc(var(--spacing) * 2);\n}\n\n.pt-2\\.5 {\n padding-top: calc(var(--spacing) * 2.5);\n}\n\n.pt-12 {\n padding-top: calc(var(--spacing) * 12);\n}\n\n.pt-24 {\n padding-top: calc(var(--spacing) * 24);\n}\n\n.pt-\\[0\\.5rem\\] {\n padding-top: .5rem;\n}\n```\n\n```text\npt-{number}\n```\n\n```text\npt-<number>\n```\n\n```text\npt-[custom value]\n```\n\n```text\npt-{number}\n```\n\n```text\npt-{number}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.887Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":157,"estimatedTokens":677}}696{"id":"stack-75971050","source":"stackoverflow","questionId":75971050,"title":"Nuxt 3 ignores TypeScript errors when saving the code","tags":["typescript","vue.js","nuxt.js"],"text":"Title: Nuxt 3 ignores TypeScript errors when saving the code\nTags: typescript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a problem. When there is a TypeScript error in the code, there is an error in the IDE, but I anyways can save it and run in the browser. Is it okay?\n\nHere is the code:\n\n```\n\nconst a = ref(5);\n\n```\n\nI tried export default and export default defineComponent(), but it didn't help.\n\nHere is the screenshoot of my IDE\nhttps://i.sstatic.net/UHOrq.png\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\" setup>\nconst a = ref<string>(5);\n</script>\n```\n\n```text\ntypescript: {\n typeCheck: true,\n}\n```\n\n```text\nvue-tsc\n```\n\n```text\ntypescript\n```\n\n```text\ndevDependencies\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- typescript doesn't run in the browser, it's always transpiled to javascript beforehand, that's why you can break typescript specific rules and still run your code ok. it's up to you as a developer whether you feel this is an ok practice, though most would say it's bad practice to .\n- @yoduh, yes, i mean when i save the code, it compiles to JS without giving any errors in the terminal. If i do this with React or just Vue 3, it would give an error, but Nuxt is not doing it, it's working with errors without problems.","metadata":{"transformedAt":"2026-08-18T18:33:07.887Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":56,"estimatedTokens":332}}697{"id":"stack-68359686","source":"stackoverflow","questionId":68359686,"title":"No layout folder in a Nuxt Project","tags":["vue.js","nuxt.js"],"text":"Title: No layout folder in a Nuxt Project\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhenever I was creating a new Nuxt project, there were directories like: `components`, `pages`, `static`, `store`, `.nuxt`, `node_modules` but there are no `layouts` and other directories as of right now.\n\nHow can I fix that?\n\n========================================\n\nCode:\n```text\ncomponents\n```\n\n```text\npages\n```\n\n```text\nstatic\n```\n\n```text\nstore\n```\n\n```text\n.nuxt\n```\n\n```text\nnode_modules\n```\n\n```text\nlayouts\n```\n\n```text\n.nuxt\n```\n\n```text\nnode_modules\n```\n\n```text\nnode_modules\n```\n\n```text\nyarn\n```\n\n```text\nnpx create-nuxt-app <project-name>\n```\n\n========================================\n\nComments:\n- just create them manually by `mkdir` or GUI\n- So in the latest release of nuxt , when you are creating a nuxt project there is no layout folder?\n- Yep, the point is to make a gradual learning of Nuxt, without giving to much directories at the same time. More info should be coming by the start of August. Feel free to create a new `layouts` directory and move forward!\n- Probably aren't too related but i struggled at first when creating a layouts folder with default.vue. Just quit the server and `npm run dev`\n- @MichaelHalim as with any major configuration change of a project, you indeed need a server restart.","metadata":{"transformedAt":"2026-08-18T18:33:07.887Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":68,"estimatedTokens":332}}698{"id":"stack-67032816","source":"stackoverflow","questionId":67032816,"title":"IntersectionObserver doesn't work while using nuxt-link","tags":["vue.js","nuxt.js","intersection-observer"],"text":"Title: IntersectionObserver doesn't work while using nuxt-link\nTags: vue.js, nuxt.js, intersection-observer\nSource: Stack Overflow\n\nQuestion:\nI use `IntersectionObserver` to add a class whenever a element is visible so I can add a fade-in/out animation in my nuxt project. It work well but if I change the page with `nuxt-link` (or go back to the same page) IntersectionObserver doesn't add the class (so everything is `opacity: 0`)\n\nHere is the Intersection observer script in my main nuxt layout (default.vue)\n\n```\nmounted() {\n\n const animate = document.querySelectorAll('.animate');\n\n const observer = new IntersectionObserver(entries => {\n entries.forEach(entry => {\n if (entry.isIntersecting) {\n entry.target.classList.add('in')\n } else {\n entry.target.classList.remove('in')\n }\n })\n }, {\n rootMargin: '-15px',\n })\n\n animate.forEach(entry => {\n observer.observe(entry);\n });\n\n},\n```\n\nI would like this code to run everytime I change page with nuxt-link\n\n========================================\n\nTop Answer:\nI suggest **not to use the dom directly** instead, use `template refs` to access the dom, just in case you have the *`same ref for more than one element`* read through this discussion Link\n\nIf you try to **observe the `NuxtLink` directly with ref** the observer is not detecting the NuxtLink as an element so it will crash to fix that *`enclose it with div`*, so that it works.\n\n```\n\nconst root = ref(null);\nconst target = ref(null);\n\nonMounted(() => {\n const observer = new IntersectionObserver((entries) => {\n entries.forEach(\n (entry) => {\n entry.target.classList.toggle(\"show\", entry.isIntersecting);\n },\n {\n threshold: 0.5,\n }\n );\n });\n\n target.value.forEach((card) => {\n observer.observe(card);\n });\n});\n\n \n Got blog\n\n \n \n Go to blog\n \n \n show card\n \n \n Show Card\n \n \n \n\n```\n\n========================================\n\nCode:\n```text\nmounted() {\n\n const animate = document.querySelectorAll('.animate');\n\n const observer = new IntersectionObserver(entries => {\n entries.forEach(entry => {\n if (entry.isIntersecting) {\n entry.target.classList.add('in')\n } else {\n entry.target.classList.remove('in')\n }\n })\n }, {\n rootMargin: '-15px',\n })\n\n animate.forEach(entry => {\n observer.observe(entry);\n });\n\n},\n```\n\n```text\nIntersectionObserver\n```\n\n```text\nnuxt-link\n```\n\n```text\nopacity: 0\n```\n\n```text\ncomputed: {\n routeName() {\n return this.$route.name;\n }\n},\n\nwatch: {\n routeName: {\n immediate: true,\n handler() {\n // Bind observer here\n },\n },\n},\n```\n\n```text\nthis.$route.name\n```\n\n```text\nimmediate:true\n```\n\n```text\ndeep\n```\n\n```text\n$route\n```\n\n```text\n<script setup>\nconst root = ref(null);\nconst target = ref(null);\n\nonMounted(() => {\n const observer = new IntersectionObserver((entries) => {\n entries.forEach(\n (entry) => {\n entry.target.classList.toggle(\"show\", entry.isIntersecting);\n },\n {\n threshold: 0.5,\n }\n );\n });\n\n target.value.forEach((card) => {\n observer.observe(card);\n });\n});\n</script>\n\n<template ref=\"root\">\n <div>\n <NuxtLink to=\"/blogs\" class=\"mb-60\">Got blog</NuxtLink>\n\n <div v-for=\"i in 1\" class=\"flex flex-col\">\n <div\n ref=\"target\"\n class=\"card p-10 border-2 border-black self-start rounded-xl bg-red-400\"\n >\n <NuxtLink to=\"/blogs\">Go to blog</NuxtLink>\n </div>\n <div\n ref=\"target\"\n class=\"card p-10 border-2 border-black self-start rounded-xl bg-red-400\"\n >\n show card\n </div>\n <div\n ref=\"target\"\n class=\"card p-10 border-2 border-black self-start rounded-xl bg-red-400\"\n >\n Show Card\n </div>\n </div>\n </div>\n</template>\n```\n\n```text\ntemplate refs\n```\n\n```text\nsame ref for more than one element\n```\n\n```text\nNuxtLink\n```\n\n```text\nenclose it with div\n```\n\n========================================\n\nComments:\n- Setting IntersectionObserver on pages instead of layout worked juste fine thank you very much :)\n- Perfect! Didn't even have to use my hacky workaround in the end then! I do wonder what Nuxt is doing in the background to dispose of the observer within layouts when route changes. Happy to have helped :)","metadata":{"transformedAt":"2026-08-18T18:33:07.887Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":226,"estimatedTokens":1049}}699{"id":"stack-61902788","source":"stackoverflow","questionId":61902788,"title":"Is there a way to redirect a NuxtJs application using Express server?","tags":["express","nuxt.js"],"text":"Title: Is there a way to redirect a NuxtJs application using Express server?\nTags: express, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a NuxtJs application initialized with Express server using `npx create-nuxt-app `. It is set for server-side rendering.\n\nExpress has access to NuxtJs middleware like so. ( Which comes by default when Nuxt app is created )\n\n```\napp.use(nuxt.render)\n```\n\nNow I have created a different route file in server side that handles API routes. This route works as I can access data using Axios. I have added this route right before the above code, like this. ( API routes don't work if it is added after )\n\n```\napp.use('/api', apiRoutes)\napp.use(nuxt.render)\n```\n\nThere is a route where, after some operation, I need to redirect the application to another page. I tried using `res.redirect('/some-route')`, which is an Express way for redirection but that didn't work.\n\nAm I missing something here? Is there some other way we do redirection from server side in Nuxt application that I'm totally unaware of?\n\n========================================\n\nCode:\n```text\napp.use(nuxt.render)\n```\n\n```text\napp.use('/api', apiRoutes)\napp.use(nuxt.render)\n```\n\n```text\nnpx create-nuxt-app <project-name>\n```\n\n```text\nres.redirect('/some-route')\n```\n\n```js\nres.writeHead(301, { Location: url })\nres.end()\n```\n\n========================================\n\nComments:\n- Have you found a solution for this?\n- You could use a middleware. In the middleware, use context api for redirect.","metadata":{"transformedAt":"2026-08-18T18:33:07.887Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":54,"estimatedTokens":375}}700{"id":"stack-73849290","source":"stackoverflow","questionId":73849290,"title":"Three JS object does not load in Nuxt 3 when navigating between pages","tags":["vue.js","three.js","nuxt.js","lifecycle","vue-composition-api"],"text":"Title: Three JS object does not load in Nuxt 3 when navigating between pages\nTags: vue.js, three.js, nuxt.js, lifecycle, vue-composition-api\nSource: Stack Overflow\n\nQuestion:\nLet me start by saying I have a lot to learn.\nI hate asking for help, but I have went through pages and pages looking for an answer with no luck.\n\nI am sure the issue is simple, but can someone please explain to me what I am doing wrong? My Three JS atom loads just fine. I dont have any issue until i navigate to a different page (NuxtLink) and then return to this page.\n\nIt throws this error:\n\nUncaught (in promise) TypeError: Cannot read properties of null\n(reading 'width')\nat new WebGLRenderer (three.module.js:26639:23)\nat Atom.vue:64:1\nat hook.__wdc.hook.__wdc (runtime-core.esm-bundler.js:2626:20)\nat callWithErrorHandling (runtime-core.esm-bundler.js:155:22)\nat callWithAsyncErrorHandling (runtime-core.esm-bundler.js:164:21)\nat hook.__weh.hook.__weh (runtime-core.esm-bundler.js:2684:29)\nat flushPostFlushCbs (runtime-core.esm-bundler.js:341:32)\nat flushJobs (runtime-core.esm-bundler.js:395:9)\n\nWhich to my understanding means that the canvas isnt loading ? I even tried using the options API instead of the composition API, but I get the same issue. Ive tried using onActivated & KeepAlive as you can see and neither of those work too.\n\n```\n\n import * as THREE from 'three'\n\n onActivated(() => {\n // Canvas\n const canvas = document.querySelector('canvas.webgl')\n // Sizes\n const sizes = {\n width: 300,\n height: 300\n }\n const pixelRatio = window.devicePixelRatio\n\n /* Base */\n // Scene\n const scene = new THREE.Scene()\n\n /* Props */\n // Plane Background\n const backgroundPlane = new THREE.PlaneGeometry(50, 50, 4, 4)\n const backgroundMaterial = new THREE.MeshStandardMaterial({ emissive: \"#000505\", roughness:0.1, metalness: 1 })\n const background = new THREE.Mesh(backgroundPlane, backgroundMaterial)\n background.position.z = -5\n scene.add(background)\n\n // Atom Group\n const atom = new THREE.Group()\n scene.add(atom)\n atom.position.z = -2\n\n const protonSphere = new THREE.SphereGeometry(.3, 16, 16)\n const protonMaterial = new THREE.MeshStandardMaterial({ emissive: \"#080E54\", roughness:0.4, metalness: 0.9 })\n const proton = new THREE.Mesh(protonSphere, protonMaterial)\n atom.add(proton)\n\n const electronCloudSphere = new THREE.SphereGeometry(2, 32, 32)\n const electronCloudMaterial = new THREE.MeshPhysicalMaterial({ opacity: .2, transparent: true, reflectivity:0, side:THREE.DoubleSide, roughness:0.5, metalness: 0, ior: 2, thickness: 2, transmission: 1 })\n const electronCloud = new THREE.Mesh(electronCloudSphere, electronCloudMaterial)\n atom.add(electronCloud)\n\n const electronSphere = new THREE.SphereGeometry(.1, 16, 16)\n const electronMaterial = new THREE.MeshStandardMaterial({ emissive: \"#2FFFFF\", roughness:0, metalness: 0.9 })\n const electron = new THREE.Mesh(electronSphere, electronMaterial)\n const radius = 1.5\n let theta = Math.random() * Math.PI * 2\n let phi = Math.random() * Math.PI\n const x = radius * Math.sin(theta)\n const z = radius * Math.cos(theta)\n const y = radius * Math.cos(phi)\n electron.position.set(x, y, z)\n atom.add(electron)\n\n const pointLight = new THREE.PointLight(\"#B7DBFF\", 1, 5)\n pointLight.position.z = 1\n scene.add(pointLight)\n\n /* Camera & Controls */\n // Base camera\n const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100)\n camera.position.z = 3\n scene.add(camera)\n\n /* Renderer */\n const renderer = new THREE.WebGLRenderer({\n canvas,\n antialias: true,\n })\n renderer.setSize(sizes.width, sizes.height)\n renderer.setPixelRatio(Math.min(pixelRatio, 2))\n \n /* Animate */\n const clock = new THREE.Clock()\n let time = 0\n\n const tick = () =>\n {\n const elapsedTime = clock.getElapsedTime()\n const deltaTime = elapsedTime - time\n time = elapsedTime\n\n // Animations\n let shake = (Math.random() * 0.015)\n proton.rotateX(.5)\n proton.position.set(shake, shake, 0)\n atom.rotateX(.01 * Math.random())\n atom.rotateY(.02 * Math.random())\n atom.rotateZ(.04 * Math.random())\n\n // Render\n renderer.render(scene, camera)\n\n // Call tick again on the next frame\n window.requestAnimationFrame(tick)\n }\n tick()\n })\n\n \n \n \n\n```\n\n========================================\n\nTop Answer:\nFinally figure it out.\n\n```\nconst webgl = ref(null)\n\nonMounted(() => {\n// Canvas\nconst canvas = webgl.value\n```\n\nUsing template refs seems to fix my issue.\n\n```\n\n \n \n \n\n```\n\nNot sure if this is the best solution... but it seems to work!\n\n========================================\n\nCode:\n```html\n<script setup>\n import * as THREE from 'three'\n\n onActivated(() => {\n // Canvas\n const canvas = document.querySelector('canvas.webgl')\n // Sizes\n const sizes = {\n width: 300,\n height: 300\n }\n const pixelRatio = window.devicePixelRatio\n\n /* Base */\n // Scene\n const scene = new THREE.Scene()\n\n /* Props */\n // Plane Background\n const backgroundPlane = new THREE.PlaneGeometry(50, 50, 4, 4)\n const backgroundMaterial = new THREE.MeshStandardMaterial({ emissive: \"#000505\", roughness:0.1, metalness: 1 })\n const background = new THREE.Mesh(backgroundPlane, backgroundMaterial)\n background.position.z = -5\n scene.add(background)\n\n // Atom Group\n const atom = new THREE.Group()\n scene.add(atom)\n atom.position.z = -2\n\n const protonSphere = new THREE.SphereGeometry(.3, 16, 16)\n const protonMaterial = new THREE.MeshStandardMaterial({ emissive: \"#080E54\", roughness:0.4, metalness: 0.9 })\n const proton = new THREE.Mesh(protonSphere, protonMaterial)\n atom.add(proton)\n\n const electronCloudSphere = new THREE.SphereGeometry(2, 32, 32)\n const electronCloudMaterial = new THREE.MeshPhysicalMaterial({ opacity: .2, transparent: true, reflectivity:0, side:THREE.DoubleSide, roughness:0.5, metalness: 0, ior: 2, thickness: 2, transmission: 1 })\n const electronCloud = new THREE.Mesh(electronCloudSphere, electronCloudMaterial)\n atom.add(electronCloud)\n\n const electronSphere = new THREE.SphereGeometry(.1, 16, 16)\n const electronMaterial = new THREE.MeshStandardMaterial({ emissive: \"#2FFFFF\", roughness:0, metalness: 0.9 })\n const electron = new THREE.Mesh(electronSphere, electronMaterial)\n const radius = 1.5\n let theta = Math.random() * Math.PI * 2\n let phi = Math.random() * Math.PI\n const x = radius * Math.sin(theta)\n const z = radius * Math.cos(theta)\n const y = radius * Math.cos(phi)\n electron.position.set(x, y, z)\n atom.add(electron)\n\n const pointLight = new THREE.PointLight(\"#B7DBFF\", 1, 5)\n pointLight.position.z = 1\n scene.add(pointLight)\n\n /* Camera & Controls */\n // Base camera\n const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100)\n camera.position.z = 3\n scene.add(camera)\n\n /* Renderer */\n const renderer = new THREE.WebGLRenderer({\n canvas,\n antialias: true,\n })\n renderer.setSize(sizes.width, sizes.height)\n renderer.setPixelRatio(Math.min(pixelRatio, 2))\n \n /* Animate */\n const clock = new THREE.Clock()\n let time = 0\n\n const tick = () =>\n {\n const elapsedTime = clock.getElapsedTime()\n const deltaTime = elapsedTime - time\n time = elapsedTime\n\n // Animations\n let shake = (Math.random() * 0.015)\n proton.rotateX(.5)\n proton.position.set(shake, shake, 0)\n atom.rotateX(.01 * Math.random())\n atom.rotateY(.02 * Math.random())\n atom.rotateZ(.04 * Math.random())\n\n // Render\n renderer.render(scene, camera)\n\n // Call tick again on the next frame\n window.requestAnimationFrame(tick)\n }\n tick()\n })\n\n</script>\n\n<template>\n <div class=\"canvas-wrapper\">\n <canvas id=\"atom\" class=\"webgl\"></canvas>\n </div>\n</template>\n```\n\n```text\ndocument\n```\n\n```text\ndocument\n```\n\n```text\nmounted\n```\n\n```text\nconst webgl = ref(null)\n\nonMounted(() => {\n// Canvas\nconst canvas = webgl.value\n```\n\n```text\n<template>\n <div class=\"canvas-wrapper\">\n <canvas ref=\"webgl\" id=\"atom\" class=\"webgl\"></canvas>\n </div>\n</template>\n```\n\n========================================\n\nComments:\n- Thanks for the effort put into the question (I've edited for some code highlight) and well played on the research before posting. I've posted an answer providing more details as of why you had this issue.","metadata":{"transformedAt":"2026-08-18T18:33:07.887Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":296,"estimatedTokens":2090}}701{"id":"stack-68852575","source":"stackoverflow","questionId":68852575,"title":"Vue editing v-data that has been passed to a component as a prop","tags":["javascript","vue.js","vuejs2","nuxt.js"],"text":"Title: Vue editing v-data that has been passed to a component as a prop\nTags: javascript, vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt `2.15.3`.\n\nIn my app, users can set up Questions that their customers can answer, and the questions can be a variety of types, one of them being a Multiple Choice question. These types of questions have a title, as well as multiple answer options that people can choose from.\n\nOn my Questions page, I list all of the User's questions, and I want to allow them to edit any question, but I'm having some trouble figuring out how to do that exactly, at least when it comes to editing multiple choice questions. As it stands currently, I have a `EditQuestion` component to which I pass a `question` prop from my `QuestionCard` component, the prop just being the details of the question which is stored in Vuex.\n\nMy current (simplified for SO) version of the `EditQuestion` component:\n\n```\n\n \n \n \n \n \n\n export default {\n props: {\n question: {}\n },\n data() {\n return {\n questionTitle: this.question.title,\n questionOptions: this.question.options\n }\n },\n methods: {\n updateQuestion() {\n // Call the API with the new question details\n }\n }\n }\n\n```\n\nIf I were only editing question titles, this works great. However, my issue comes from the options. If I try to update one, Vuex warns me about mutating the store state outside of a mutation, and it warns me all the same even if I clone `question.options`, for example by doing `questionOptions: Object.assign({}, this.question.options)` or `questionOptions: {...this.question.options}.` The part that confuses me is why Vuex doesn't complain when I modify the `questionTitle` data object, and only when editing the questionOptions?\n\nFor reference if it's relevant, `question.title` is just a simple string, while `question.options` is an object that looks something like this:\n\n```\n{\n \"0\": {\n \"id\": 0,\n \"content\": \"Option 1\"\n },\n \"1\": {\n \"id\": 1,\n \"content\": \"Option 2\"\n }\n}\n```\n\nWhat is the best way for me to allow people to edit the Multiple Choice question options?\n\n========================================\n\nTop Answer:\nTry making a local copy of the `question` object and do all the updates on that local copy only, something like this:\n\n```\n\n export default {\n props: {\n question: {}\n },\n data() {\n return {\n localCopyOfQuestion: JSON.parse(JSON.stringify(this.question)),\n questionTitle: this.localCopyOfQuestion.title,\n questionOptions: this.localCopyOfquestion.options\n }\n },\n methods: {\n updateQuestion() {\n // Call the API with the new question details\n }\n }\n }\n\n```\n\n========================================\n\nCode:\n```html\n<template>\n <input v-model=\"questionTitle\" type=\"text\">\n <div v-if=\"question.type === 'multiple_choice'\">\n <input v-for=\"option in questionOptions\" v-model=\"option.content\" type=\"text\">\n </div>\n <button @click.prevent=\"updateQuestion\"></button>\n</template>\n\n<script>\n export default {\n props: {\n question: {}\n },\n data() {\n return {\n questionTitle: this.question.title,\n questionOptions: this.question.options\n }\n },\n methods: {\n updateQuestion() {\n // Call the API with the new question details\n }\n }\n }\n</script>\n```\n\n```json\n{\n \"0\": {\n \"id\": 0,\n \"content\": \"Option 1\"\n },\n \"1\": {\n \"id\": 1,\n \"content\": \"Option 2\"\n }\n}\n```\n\n```text\n2.15.3\n```\n\n```text\nEditQuestion\n```\n\n```text\nquestion\n```\n\n```text\nQuestionCard\n```\n\n```text\nEditQuestion\n```\n\n```text\nquestion.options\n```\n\n```text\nquestionOptions: Object.assign({}, this.question.options)\n```\n\n```text\nquestionOptions: {...this.question.options}.\n```\n\n```text\nquestionTitle\n```\n\n```text\nquestion.title\n```\n\n```text\nquestion.options\n```\n\n```js\nexport default {\n data() {\n return {\n questionTitle: this.question.title,\n questionOptions: JSON.parse(JSON.stringify(this.question.options))\n }\n }\n}\n```\n\n```text\nString\n```\n\n```text\nNumber\n```\n\n```text\nBigInt\n```\n\n```text\nBoolean\n```\n\n```text\nundefined\n```\n\n```text\nnull\n```\n\n```text\nArray\n```\n\n```text\nMap\n```\n\n```text\nWeakMap\n```\n\n```text\nSet\n```\n\n```text\nWeakSet\n```\n\n```text\nthis.question.title\n```\n\n```text\nString\n```\n\n```text\nthis.question.options\n```\n\n```text\nArray\n```\n\n```text\nquestionOptions\n```\n\n```text\nquestionOptions\n```\n\n```text\nthis.question.options\n```\n\n```text\nthis.question.options\n```\n\n```text\nObject.assign()\n```\n\n```text\n<script>\n export default {\n props: {\n question: {}\n },\n data() {\n return {\n localCopyOfQuestion: JSON.parse(JSON.stringify(this.question)),\n questionTitle: this.localCopyOfQuestion.title,\n questionOptions: this.localCopyOfquestion.options\n }\n },\n methods: {\n updateQuestion() {\n // Call the API with the new question details\n }\n }\n }\n</script>\n```\n\n```text\nquestion\n```\n\n========================================\n\nComments:\n- Did you tried to use Lodash's `cloneDeep` method? Because it is maybe complaining because you are trying to modify a reference of the object. Rather clone all the object and update the copy rather than the reference. There is not Vuex shown here, but usually this kind of thing is nice when done in a Vuex action directly.","metadata":{"transformedAt":"2026-08-18T18:33:07.887Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":296,"estimatedTokens":1302}}702{"id":"stack-66375900","source":"stackoverflow","questionId":66375900,"title":"Nuxt plugin imports abuse vendors","tags":["javascript","vue.js","webpack","datepicker","nuxt.js"],"text":"Title: Nuxt plugin imports abuse vendors\nTags: javascript, vue.js, webpack, datepicker, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to use `vuejs-datepicker` in a nuxt app, everything is done by nuxt plugin usage standarts.\n\n`plugins/vue-datepicker.js`\n\n```\nimport Vue from 'vue'\nimport Datepicker from 'vuejs-datepicker'\n\nVue.component('Datepicker', Datepicker)\n```\n\n`nuxt.config.js`\n\n```\nplugins: [\n { src: '~/plugins/vue-datepicker', ssr: false }\n],\n```\n\nBut even when it is not used I am getting its dist uploaded in the `vendors/app....js` after the build. How can make nuxt create a separate chunk for it and import that chunk only in the pages which are using it?\n\nhttps://i.sstatic.net/V4L8a.png\n\n========================================\n\nTop Answer:\nSo yeah, there is basically a feature request open for this kind of use-case.\n\nBut looking at the Nuxt lifecycle, it looks like the plugins are imported even before the VueJS instance is done. So, you cannot lazy load it if it's done ahead of Vue.\n\nBut, you can totally import `vuejs-datepicker` on the page itself, rather than on the whole project. This may be enough\n\n```\nimport Datepicker from 'vuejs-datepicker' // then simply use `Datepicker` in the code below\n```\n\nIf it's not, you can maybe try this solution: https://github.com/nuxt/nuxt.js/issues/2727#issuecomment-362213022\n\n```\n// plugins/my-plugin\nimport Vue from 'vue'\nexport default () => {\n // ...\n Vue.use(....)\n}\n\n// adminLayouts\nimport myPlugin from '~/plugins/my-plugin'\nexport default {\n created() {\n myPlugin()\n }\n}\n```\n\nSo, the downside is that you have to import the component each time that you need it rather than having it globally but it also allows you to load it only on the concerned pages too and have it chunked per page/component.\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\nimport Datepicker from 'vuejs-datepicker'\n\nVue.component('Datepicker', Datepicker)\n```\n\n```text\nplugins: [\n { src: '~/plugins/vue-datepicker', ssr: false }\n],\n```\n\n```text\nvuejs-datepicker\n```\n\n```text\nplugins/vue-datepicker.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nvendors/app....js\n```\n\n```text\ncomponents: {\n Datepicker: () => import('vue-datepicker')\n}\n```\n\n```text\nvendor\n```\n\n```text\ndocument is not defined\n```\n\n```text\n<client-only>\n```\n\n```js\nimport Datepicker from 'vuejs-datepicker' // then simply use `Datepicker` in the code below\n```\n\n```js\n// plugins/my-plugin\nimport Vue from 'vue'\nexport default () => {\n // ...\n Vue.use(....)\n}\n\n// adminLayouts\nimport myPlugin from '~/plugins/my-plugin'\nexport default {\n created() {\n myPlugin()\n }\n}\n```\n\n```text\nvuejs-datepicker\n```\n\n```text\nasync mounted() {\n const Datepicker = await import('vuejs-datepicker');\n Vue.use(Datepicker);\n}\n```\n\n```text\nwindow\n```\n\n```text\nVue.use()\n```\n\n```text\nVue.use(MyPlugin.default)\n```\n\n========================================\n\nComments:\n- With regular import, I was getting a `document not defined` error even after wrapping it in `client-only` tag. But I think that is unrelated, anyway thanks for your answe!","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":160,"estimatedTokens":770}}703{"id":"stack-65061266","source":"stackoverflow","questionId":65061266,"title":"How do I change the vuetify theme background color","tags":["vue.js","sass","nuxt.js","vuetify.js"],"text":"Title: How do I change the vuetify theme background color\nTags: vue.js, sass, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nThe default vuetify themes have a very limited amount of properties to tweak.\n\n```\ndark: {\n primary: '#3739FF',\n accent: '#101721',\n secondary: colors.amber.darken3,\n info: colors.teal.lighten1,\n warning: colors.amber.base,\n error: colors.deepOrange.accent4,\n success: colors.green.accent3\n}\n```\n\nI want to have control over all the background colors.\n\nI tried the answer from Dmitry Kaltovich\n\nHow To change theme colors on Nuxt/Vuetify starter template\n\nBy having a custom scss file like this\n\n```\n@import '~vuetify/src/styles/styles.sass';\n\n$material-dark: map-merge(\n $material-dark,\n (\n background: map-get($blue, 'lighten-5'),\n )\n);\n```\n\nand my nuxt config like this\n\n```\nvuetify: {\n treeShake: true,\n customVariables: ['~/assets/scss/vuetify.scss'],\n theme: {\n dark: true,\n themes: {\n options: {customProperties: true},\n dark: {\n primary: '#3739FF',\n accent: '#101721',\n secondary: colors.amber.darken3,\n info: colors.teal.lighten1,\n warning: colors.amber.base,\n error: colors.deepOrange.accent4,\n success: colors.green.accent3\n }\n }\n }\n},\n```\n\nBut it does not work.\n\nI'm using\n\n```\n\"nuxt\": \"^2.14.6\",\n\"@nuxtjs/vuetify\": \"^1.11.2\",\n\"sass\": \"^1.29.0\",\n\"sass-loader\": \"^7.3.1\"\n\"fibers\": \"^5.0.0\",\n\"node-sass\": \"^5.0.0\",\n```\n\n========================================\n\nCode:\n```text\ndark: {\n primary: '#3739FF',\n accent: '#101721',\n secondary: colors.amber.darken3,\n info: colors.teal.lighten1,\n warning: colors.amber.base,\n error: colors.deepOrange.accent4,\n success: colors.green.accent3\n}\n```\n\n```text\n@import '~vuetify/src/styles/styles.sass';\n\n$material-dark: map-merge(\n $material-dark,\n (\n background: map-get($blue, 'lighten-5'),\n )\n);\n```\n\n```text\nvuetify: {\n treeShake: true,\n customVariables: ['~/assets/scss/vuetify.scss'],\n theme: {\n dark: true,\n themes: {\n options: {customProperties: true},\n dark: {\n primary: '#3739FF',\n accent: '#101721',\n secondary: colors.amber.darken3,\n info: colors.teal.lighten1,\n warning: colors.amber.base,\n error: colors.deepOrange.accent4,\n success: colors.green.accent3\n }\n }\n }\n},\n```\n\n```text\n\"nuxt\": \"^2.14.6\",\n\"@nuxtjs/vuetify\": \"^1.11.2\",\n\"sass\": \"^1.29.0\",\n\"sass-loader\": \"^7.3.1\"\n\"fibers\": \"^5.0.0\",\n\"node-sass\": \"^5.0.0\",\n```\n\n```text\n/* Example of `~assets/scss/vuetify.scss` */\n\n@import '~vuetify/src/styles/styles.sass';\n\n// theme to override, same applies for $material-light\n$material-dark: map-merge(\n $material-dark,\n (\n 'background': rgb(130, 130, 130),\n 'text': (\n 'primary': map-get($grey, 'lighten-2'),\n ),\n 'calendar': (\n background-color: red,\n ),\n )\n);\n```\n\n```js\nvuetify: {\n treeShake: true,\n customVariables: ['~/assets/scss/vuetify.scss'],\n theme: {\n dark: true,\n themes: {\n options: { customProperties: true },\n dark: {\n header: '#3739FF',\n footer: '#101721'\n },\n },\n },\n },\n```\n\n```text\nsass-loader\n```\n\n```text\ncustomVariables:\n```\n\n```text\nnpm install -D sass-loader@8\n```\n\n```text\nsass-loader\n```\n\n```text\nvuetify.scss\n```\n\n```text\n$material-dark\n```\n\n```text\nnode_modules/vuetify/src/styles/settings/_dark.scss\n```\n\n```text\nnode_modules/vuetify/src/styles/settings/_colors.scss\n```\n\n```text\nmap-get\n```\n\n```text\n_dark.scss\n```\n\n```text\nvuetify.theme.themes.dark\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nprimary, secondary, accent, info, warning, error, success\n```\n\n```text\nheader, footer, etc.\n```\n\n```text\ncolor/background/background-color\n```\n\n```text\n<v-btn color=\"header\" />\n```\n\n```text\n<div class=\"primary\" />\n```\n\n```text\n<div class=\"footer\" />\n```\n\n```text\n<div class=\"primary--text\" />\n```\n\n```text\n<div class=\"header--text\" />\n```\n\n```text\n<div class=\"header lighten-2\" />\n```\n\n```text\nprimary, success, error etc.\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":28,"totalLines":256,"estimatedTokens":1008}}704{"id":"stack-67983753","source":"stackoverflow","questionId":67983753,"title":"Contentful API: How to render entry-hyperlink","tags":["nuxt.js","contentful"],"text":"Title: Contentful API: How to render entry-hyperlink\nTags: nuxt.js, contentful\nSource: Stack Overflow\n\nQuestion:\nI'm trying to render the Contentful `Document` to html, using rich-text-html-renderer. However, if the richtext contains nodes of the type `entry-hyperlink`, this just renders out like this:\n`type: entry-hyperlink id: QUfIK1T2dFDnubS5Ztc9N`\n\nAccording to the documentation you'll need to pass an options object to the `documentToHtmlString`.\nBut how do I do an async call within this render method to get the actual Contentful entry for this id?\n\nIn my case I am trying to do this within a Vue component in a Nuxt environment.\n\n========================================\n\nCode:\n```text\nDocument\n```\n\n```text\nentry-hyperlink\n```\n\n```text\n<span>type: entry-hyperlink id: QUfIK1T2dFDnubS5Ztc9N</span>\n```\n\n```text\ndocumentToHtmlString\n```\n\n```text\n<template>\n <!-- eslint-disable-next-line vue/no-v-html -->\n <div class=\"text\" v-html=\"html\"></div>\n</template>\n<script lang=\"ts\">\nimport { computed, defineComponent, useAsync } from '@nuxtjs/composition-api';\nimport { Block, INLINES, Inline } from '@contentful/rich-text-types';\nimport {\n documentToHtmlString,\n Options,\n} from '@contentful/rich-text-html-renderer';\nimport { IText } from '~/types/generated/contentful';\nimport useContentful from '~/plugins/contentful';\n\nexport default defineComponent({\n props: {\n entry: {\n type: Object as () => IText,\n required: true,\n },\n },\n setup(props) {\n const { client } = useContentful();\n const text = useAsync(() => client.getEntry<IText>(props.entry.sys.id));\n\n const html = computed(() => {\n if (text.value) {\n const options: Partial<Options> = {\n renderNode: {\n [INLINES.ENTRY_HYPERLINK]: (node: Inline | Block) => {\n return `<a href=\"/${node.data.target.fields.slug}\">${node.content[0].value}</a>`;\n },\n },\n };\n return documentToHtmlString(text.value.fields.text, options);\n }\n });\n return {\n html,\n };\n },\n});\n</script>\n```\n\n```text\nentry-hyperlink\n```\n\n========================================\n\nComments:\n- Not sure of what is the issue here. You're not sure how to write an async call in Nuxt or some code that you've already wrote is not rendering as expected?\n- @kissu I'm trying to render the richtext with internal links. It seems I need to load the target async in the render options. Or I misunderstand some concepts...\n- Can you show us what you did so far? It will also help me see what is the issue because I'm not sure of what is to call here. Did you read this one already? contentful.com/developers/docs/javascript/tutorials/…","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":88,"estimatedTokens":712}}705{"id":"stack-65844790","source":"stackoverflow","questionId":65844790,"title":"dynamic class binding in nuxtjs/vuejs with tailwind classes","tags":["vue.js","vue-component","tailwind-css","nuxt.js"],"text":"Title: dynamic class binding in nuxtjs/vuejs with tailwind classes\nTags: vue.js, vue-component, tailwind-css, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am assigning css classes according to some timer to a div.\n\ns0 can be 0 - 5\n\nthis assignment (as below) works fine but it feels like it is a lot of overhead in both writing and performance. Is there another way to assign css classes dynamically in nuxt?\n\ne.g. writing `class=\"-mt-{s0*8}\"` directly on the template? Why is there a need for a boolean to return? Am I missing something?\n\n```\n \n \n\n...\n\n ...\n methods: {\n oct(o, p) {\n return o*8 == p\n }\n },\n ...\n```\n\n========================================\n\nCode:\n```text\n<template> \n <div class=\"secs-0\" :class='{\"-mt-8\": oct(s0, 8),\n \"-mt-16\": oct(s0, 16),\n \"-mt-24\": oct(s0, 24),\n \"-mt-32\": oct(s0, 32),\n \"-mt-40\": oct(s0, 40)}'>\n\n...\n\n\n\n<script>\n ...\n methods: {\n oct(o, p) {\n return o*8 == p\n }\n },\n ...\n```\n\n```text\nclass=\"-mt-{s0*8}\"\n```\n\n```text\n<template> \n <div class=\"secs-0\" :class=\"['-mt-'+h0*8]\">\n```\n\n========================================\n\nComments:\n- You'll probably find this syntax handy in your case: `:class=\"['-mt-' + s0 * 8]\"`\n- Here's a tiny toy.","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":67,"estimatedTokens":341}}706{"id":"stack-52666872","source":"stackoverflow","questionId":52666872,"title":"Init nuxt plugins once instead of server + client","tags":["vue.js","nuxt.js"],"text":"Title: Init nuxt plugins once instead of server + client\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using nuxt i18n and @nuxtjs/router, which I initialize with async data from my API whenever the user loads the app.\n\nRouter example:\n\n```\nexport async function createRouter() {\n const routes = await httpService.get('routes')\n\n return new Router({\n mode: 'history',\n routes: routes.data\n })\n}\n```\n\nThis works fine. However, both plugins are initialized twice, first from the server, then from the client, which I noticed because of 2 api calls foreach plugin when I load the app. \n\nWhy are plugins initialized twice in `univerval` mode?\n\n========================================\n\nCode:\n```text\nexport async function createRouter() {\n const routes = await httpService.get('routes')\n\n return new Router({\n mode: 'history',\n routes: routes.data\n })\n}\n```\n\n```text\nuniverval\n```\n\n```text\nserver-side\n```\n\n```text\nclient-side\n```\n\n========================================\n\nComments:\n- Allright, I was expecting the server side initialization to be reused. Thanks for clarifying","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":54,"estimatedTokens":275}}707{"id":"stack-66915768","source":"stackoverflow","questionId":66915768,"title":"Is there a way to reduce nuxt entry point bundle size?","tags":["vue.js","nuxt.js","webpack-4"],"text":"Title: Is there a way to reduce nuxt entry point bundle size?\nTags: vue.js, nuxt.js, webpack-4\nSource: Stack Overflow\n\nQuestion:\nAfter upgrading my nuxt-cli version to 2.15.3 i've notice that pages chunks size was reduced and all node_modules installed packages are now being bundled into the app.js which is getting huge now.\n\nhttps://i.sstatic.net/4Mwbb.jpg\n\nHere below you can see my nuxt.config.js\n\n```\nexport default {\n ssr: false,\n target: \"static\",\n geneate: {\n fallback: true,\n },\n\n css: [\"@/assets/sass/app.scss\"],\n\n plugins: [\n \"@/store/plugins/permissionsPlugin\",\n \"@/store/plugins/authPlugin\",\n \"@/plugins/casl-abilities\",\n \"@/plugins/moment\",\n \"@/plugins/v-select\",\n \"@/plugins/vue-lazyload\",\n \"@/plugins/vue-mq\",\n { src: \"@/plugins/vue-infinite-scroll\", mode: \"client\" },\n { src: \"@/plugins/formatWebpSuppoted\", ssr: false },\n { src: \"@/plugins/ga.js\", mode: \"client\" },\n { src: \"@/plugins/mapbox\", mode: \"client\" },\n ],\n\n bundleRenderer: {\n shouldPreload: (file, type) => {\n return [\"script\", \"style\", \"font\"].includes(type)\n },\n },\n components: true,\n\n modules: [\n // Doc: https://bootstrap-vue.js.org\n \"bootstrap-vue/nuxt\",\n // Doc: https://github.com/Developmint/nuxt-purgecss\n // 'nuxt-purgecss',\n // Doc: https://pwa.nuxtjs.org/\n \"@nuxtjs/pwa\",\n // Doc: https://github.com/nuxt-community/dotenv-module\n \"@nuxtjs/dotenv\",\n // Doc: https://github.com/nuxt-community/apollo-module\n \"@nuxtjs/apollo\",\n // Doc: https://nuxtjs.org/faq/http-proxy\n \"@nuxtjs/proxy\",\n // Doc: https://github.com/Developmint/nuxt-webfontloader\n \"nuxt-webfontloader\",\n // Doc: https://github.com/frenchrabbit/nuxt-precompress\n \"nuxt-precompress\",\n // Doc : https://www.npmjs.com/package/vue-social-sharing\n \"vue-social-sharing/nuxt\",\n ],\n bootstrapVue: {\n bootstrapCSS: false, // Or `css: false`\n bootstrapVueCSS: false, // Or `bvCSS: false`\n componentPlugins: [\n \"LayoutPlugin\",\n \"DropdownPlugin\",\n \"FormPlugin\",\n \"FormGroupPlugin\",\n \"FormInputPlugin\",\n \"FormTextareaPlugin\",\n \"FormCheckboxPlugin\",\n \"FormRadioPlugin\",\n \"FormSelectPlugin\",\n \"ButtonPlugin\",\n \"ButtonGroupPlugin\",\n \"SpinnerPlugin\",\n \"VBPopoverPlugin\",\n \"ToastPlugin\",\n \"CardPlugin\",\n \"AlertPlugin\",\n \"PaginationPlugin\",\n \"BadgePlugin\",\n \"PopoverPlugin\",\n \"CollapsePlugin\",\n ],\n },\n build: {\n transpile: [\"bootstrap-vue\"],\n analyze: true,\n components: true,\n babel: {\n presets({ isServer }) {\n return [\n [\n require.resolve(\"@nuxt/babel-preset-app\")\n {\n buildTarget: isServer ? \"server\" : \"client\",\n corejs: { version: 3 },\n },\n ],\n ]\n },\n },\n cssSourceMap: false,\n plugins: [new webpack.IgnorePlugin(/^\\.\\/locale$/, /moment$/)],\n optimization: {\n runtimeChunk: true,\n splitChunks: {\n chunks: \"async\",\n },\n },\n splitChunks: {\n pages: true,\n vendor: false,\n commons: false,\n runtime: false,\n layouts: true,\n name: true,\n },\n },\n}\n```\n\nCan you help me on dividing main entry chunks into pages chunks ?\n\n========================================\n\nTop Answer:\nAll the plugins are loaded **before** the Vue instance is ever created and available globally. One solution would be to load any of those packages in specific components rather than on a global level if you don't need them everywhere.\n\nNot sure what can be optimized beyond this.\n\nAlso, from this page: https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-plugins\n\nssr: false will be adapted to mode: 'client' and deprecated in next major release\n\nSo, you should not have any `ssr` in your `plugins` array.\n\n========================================\n\nCode:\n```text\nexport default {\n ssr: false,\n target: \"static\",\n geneate: {\n fallback: true,\n },\n\n css: [\"@/assets/sass/app.scss\"],\n\n plugins: [\n \"@/store/plugins/permissionsPlugin\",\n \"@/store/plugins/authPlugin\",\n \"@/plugins/casl-abilities\",\n \"@/plugins/moment\",\n \"@/plugins/v-select\",\n \"@/plugins/vue-lazyload\",\n \"@/plugins/vue-mq\",\n { src: \"@/plugins/vue-infinite-scroll\", mode: \"client\" },\n { src: \"@/plugins/formatWebpSuppoted\", ssr: false },\n { src: \"@/plugins/ga.js\", mode: \"client\" },\n { src: \"@/plugins/mapbox\", mode: \"client\" },\n ],\n\n bundleRenderer: {\n shouldPreload: (file, type) => {\n return [\"script\", \"style\", \"font\"].includes(type)\n },\n },\n components: true,\n\n modules: [\n // Doc: https://bootstrap-vue.js.org\n \"bootstrap-vue/nuxt\",\n // Doc: https://github.com/Developmint/nuxt-purgecss\n // 'nuxt-purgecss',\n // Doc: https://pwa.nuxtjs.org/\n \"@nuxtjs/pwa\",\n // Doc: https://github.com/nuxt-community/dotenv-module\n \"@nuxtjs/dotenv\",\n // Doc: https://github.com/nuxt-community/apollo-module\n \"@nuxtjs/apollo\",\n // Doc: https://nuxtjs.org/faq/http-proxy\n \"@nuxtjs/proxy\",\n // Doc: https://github.com/Developmint/nuxt-webfontloader\n \"nuxt-webfontloader\",\n // Doc: https://github.com/frenchrabbit/nuxt-precompress\n \"nuxt-precompress\",\n // Doc : https://www.npmjs.com/package/vue-social-sharing\n \"vue-social-sharing/nuxt\",\n ],\n bootstrapVue: {\n bootstrapCSS: false, // Or `css: false`\n bootstrapVueCSS: false, // Or `bvCSS: false`\n componentPlugins: [\n \"LayoutPlugin\",\n \"DropdownPlugin\",\n \"FormPlugin\",\n \"FormGroupPlugin\",\n \"FormInputPlugin\",\n \"FormTextareaPlugin\",\n \"FormCheckboxPlugin\",\n \"FormRadioPlugin\",\n \"FormSelectPlugin\",\n \"ButtonPlugin\",\n \"ButtonGroupPlugin\",\n \"SpinnerPlugin\",\n \"VBPopoverPlugin\",\n \"ToastPlugin\",\n \"CardPlugin\",\n \"AlertPlugin\",\n \"PaginationPlugin\",\n \"BadgePlugin\",\n \"PopoverPlugin\",\n \"CollapsePlugin\",\n ],\n },\n build: {\n transpile: [\"bootstrap-vue\"],\n analyze: true,\n components: true,\n babel: {\n presets({ isServer }) {\n return [\n [\n require.resolve(\"@nuxt/babel-preset-app\")\n {\n buildTarget: isServer ? \"server\" : \"client\",\n corejs: { version: 3 },\n },\n ],\n ]\n },\n },\n cssSourceMap: false,\n plugins: [new webpack.IgnorePlugin(/^\\.\\/locale$/, /moment$/)],\n optimization: {\n runtimeChunk: true,\n splitChunks: {\n chunks: \"async\",\n },\n },\n splitChunks: {\n pages: true,\n vendor: false,\n commons: false,\n runtime: false,\n layouts: true,\n name: true,\n },\n },\n}\n```\n\n```text\nssr\n```\n\n```text\nplugins\n```\n\n```json\noptimization: {\n minimize: true,\n splitChunks: {\n chunks: 'all',\n automaticNameDelimiter: '.',\n name: true,\n maxSize: 244000,\n cacheGroups: {\n vendor: {\n name: 'node_vendors',\n test: /[\\\\/]node_modules[\\\\/]/,\n chunks: 'all',\n maxSize: 244000\n }\n }\n }\n }\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":284,"estimatedTokens":1677}}708{"id":"stack-56729097","source":"stackoverflow","questionId":56729097,"title":"How to add Vuepress on a Nuxt project in a proper way?","tags":["vue.js","nuxt.js","vuepress"],"text":"Title: How to add Vuepress on a Nuxt project in a proper way?\nTags: vue.js, nuxt.js, vuepress\nSource: Stack Overflow\n\nQuestion:\nI have my Nuxt app and I'm trying to add Vuepress on it. \nI did `yarn add vuepress@next -D` then created the `docs` folder and a `readme.md` file in there. \n\n**The problem:** The project only shows the sidebar and navbar if the `.vuepress` folder is *outside of the `docs` folder*; If it's inside, it won't work - Not respecting the config.js rules.\n\nAlso, it's recognising the readme.md from the Nuxt app (outside from docs folder too), not the one inside docs folder.\n\nCan anyone help me with that?\n\nAnother question, if this above works, Am I be able to access through `localhost:3000/docs` instead of `localhost:3000` for the Nuxt project and `localhost:8080` for the docs?\n\nThat's my current folder structure (no sidebar showing - not respecting the config.js inside the .vuepress folder):\n\n```\ndocs\n |__.vuepress\n | |__config.js\n |\n |__guides\n```\n\nThe config.js file:\n\n```\nmodule.exports = {\n title: 'Documentation',\n description: 'Documentation',\n themeConfig: {\n sidebar: 'auto',\n nav: [{\n text: 'Home',\n link: '/'\n },\n {\n text: 'Guides A',\n link: '/guides/apis/'\n },\n {\n text: 'item with subitems',\n items: [{\n text: 'Subitem 01',\n link: '/'\n },\n {\n text: 'SubItem 02',\n link: '/'\n }\n ]\n },\n {\n text: 'External',\n link: 'https://google.com'\n },\n ]\n }\n}\n```\n\nVuepress version 1.0.2\n\nThanks.\n\n========================================\n\nCode:\n```text\ndocs\n |__.vuepress\n | |__config.js\n |\n |__guides\n```\n\n```text\nmodule.exports = {\n title: 'Documentation',\n description: 'Documentation',\n themeConfig: {\n sidebar: 'auto',\n nav: [{\n text: 'Home',\n link: '/'\n },\n {\n text: 'Guides A',\n link: '/guides/apis/'\n },\n {\n text: 'item with subitems',\n items: [{\n text: 'Subitem 01',\n link: '/'\n },\n {\n text: 'SubItem 02',\n link: '/'\n }\n ]\n },\n {\n text: 'External',\n link: 'https://google.com'\n },\n ]\n }\n}\n```\n\n```text\nyarn add vuepress@next -D\n```\n\n```text\ndocs\n```\n\n```text\nreadme.md\n```\n\n```text\n.vuepress\n```\n\n```text\ndocs\n```\n\n```text\nlocalhost:3000/docs\n```\n\n```text\nlocalhost:3000\n```\n\n```text\nlocalhost:8080\n```\n\n========================================\n\nComments:\n- I do need it as the Vuepress Docs will be written on NetliftCMS by a few more users. That's why my main Nuxt application will have a Vuepress Documentation.\n- @FabioZanchi Since your use-case is funky, there won't be a proper way\n- Thank you guys. I'm gonna create a separated project for the docs.","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":151,"estimatedTokens":672}}709{"id":"stack-66493322","source":"stackoverflow","questionId":66493322,"title":"Can't install fonts with Nuxt/Tailwind","tags":["vue.js","nuxt.js","tailwind-css"],"text":"Title: Can't install fonts with Nuxt/Tailwind\nTags: vue.js, nuxt.js, tailwind-css\nSource: Stack Overflow\n\nQuestion:\nI applied this answer exactly but my custom font class still doesn't work:\n\n`tailwind.config.js`:\n\n```\nmodule.exports = {\n theme: {\n fontFamily: {\n \"intro-regular\": \"intro-regular\"\n },\n extend: {\n fontSize: {\n \"10\": \"10px\",\n \"11\": \"11px\"\n }\n }\n }\n}\n```\n\nIn `assets/scss/fonts.scss`:\n\n```\n@font-face {\n font-family: 'intro-regular';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('../fonts/intro/Intro-Regular.otf') format('opentype');\n}\n```\n\nThis should work, but when I try `@apply intro-regular` anywhere in my app I get this error:\n\nThe `intro-black` class does not exist\n\nAny suggestion?\n\n(also I don't even see the font being loaded in DevTools' network tab: regardless of Tailwind I would think that the font should at least load but it doesn't)\n\nEDIT: more info on my setup\n\nImport of my `main.scss` in `nuxt.config.js`:\n\n```\ncss: [\n {\n src: '~/assets/scss/main.scss',\n lang: 'scss'\n }\n],\n```\n\nAnd in `main.scss`:\n\n```\n@import 'fonts';\n```\n\nTo install Nuxt/Tailwind I followed the docs to the letter. But is sometimes the case with `Nuxt.js`, things didn't turn out as they were supposed to and `Nuxt` did not create any `tailwind.css` file in the `/assets` folder.\n\n========================================\n\nTop Answer:\n`src: url('../fonts/intro/Intro-Regular.otf')`\n\nShould be:\n\n`src: url('~/assets/fonts/intro/Intro-Regular.otf')`\n\n========================================\n\nCode:\n```js\nmodule.exports = {\n theme: {\n fontFamily: {\n \"intro-regular\": \"intro-regular\"\n },\n extend: {\n fontSize: {\n \"10\": \"10px\",\n \"11\": \"11px\"\n }\n }\n }\n}\n```\n\n```css\n@font-face {\n font-family: 'intro-regular';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('../fonts/intro/Intro-Regular.otf') format('opentype');\n}\n```\n\n```text\ncss: [\n {\n src: '~/assets/scss/main.scss',\n lang: 'scss'\n }\n],\n```\n\n```text\n@import 'fonts';\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nassets/scss/fonts.scss\n```\n\n```text\n@apply intro-regular\n```\n\n```text\nintro-black\n```\n\n```text\nmain.scss\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nmain.scss\n```\n\n```text\nNuxt.js\n```\n\n```text\nNuxt\n```\n\n```text\ntailwind.css\n```\n\n```text\n/assets\n```\n\n```css\n/* stylelint-disable scss/at-rule-no-unknown */\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n/* stylelint-enable */\n```\n\n```js\nbuildModules: [\n [\n '@nuxtjs/tailwindcss',\n {\n cssPath: '~/assets/scss/tailwind.scss',\n },\n ],\n]\n```\n\n```text\n@apply font-intro-regular\n```\n\n```text\nfont\n```\n\n```text\n~/assets/scss/tailwind.scss\n```\n\n```text\n@import './fonts';\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nsrc: url('../fonts/intro/Intro-Regular.otf')\n```\n\n```text\nsrc: url('~/assets/fonts/intro/Intro-Regular.otf')\n```\n\n```js\nmodule.exports = {\n theme: {\n fontFamily: {\n intro: (\"intro-regular\": \"intro-regular\")\n },\n extend: {\n fontSize: {\n \"10\": \"10px\",\n \"11\": \"11px\"\n }\n }\n }\n}\n```\n\n========================================\n\nComments:\n- Thanks, that's what I had initially. I changed at some point during my struggle. But it does not solve my problem. Font still won't load and same error message...\n- You mention you’ve imported the font in assets/scss/fonts.scss, but it isn’t clear how you’ve imported that file into your main css. Can you ?\n- How have you implemented tailwind with your nuxt app? Typically you would have a tailwind.css which imports the base, utility classes etc. That’s where you’d import your fonts.scss. Can you update again with more detail about how you’ve implemented tailwind into your app?\n- Thanks! Adding `font-` before `intro-regular` in my `@apply` did the trick :) I didn't know we should put `font-` before the font name though, and even when knowing that I can't find it clearly explained in the docs! (SO wants me to wait 20h before I can award bounty)\n- Usually, when you do have a key nested into a object, you need some kind of prefix for it (like `opacity`, `borderRadius` or `lineHeight`). It is also useful to know when you want to add your own keys. For the example, go to this page: v1.tailwindcss.com/docs/font-family#font-families There, you will see the default settings for `sans, serif, mono` and you can see those in action at the top of the page with their default behavior. `variants` are tricky in Tailwind tho ! (v1.tailwindcss.com/docs/configuring-variants) Alright for the bounty, waiting patiently. :)\n- Please do more effort to your answer, so everyone can understand it.","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":233,"estimatedTokens":1156}}710{"id":"stack-58977870","source":"stackoverflow","questionId":58977870,"title":"Nuxt reload api data fails","tags":["async-await","axios","nuxt.js"],"text":"Title: Nuxt reload api data fails\nTags: async-await, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nNeed some help in solving a reload problem.\nI fetch data via service:\n\n```\nimport axios from 'axios'\n\nconst apiClient = axios.create({\n baseURL: 'www.domain/api/v1',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json'\n }\n})\n```\n\nand\n\n```\nexport default {\n getCompanies() {\nreturn apiClient.get('/companies')\n},\n```\n\nin store:\n\n```\nexport const actions = {\n fetchCompanies({ commit }) {\n return CompanyService.getCompanies().then(response => {\n commit('SET_COMPANIES', response.data)\n })\n},\n```\n\nin pages/companies:\n\n```\nasync fetch({ store, error }) {\n try {\n await store.dispatch('company/fetchCompanies')\n } catch (e) {\n error({\n statusCode: 503,\n message: 'Unable to fetch Companies at this time'\n })\n }\n},\n```\n\nworks fine, but no data on page reload. \nSome help would be great.\n\n========================================\n\nCode:\n```text\nimport axios from 'axios'\n\nconst apiClient = axios.create({\n baseURL: 'www.domain/api/v1',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json'\n }\n})\n```\n\n```text\nexport default {\n getCompanies() {\nreturn apiClient.get('/companies')\n},\n```\n\n```text\nexport const actions = {\n fetchCompanies({ commit }) {\n return CompanyService.getCompanies().then(response => {\n commit('SET_COMPANIES', response.data)\n })\n},\n```\n\n```text\nasync fetch({ store, error }) {\n try {\n await store.dispatch('company/fetchCompanies')\n } catch (e) {\n error({\n statusCode: 503,\n message: 'Unable to fetch Companies at this time'\n })\n }\n},\n```\n\n```text\nfetch\n```\n\n```text\nwatchQuery\n```\n\n========================================\n\nComments:\n- Thanks for your answer. I will check that out..I am in doubt now why I should go all the way through the store at all... in some tutorials they call the API's directly in the actual index.vue..can you give me some answer about that.. Thanks for helping.\n- I can't find a way to fit in: watchQuery in my code..watchQuery: true or watchQuery (newQuery, oldQuery) {}..no success","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":115,"estimatedTokens":526}}711{"id":"stack-58651135","source":"stackoverflow","questionId":58651135,"title":"How I can access route.meta on nuxt.js","tags":["nuxt.js"],"text":"Title: How I can access route.meta on nuxt.js\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI try to access route.meta on nuxt.js custom route.\n\nI have set up this custom route in nuxt.config.js\n\n```\nrouter: {\n extendRoutes (routes, resolve) {\n routes.push({\n path: '*',\n component: resolve(__dirname, 'my-component.vue'),\n meta: { accessToken: 'mydata' }\n })\n }\n },\n```\n\nThen I try from inside this component to get this meta value \nIdeally I want to have access to it thought my asyncData function. \n\nAny ideas?\n\n========================================\n\nCode:\n```text\nrouter: {\n extendRoutes (routes, resolve) {\n routes.push({\n path: '*',\n component: resolve(__dirname, 'my-component.vue'),\n meta: { accessToken: 'mydata' }\n })\n }\n },\n```\n\n```js\nexport default {\n asyncData(ctx) {\n const { route } = ctx;\n console.log(route.meta);\n }\n}\n```\n\n```text\nasyncData\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":53,"estimatedTokens":237}}712{"id":"stack-55591206","source":"stackoverflow","questionId":55591206,"title":"How to use workbox-webpack-plugin together with Nuxt PWA","tags":["javascript","progressive-web-apps","nuxt.js","workbox-webpack-plugin"],"text":"Title: How to use workbox-webpack-plugin together with Nuxt PWA\nTags: javascript, progressive-web-apps, nuxt.js, workbox-webpack-plugin\nSource: Stack Overflow\n\nQuestion:\nI'm currently on Nuxt with PWA Plugin, including workbox module. However if I'm not mistaken this plugin doesn't allow to add the assets generated by webpack to precaching.\n\nIs it possible to use workbox-webpack-plugin for only generating the precaching part of the sw.js file? If so, how would it be done?\n\nThere is some documentation on https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin, however I'm not sure how to apply this to the Nuxt PWA context.\n\n========================================\n\nCode:\n```text\nworkbox.precaching.precacheAndRoute(self.__precacheManifest)\n```\n\n```text\nimport { InjectManifest } from 'workbox-webpack-plugin'\n\n...\n\n workbox: {\n importScripts: ['_nuxt/sw-precache.js'],\n workboxExtensions: ['~/plugins/sw-precache-register.js']\n }\n```\n\n========================================\n\nComments:\n- Is this still a good answer? I'm also wondering how to solve this, I receive a browser console warning saying \"Workbox is precaching URLs without revision info...\"","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":33,"estimatedTokens":298}}713{"id":"stack-55991788","source":"stackoverflow","questionId":55991788,"title":"how to add plugins of ckeditor in nuxt with ssr","tags":["nuxt.js","ckeditor5"],"text":"Title: how to add plugins of ckeditor in nuxt with ssr\nTags: nuxt.js, ckeditor5\nSource: Stack Overflow\n\nQuestion:\ni am trying to add Alignment plugins of ckeditor 5 in my nuxt app which is universal (SSR)\n\ni tried like this in plugins\n\n```\nimport Vue from 'vue'\nimport ClassicEditor from '@ckeditor/ckeditor5-build-classic'\nimport VueCkeditor from 'vue-ckeditor5'\n\n// import Alignment from '@ckeditor/ckeditor5-alignment/src/alignment'; i also tried direct import to page like this\n\n`import Alignment from '@ckeditor/ckeditor5-alignment/src/alignment';`\n\ngetting error\n\n Unexpected identifier\n\nNormal editorConfig is working fine \n\n```\neditorConfig: {\n\n image: {\n\n toolbar: ['imageTextAlternative', '|', 'imageStyle:alignLeft', 'imageStyle:full', 'imageStyle:alignRight'],\n\n styles: [\n\n 'full',\n\n 'alignLeft',\n\n 'alignRight'\n ]\n },\n alignment: {\n options: [ 'left', 'right' ]\n },\n toolbar: {\n items: [\n 'heading',\n 'bold',\n 'italic',\n 'link',\n 'bulletedList',\n 'numberedList',\n 'blockQuote',\n 'insertTable',\n 'imageUpload',\n 'mediaEmbed',\n 'alignment'\n ]\n }\n },\n```\n\n========================================\n\nTop Answer:\nYou can import/render CKEditor on client side only using workaround with plugin included on client side only which register component for editor\n\n**nuxt.config**\n\n```\nplugins: [\n { src: '~/plugins/rich-editor', mode: 'client' },\n],\n```\n\nssr=false makes plugin not to be included in server side build\n\n**plugins/rich-editor.js**\n\n```\nimport Vue from 'vue'\nimport RichEditor from '@/components/RichEditor'\n\n// register component from plugin to bypass SSR\nVue.component('rich-editor', RichEditor)\n```\n\nAnd finally import CKEditor in RichEditor wrapper.\n\n**RichEditor.js**\n\n```\nimport CKEditor from '@ckeditor/ckeditor5-vue';\n```\n\nOn server side will be empty div which will be rendered as CKEditor on client side.\n\nAlternativelly you can register in your plugin.\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\nimport ClassicEditor from '@ckeditor/ckeditor5-build-classic'\nimport VueCkeditor from 'vue-ckeditor5'\n\n// import Alignment from '@ckeditor/ckeditor5-alignment/src/alignment'; <-- not working\n\n\nconst options = {\n\n editors: {\n classic: ClassicEditor,\n\n },\n name: 'ckeditor'\n}\n\nVue.use(VueCkeditor.plugin, options);\n```\n\n```text\neditorConfig: {\n\n image: {\n\n toolbar: ['imageTextAlternative', '|', 'imageStyle:alignLeft', 'imageStyle:full', 'imageStyle:alignRight'],\n\n styles: [\n\n 'full',\n\n\n 'alignLeft',\n\n\n 'alignRight'\n ]\n },\n alignment: {\n options: [ 'left', 'right' ]\n },\n toolbar: {\n items: [\n 'heading',\n 'bold',\n 'italic',\n 'link',\n 'bulletedList',\n 'numberedList',\n 'blockQuote',\n 'insertTable',\n 'imageUpload',\n 'mediaEmbed',\n 'alignment'\n ]\n }\n },\n```\n\n```text\nimport Alignment from '@ckeditor/ckeditor5-alignment/src/alignment';\n```\n\n```text\nplugins: [\n { src: '~/plugins/rich-editor', mode: 'client' },\n],\n```\n\n```text\nimport Vue from 'vue'\nimport RichEditor from '@/components/RichEditor'\n\n// register component from plugin to bypass SSR\nVue.component('rich-editor', RichEditor)\n```\n\n```text\nimport CKEditor from '@ckeditor/ckeditor5-vue';\n```\n\n========================================\n\nComments:\n- Show full error\n- @Aldarund prntscr.com/nkn8bm\n- You probably need to transpile it nuxtjs.org/api/configuration-build/#transpile\n- @Aldarund i never use this and i don't know what is this can u tell me how to fix this? thanks\n- i told you, try to add its to transpile option. U are basicallt importing from sources which was transplied. u need to compile them first\n- This works well but do you have any idea why when I reload the page (Cmd + R, full reload), I get window is not defined? And not the first time I go to the page.\n- @Skoua I guess you have accidentally imported editor on server side.","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":192,"estimatedTokens":1014}}714{"id":"stack-57178253","source":"stackoverflow","questionId":57178253,"title":"How to create skeleton Loading in Nuxt.js?","tags":["vue.js","nuxt.js"],"text":"Title: How to create skeleton Loading in Nuxt.js?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to create \"skeleton loading\" in Nuxt.js, but I have a problem with the moment when routing to the page. Nuxt.js doesn't change the page until the success of 'fetch' and 'asyncData' by default.\nCan I go to the page at once, and then wait for the data and fetch?\n\nOn the example:\n\n```\n\n \n \n \n\n### \n\n \n \n \n\n### {{ val1 }}\n\n \n \n\n \n\nexport default {\n async asyncData(){\n let val1 = await (new Promise(resolve => setTimeout(\n () => resolve('work'), 5000\n )));\n return {\n val1\n }\n },\n}\n\n```\n\n========================================\n\nTop Answer:\nThe same problem I was facing, My solution is\n\n- First, create a middleware in /middleware directory\n\n- Register it in nuxt.config.js file like this\n\n```\nrouter: {\n middleware: 'skelton'\n }\n```\n\nIn \\middleware\\skelton.js\n\n```\nexport default function ({store}) {\n if (!process.server) {\n store.commit('ui/changeSkletonLoading', {\n skeltonLoading: true\n })\n }\n }\n```\n\nAdd file in store\\ui.js directory \n\n```\nexport const state = () => ({\n skeltonLoading: false,\n })\n\n export const mutations = {\n changeSkletonLoading(state, payload) {\n state.skeltonLoading = payload.skeltonLoading;\n }\n }\n```\n\nNow go to your component file and add this code\n\n```\n\n \n \n // PUT YOUR CONTENT HERE \n \n \n\n \n import { mapState } from \"vuex\";\n export default {\n computed: {\n ...mapState(\"ui\", {\n skeltonLoading: state => state.skeltonLoading\n })\n },\n created() {\n this.$store.commit(\"ui/changeSkletonLoading\", {\n skeltonLoading: false\n });\n }\n };\n \n```\n\nWhenever you click to go on another route it will show you Skelton loading.\n\n Note: It will not show Skelton loading on page load but it will show Skelton loading on page change (route navigation)\n\n========================================\n\nCode:\n```vue\n<template>\n <div>\n <div class=\"sceleton-loading\">\n <h1> <svg> <!-- h1-empty content animation--> </svg> </h1>\n </div>\n <div class=\"content\">\n <h1>{{ val1 }}</h1>\n </div>\n </div>\n</template>\n \n<script>\nexport default {\n async asyncData(){\n let val1 = await (new Promise(resolve => setTimeout(\n () => resolve('work'), 5000\n )));\n return {\n val1\n }\n },\n}\n</script>\n```\n\n```text\nexport default function({ store, route }) {\n let skeleton = null;\n\n if (route.name.indexOf(\"page-one\") !== -1)\n skeleton = \"skeleton-page-one\";\n else if (route.name.indexOf(\"page-two\") !== -1)\n skeleton = \"skeleton-page-two\"; \n ...\n\n store.commit(\"UPDATE_SKELETON\", skeleton);\n}\n```\n\n```text\nmiddleware: \"skeleton\",\n```\n\n```text\n<v-app>\n <header/>\n <main v-if=\"page_loading\" class=\"main\">\n <page-one-skeleton v-if=\"skeleton === 'page-one'\" />\n <page-two-skeleton v-if=\"skeleton === 'page-two'\" />\n </main>\n <nuxt v-else />\n <footer/>\n <common />\n </v-app>\n <script>\n computed: {\n skeleton() {\n return this.$store.state.skeleton;\n },\n page_loading() {\n return this.$store.state.page_loading;\n }\n }\n </script>\n```\n\n```text\nexport const state = () => ({\n skeleton: null,\n page_loading: false\n\n})\n\nexport const mutations = {\n UPDATE_SKELETON(state, data) {\n state.skeleton = data;\n },\n UPDATE_LOADING(state, data) {\n state.global_loading = data;\n }\n})\n```\n\n```text\nrouter: {\n middleware: 'skelton'\n }\n```\n\n```text\nexport default function ({store}) {\n if (!process.server) {\n store.commit('ui/changeSkletonLoading', {\n skeltonLoading: true\n })\n }\n }\n```\n\n```text\nexport const state = () => ({\n skeltonLoading: false,\n })\n\n export const mutations = {\n changeSkletonLoading(state, payload) {\n state.skeltonLoading = payload.skeltonLoading;\n }\n }\n```\n\n```text\n<template>\n <div>\n <v-skeleton-loader\n class=\"mx-auto my-2\"\n v-if=\"skeltonLoading\"\n type=\"card-heading, list-item-three-line\"\n ></v-skeleton-loader>\n <div v-if=\"!skeltonLoading\">// PUT YOUR CONTENT HERE </div>\n </div>\n </template>\n\n <script>\n import { mapState } from \"vuex\";\n export default {\n computed: {\n ...mapState(\"ui\", {\n skeltonLoading: state => state.skeltonLoading\n })\n },\n created() {\n this.$store.commit(\"ui/changeSkletonLoading\", {\n skeltonLoading: false\n });\n }\n };\n </script>\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":257,"estimatedTokens":1120}}715{"id":"stack-69683768","source":"stackoverflow","questionId":69683768,"title":"redirection link generate by the methods to href or nuxt-link","tags":["vue.js","nuxt.js","vue-router"],"text":"Title: redirection link generate by the methods to href or nuxt-link\nTags: vue.js, nuxt.js, vue-router\nSource: Stack Overflow\n\nQuestion:\nHello I want to display a page with a link generated by a method.\n\nHere is my current code.\n\n```\n\n \n \n Go to product\n \n \n\nexport default {\nmethods: {\n async seeProduct(id) {\n const app = { $axios: this.$axios };\n const urlProduct = await endPoint.getProduct(app, id);\n console.log(urlProduct.url); // https://www.products/gants.html => this is the url\n return urlProduct.url;\n },\n }\n}\n\n```\n\nWhen I click on the link, the redirection is not good. How to do a good redirection with an URL generated by a method?\n\n========================================\n\nCode:\n```html\n<template>\n <nuxt-link :to=\"seeProduct(item.sku.product.id).toString()\">\n <div>\n <span>Go to product</span>\n </div>\n </nuxt-link>\n</template>\n\n<script>\nexport default {\nmethods: {\n async seeProduct(id) {\n const app = { $axios: this.$axios };\n const urlProduct = await endPoint.getProduct(app, id);\n console.log(urlProduct.url); // https://www.products/gants.html => this is the url\n return urlProduct.url;\n },\n }\n}\n</script>\n```\n\n```text\n:to=\"{ name: 'gants' }\"\n```\n\n========================================\n\nComments:\n- This is an internal path to your app or an external URL? `href` are to be used only if you want to leave your Nuxt app. Otherwise use `nuxt-link`. You also probably don't need the `toString()`.\n- is an internal path","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":67,"estimatedTokens":369}}716{"id":"stack-56408998","source":"stackoverflow","questionId":56408998,"title":"Use mongodb in nuxt","tags":["mongodb","vue.js","nuxt.js"],"text":"Title: Use mongodb in nuxt\nTags: mongodb, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to use MongoDB for long term and complex storage that Vuex isn't suited for.\n\nI have MongoDB installed and running and I installed the mongoose package.\n\nIn my plugins folder, I have a create a script that initializes the module and exports it:\n\n**plugins/mongoose.js**\n\n```\nconst mongoose = require('mongoose');\n\nmongoose.connect('mongodb://localhost/users', { useNewUrlParser: true });\n\nexport default({ app }, inject) => {\n\n inject('mongoose', mongoose);\n\n}\n```\n\nand then in my nuxt.config.js, I declare the module and set it as server side only.\n\n**nuxt.config.js**\n\n```\n...\nplugins: [\n { src: '~/plugins/mongoose.js', mode: 'server' },\n],\n...\n```\n\nand then finally, in one of my pages I try to access it in a method.\n\n**pages/users.vue**\n\n```\n\n Joe\n\n export default {\n methods: {\n addUser(name) {\n console.log(this.$mongoose);\n }\n }\n }\n\n```\n\nand when I click the button in the console I get `cannot stringify a function change` and then `cannot stringify a function name`. I can't tell if this is working but I can't use any properties of the `mongoose` object.\n\nThere doesn't seem to be much structured information on this topic even though it seems like it would be fairly common.\n\n========================================\n\nTop Answer:\nYou could create your own serverMiddleware, and then call that in your asyncData. Simplified, I have the following:\n\n```\n// nuxt.config.js\nconst bodyParser = require('body-parser')\n\nexport default {\n ...,\n serverMiddleware: [\n bodyParser.json(),\n { path: '/db-api', handler: '~/api/db-connection' },\n ],\n}\n```\n\nin db-connection you can add something like:\n\n```\nimport {\n getOneDocument,\n} from '../utils/db-helper'\n\nexport default async function (req, res, next) {\n const doc = await getOneDocument('my-one-and-only-collection', req.body)\n\n res.end(JSON.stringify(doc))\n}\n```\n\nand then in asyncData you can do something like:\n\n```\nasync asyncData (context: any) {\n const reqq = await axios.post(\n `${url}/db-api`,\n {\n 'sys.id': '2J2a1nQhmTYbHML2si8gmW'\n }\n )\n return {\n thatOneAndOnlyRecord: reqq.data,\n }\n}\n```\n\nYou will need to make sure that any complex querying happens inside your middleware as well since you are making a network request for each query to mongo.\n\n========================================\n\nCode:\n```text\nconst mongoose = require('mongoose');\n\nmongoose.connect('mongodb://localhost/users', { useNewUrlParser: true });\n\nexport default({ app }, inject) => {\n\n inject('mongoose', mongoose);\n\n}\n```\n\n```text\n...\nplugins: [\n { src: '~/plugins/mongoose.js', mode: 'server' },\n],\n...\n```\n\n```text\n<template>\n <button @click=\"addUser('joe')\">Joe</button>\n</template>\n\n<script>\n export default {\n methods: {\n addUser(name) {\n console.log(this.$mongoose);\n }\n }\n }\n</script>\n```\n\n```text\ncannot stringify a function change\n```\n\n```text\ncannot stringify a function name\n```\n\n```text\nmongoose\n```\n\n```js\n// nuxt.config.js\nconst bodyParser = require('body-parser')\n\nexport default {\n ...,\n serverMiddleware: [\n bodyParser.json(),\n { path: '/db-api', handler: '~/api/db-connection' },\n ],\n}\n```\n\n```js\nimport {\n getOneDocument,\n} from '../utils/db-helper'\n\nexport default async function (req, res, next) {\n const doc = await getOneDocument('my-one-and-only-collection', req.body)\n\n res.end(JSON.stringify(doc))\n}\n```\n\n```js\nasync asyncData (context: any) {\n const reqq = await axios.post(\n `${url}/db-api`,\n {\n 'sys.id': '2J2a1nQhmTYbHML2si8gmW'\n }\n )\n return {\n thatOneAndOnlyRecord: reqq.data,\n }\n}\n```\n\n========================================\n\nComments:\n- But Nuxt is server-side rendered. Doesn't that mean the functions will run on the server?\n- @AndreOdendaal on initial call. But than when user click buttons etc it all happens on client\n- This is not accurate. You could use serverMiddleware for it, no?\n- Nuxtjs or any static site generator needs a nodejs environment to run, so since you have node you can do anything, but yes only on generation time, after generation then you cant use have access\n- \"Nuxt is frontend\", that is not correct. Nuxt runs in the server side and has the serverMiddleware feature to develop server-side logic, in NodeJS.","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":207,"estimatedTokens":1079}}717{"id":"stack-68047044","source":"stackoverflow","questionId":68047044,"title":"how to use raw html file in nuxt(vue)?","tags":["javascript","firebase","vue.js","stripe-payments","nuxt.js"],"text":"Title: how to use raw html file in nuxt(vue)?\nTags: javascript, firebase, vue.js, stripe-payments, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to create a page Jump to the stripe payment page use stripe-samples/firebase-subscription-payments .\nso I placed it's html/css/js file(which in the \"public\" folder) to my nuxt app's /static.\nHowever, since it is for static files only, so vuex and plugins could not be used. Fortunately, the tag in html reads firebase from the url, so it is possible to use firebase.\n\nbut can I put raw html/css/js files to nuxt/pages like .vue file?(I tried but couldn't..)\nI know the best way is to rewrite the html/js file into vue file, but it was too difficult for me as a beginner(Also, I'm Japanese and I'm not good at English,sorry).\nor can I use npm package and module in /static/files ?\nI have google it for two days and couldn't resolve it.I really need help,thank you!!\n\nhere is my code:\nstatic/public/javascript/app.js\n\n```\nimport firebase from firebase; \n /*↑ it will be error \"Cannot use import statement outside a module\".\n but in pages/.vue files and plugins/files, it will work... \n I also tried \"import firebase from '~/plugins/firebase.js'\"*/\n \n const STRIPE_PUBLISHABLE_KEY = ....\n```\n\nstatic/public/index.html\n\n```\n\n \n \n\n \n \n\n \n \n \n```\n\n↑ it read firebase from url, but I want use firebase module I've installed.\n\n========================================\n\nTop Answer:\nEventually I rewrote the js / html code to vue. Basically it is completed just by copying the js code to mounted(), but since I could not manipulate the nested template tag with js, I rewrote a part using v-if and v-for.\n\n========================================\n\nCode:\n```js\nimport firebase from firebase; \n /*↑ it will be error \"Cannot use import statement outside a module\".\n but in pages/.vue files and plugins/files, it will work... \n I also tried \"import firebase from '~/plugins/firebase.js'\"*/\n \n const STRIPE_PUBLISHABLE_KEY = ....\n```\n\n```html\n<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n <script src=\"https://www.gstatic.com/firebasejs/7.14.6/firebase.js\"></script>\n <script src=\"https://www.gstatic.com/firebasejs/7.14.6/firebase-functions.js\"></script>\n\n <!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->\n <script src=\"https://www.gstatic.com/firebasejs/7.14.5/firebase-analytics.js\"></script>\n\n <!-- Add Firebase products that you want to use -->\n <script src=\"https://www.gstatic.com/firebasejs/7.14.5/firebase-auth.js\"></script>\n <script src=\"https://www.gstatic.com/firebasejs/7.14.5/firebase-firestore.js\"></script>\n```\n\n```text\nstatic\n```\n\n```js\nbuild: {\n extend(config, ctx){\n config.resolve.alias['vue'] = 'vue/dist/vue.common';\n }\n }\n```\n\n```text\n<script>\nimport myHtml from '~/path/to/your/html/my_html.html';\nexport default{\n render(h){\n return h({\n template: `<main>${myHtml}</main>`\n });\n }\n}\n</script>\n```\n\n```text\n<script>\nimport myHtml from '~/path/to/your/html/my_html.html';\nexport default{\n render(h){\n return h({\n template: `<main>${myHtml}</main>`,\n created(){\n console.log('I have been created!')\n },\n mounted(){\n console.log('I have been mounted!')\n },\n methods: {\n exampleMethod(){\n alert('this is an example')\n }\n }\n });\n }\n}\n</script>\n```\n\n```text\nhtml\n```\n\n```text\nrender()\n```\n\n```text\n<router-view/>\n```\n\n```text\n<nuxt/>\n```\n\n```text\n<script>\n```\n\n```text\nmy_html.html\n```\n\n```text\nrender()\n```\n\n========================================\n\nComments:\n- You need to port it to nuxt, it's only a process sample to guide you in what needs to be done in vanilla js, if you want the same app in vue/nuxt you need to go through it and implement it. The code in .html you put in your pages/*.vue file, then either create a plugin to load the firebase lib, or use a nuxt plugin firebase.nuxtjs.org then go through the js file app.js and convert/implement the code into models, methods etc, if you want .html files at the end you use `nuxt generate`.. hire a dev, is like an hours work\n- @Lawrence Cherone I'm glad to know that it's common to rewrite to vue! At the same time, I got motivated to rewrite it in vue ^ ^Thanks for the quick answer!\n- @kissu Sorry for the late comment! I'm happy to be confident that static is still not suitable for code rendering I'm a beginner so I thought it was a best practice ^^;\n- No issues. Didn't meant to be rude. It's just a common mistake and I was debunking it. :)\n- @kissu I was able to get a great answer and it was worth asking in English~","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":158,"estimatedTokens":1207}}718{"id":"stack-77037790","source":"stackoverflow","questionId":77037790,"title":"How to run Nuxt3 with docker (docker compose)","tags":["docker","docker-compose","dockerfile","nuxt.js","nuxt3.js"],"text":"Title: How to run Nuxt3 with docker (docker compose)\nTags: docker, docker-compose, dockerfile, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI want to run nuxt3 in a Docker container (using docker compose)\n\nMy Dockerfile looks like that:\n\n```\nFROM node:18.17.1-bullseye as build-stage\n\nWORKDIR /app\nCOPY . .\nRUN yarn install\nRUN yarn build\n\nFROM node:18.17.1-bullseye as production-stage\nRUN mkdir /app\nCOPY --from=build-stage /app/.output /app/.output\n\nENTRYPOINT [\"node\", \".output/server/index.mjs\"]\n```\n\nWhen I start the container it quits with this error:\n\n```\nnode:internal/modules/cjs/loader:1080\n throw err;\n ^\n \n Error: Cannot find module '/app/.output/server/index.mjs'\n at Module._resolveFilename (node:internal/modules/cjs/loader:1077:15)\n at Module._load (node:internal/modules/cjs/loader:922:27)\n at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)\n at node:internal/main/run_main_module:23:47 {\n code: 'MODULE_NOT_FOUND',\n requireStack: []\n }\n \n Node.js v18.17.1\n exited with code 0\n```\n\nFor me it looks like that the folder .output is not there. But I don't understand why and how to debug this.\n\nEDIT:\n#docker-compose.yaml\n\n```\nversion: '3'\n\nservices:\n web:\n build: .\n ports:\n - \"3000:3000\"\n volumes:\n - .:/app\n - /app/node_modules\n environment:\n - HOST=0.0.0.0\n```\n\n#production.yaml\n\n```\nversion: '3.8'\n\nservices:\n web:\n restart: always\n volumes: []\n```\n\nYou are right. When I remove the volumes from my docker-compose.yaml it works fine.\nI start my application with this command:\n\n```\ndocker compose -f docker-compose.yaml -f production.yaml up --build\n```\n\nWhy is production.yaml not overwritten the docker-compose volume entry?\n\n========================================\n\nCode:\n```text\nFROM node:18.17.1-bullseye as build-stage\n\nWORKDIR /app\nCOPY . .\nRUN yarn install\nRUN yarn build\n\nFROM node:18.17.1-bullseye as production-stage\nRUN mkdir /app\nCOPY --from=build-stage /app/.output /app/.output\n\n\n\nENTRYPOINT [\"node\", \".output/server/index.mjs\"]\n```\n\n```text\nnode:internal/modules/cjs/loader:1080\n throw err;\n ^\n \n Error: Cannot find module '/app/.output/server/index.mjs'\n at Module._resolveFilename (node:internal/modules/cjs/loader:1077:15)\n at Module._load (node:internal/modules/cjs/loader:922:27)\n at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)\n at node:internal/main/run_main_module:23:47 {\n code: 'MODULE_NOT_FOUND',\n requireStack: []\n }\n \n Node.js v18.17.1\n exited with code 0\n```\n\n```text\nversion: '3'\n\nservices:\n web:\n build: .\n ports:\n - \"3000:3000\"\n volumes:\n - .:/app\n - /app/node_modules\n environment:\n - HOST=0.0.0.0\n```\n\n```text\nversion: '3.8'\n\nservices:\n web:\n restart: always\n volumes: []\n```\n\n```text\ndocker compose -f docker-compose.yaml -f production.yaml up --build\n```\n\n========================================\n\nComments:\n- can you your docker-compose.yaml file, this error maybe related to the volumes overwrites the node_modules folder\n- @yahyasghayron yes you are correct it can be caused by the overwrite but we need the docker-compose file to verify\n- I removed the volumes area and it is working. How can I override/deactivate volumes in my production file?\n- or try to rename the docker-compose.yaml to somting like `docker compose -f compose.yml -f production.yml up -d`","metadata":{"transformedAt":"2026-08-18T18:33:07.888Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":157,"estimatedTokens":842}}719{"id":"stack-67631547","source":"stackoverflow","questionId":67631547,"title":"Nuxt: Dynamic head / meta title is undefined on ssr","tags":["javascript","vue.js","nuxt.js","html-meta"],"text":"Title: Nuxt: Dynamic head / meta title is undefined on ssr\nTags: javascript, vue.js, nuxt.js, html-meta\nSource: Stack Overflow\n\nQuestion:\nI have a nuxt project, where the meta title and description comes (from nuxt/content).\nThe async fetch for the data is made in index and received in a sub component via a getter.\n\nOn generate, the meta tags are there but on ssr not :/\n\nI tried it with async and await, but I still get the error\n\nUncaught (in promise) TypeError: seoTitle is undefined\n\n(I tried it with a useless await this.getArticle const, in hope that the whole thing waits, this stuff is there, but no)\n\nHere my code:\n\n```\nasync head() {\n const article = await this.getArticle\n const seoTitle = await this.getArticle.seoTitle,\n title = await this.getArticle.title,\n seoDescription = await this.getArticle.description\n\n return {\n title: `\"${\n seoTitle.length ? seoTitle : title\n }\"`,\n meta: [\n {\n hid: \"description\",\n name: \"description\",\n content: `${\n seoDescription.length\n ? seoDescription.slice(0, 50)\n : seoDescription.slice(0, 50)\n }`,\n },\n ],\n };\n },\n```\n\n========================================\n\nCode:\n```text\nasync head() {\n const article = await this.getArticle\n const seoTitle = await this.getArticle.seoTitle,\n title = await this.getArticle.title,\n seoDescription = await this.getArticle.description\n\n return {\n title: `\"${\n seoTitle.length ? seoTitle : title\n }\"`,\n meta: [\n {\n hid: \"description\",\n name: \"description\",\n content: `${\n seoDescription.length\n ? seoDescription.slice(0, 50)\n : seoDescription.slice(0, 50)\n }`,\n },\n ],\n };\n },\n```\n\n```js\nhead() {\n return { title: this.info.title }\n},\nasync asyncData ({ params }) {\n return axios.get(`/post/${params.id}/info`)\n .then((res) => {\n return {\n info: res.data.info\n }\n }).catch((err) => {\n console.log(err)\n })\n},\n```\n\n```text\nasync\n```\n\n```text\nhead\n```\n\n```text\nasyncData\n```\n\n```text\nhead\n```\n\n========================================\n\nComments:\n- @TimothyAlexisVass why would it not? I don't use them neither and ESlint does it job perfectly. Also, what do you mean by `On generate, the meta tags are there but on ssr not`. You do have `target: static` and `ssr: true`, right? How can they be there on generate?\n- Yeah, thanks. I might have not expressed it detailed enough. Actually it happens in dev mode. I get data already wih asyncDate. When I export it into static files (via generate --modern) it adds the meta tags correctly. So that is fine. But I am wondering how to archive that in ssr mode? Or will it just work, once I run build? And if not, how to have conditional meta tags, like I want to have them by: seoTitle.length ? seoTitle : title\n- My first question is still valid. Also, try building your app locally to debug this.\n- Yes @kissu target is statis, ssr is not at all in the config file. (Currently the project is supposed to be static only. But my next project wont be)\n- `ssr: true` is the default and with `target: static`, you should be good. Does it work when you're `yarn generate` + `yarn start`, do you see your meta?\n- Hi @kissu, yes that works, but that was my initial setting (\"On generate, the meta tags ...\"). I just wonder, how I would that work, if it would not be a static app.\n- With my solution and `target: server`, it should work as well IMO. Just remember to `yarn build` + `yarn start`.\n- if the above doesn’t work out check out stackoverflow.com/questions/70328833/…","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":116,"estimatedTokens":893}}720{"id":"stack-73796712","source":"stackoverflow","questionId":73796712,"title":"Nuxt Cannot load payload _payload.js TypeError: Failed to resolve module specifier '_payload.js'","tags":["vue.js","nuxt.js","nuxt3.js"],"text":"Title: Nuxt Cannot load payload _payload.js TypeError: Failed to resolve module specifier '_payload.js'\nTags: vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nIn My project, nuxt3 version is `\"nuxt\": \"^3.0.0-rc.10\",`\n\nEverything is ok on my dev server. But when I generate pages using `npm run generate` and serve using `npm run preview` I get this below error,\n\n```\nentry.a89924e4.js:5 [nuxt] Cannot load payload _payload.js TypeError: Failed to resolve module specifier '_payload.js'\n at entry.a89924e4.js:5:30975\n at ht (entry.a89924e4.js:5:30106)\n at qk (entry.a89924e4.js:5:30968)\n at Hk (entry.a89924e4.js:5:30683)\n at e (entry.a89924e4.js:3072:7911)\n at entry.a89924e4.js:3072:8045\n at entry.a89924e4.js:1:78708\n at async Promise.all (:45915/index 0)\n at async entry.a89924e4.js:5:32621\n```\n\nI don't know from where this error might be generated.\n\n========================================\n\nCode:\n```text\nentry.a89924e4.js:5 [nuxt] Cannot load payload _payload.js TypeError: Failed to resolve module specifier '_payload.js'\n at entry.a89924e4.js:5:30975\n at ht (entry.a89924e4.js:5:30106)\n at qk (entry.a89924e4.js:5:30968)\n at Hk (entry.a89924e4.js:5:30683)\n at e (entry.a89924e4.js:3072:7911)\n at entry.a89924e4.js:3072:8045\n at entry.a89924e4.js:1:78708\n at async Promise.all (:45915/index 0)\n at async entry.a89924e4.js:5:32621\n```\n\n```text\n\"nuxt\": \"^3.0.0-rc.10\",\n```\n\n```text\nnpm run generate\n```\n\n```text\nnpm run preview\n```\n\n```text\n<nuxt-link to=\"#\">Link</nuxt-link>\n```\n\n========================================\n\nComments:\n- Does it also happen on `3.0.0-rc.11`? Can you provide a reproduction?\n- Just updated to rc.11 getting same error. I will try to provide a reproduction as soon as possible.\n- I have used hash(#) in my unused link i.e `Link` That is one of the reason I am getting error in generated file.\n- Yes, it solved my above mentioned issue.","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":63,"estimatedTokens":478}}721{"id":"stack-69340160","source":"stackoverflow","questionId":69340160,"title":"Synchronize Vuex store with server side in Nuxt.js","tags":["nuxt.js","vuex","vuex-module-decorators"],"text":"Title: Synchronize Vuex store with server side in Nuxt.js\nTags: nuxt.js, vuex, vuex-module-decorators\nSource: Stack Overflow\n\nQuestion:\n### Problem\n\nBelow Nuxt middleware\n\n```\nconst inspectAuthentication: Middleware = async (): Promise => {\n await AuthenticationService.getInstance().inspectAuthentication();\n};\n```\n\nis being executed on the server side before return each page's HTML and checks has been user authenticated. If has been, it stores the `CurrentAuthenticatedUser` in Vuex module:\n\n```\nimport {\n VuexModule,\n getModule as getVuexModule,\n Module as VuexModuleConfiguration,\n VuexAction,\n VuexMutation\n} from \"nuxt-property-decorator\";\n\n@VuexModuleConfiguration({\n name: \"AuthenticationService\",\n store,\n namespaced: true,\n stateFactory: true,\n dynamic: true\n})\nexport default class AuthenticationService extends VuexModule {\n\n public static getInstance(): AuthenticationService {\n return getVuexModule(AuthenticationService);\n }\n\n private _currentAuthenticatedUser: CurrentAuthenticatedUser | null = null;\n\n public get currentAuthenticatedUser(): CurrentAuthenticatedUser | null {\n return this._currentAuthenticatedUser;\n }\n\n @VuexAction({ rawError: true })\n public async inspectAuthentication(): Promise {\n\n // This condition is always falsy after page reloading\n if (this.isAuthenticationInspectionSuccessfullyComplete) {\n return isNotNull(this._currentAuthenticatedUser);\n }\n\n this.onAuthenticationInspectionStarted();\n\n // The is no local storage on server side; use @nuxtjs/universal-storage instead\n const accessToken: string | null = DependenciesInjector.universalStorageService.\n getItem(AuthenticationService.ACCESS_TOKEN_KEY_IN_LOCAL_STORAGE);\n\n if (isNull(accessToken)) {\n this.completeAuthenticationInspection();\n return false;\n }\n\n let currentAuthenticatedUser: CurrentAuthenticatedUser | null;\n\n try {\n\n currentAuthenticatedUser = await DependenciesInjector.gateways.authentication.getCurrentAuthenticatedUser(accessToken);\n\n } catch (error: unknown) {\n\n this.onAuthenticationInspectionFailed();\n // error wrapping / rethrowing\n }\n\n if (isNull(currentAuthenticatedUser)) {\n this.completeAuthenticationInspection();\n return false;\n }\n\n this.completeAuthenticationInspection(currentAuthenticatedUser);\n\n return true;\n }\n\n @VuexMutation\n private completeAuthenticationInspection(currentAuthenticatedUser?: CurrentAuthenticatedUser): void {\n\n if (isNotUndefined(currentAuthenticatedUser)) {\n this._currentAuthenticatedUser = currentAuthenticatedUser;\n DependenciesInjector.universalStorageService.setItem(\n AuthenticationService.ACCESS_TOKEN_KEY_IN_LOCAL_STORAGE, currentAuthenticatedUser.accessToken\n );\n }\n\n // ...\n }\n}\n```\n\nAbove code works fine on server side, but then, on the client side, if to try to get `AuthenticationService.getInstance().currentAuthenticatedUser`, it will be `null`!\nI expected that Nuxt.js synchronizes the Vuex store including `AuthenticationService` with server side, however, it does not.\n\n### Target\n\n`AuthenticationService` must be synchronized with server side, so if user has been authenticated, in the client side `AuthenticationService.getInstance().currentAuthenticatedUser` it must be non-null even after page reloading.\n\nThere no need to synchronize whole Vuex store in server side (for example, the module responsible floating notification bar is required in the client side only) but if the selective methodology has not been developed, at least synchronizing of whole Vuex store will be enough for now.\n\n**Please don't recommend me the libraries or Nuxt modules for authentication** like Nuxt Auth module because here we are talking about synchronizing of the Vuex store with server, not about best Nuxt modules for authentication. Also, the syncronizing of the vuex store between client and server could be used not just for authentication.\n\n### Update\n\n### `preserveState` solution attempt\n\nUnfortunately,\n\n```\nimport { store } from \"~/Store\";\nimport { VuexModule, Module as VuexModuleConfiguration } from \"nuxt-property-decorator\";\n\n@VuexModuleConfiguration({\n name: \"AuthenticationService\",\n store,\n namespaced: true,\n stateFactory: true,\n dynamic: true,\n preserveState: true /* New */\n})\nexport default class AuthenticationService extends VuexModule {}\n```\n\ncauses\n\n```\nCannot read property '_currentAuthenticatedUser' of undefined\n```\n\nerror on the server side.\n\nhttps://i.sstatic.net/oHcse.png\n\nThe error refers to\n\n```\n@VuexAction({ rawError: true })\npublic async inspectAuthentication(): Promise {\n if (this.isAuthenticationInspectionSuccessfullyComplete) {\n // HERE ⇩\n return isNotNull(this._currentAuthenticatedUser);\n }\n}\n```\n\nI checked `this` value. It's a big object; I'll leave the the noticable part only:\n\n```\n{ \n store: Store {\n _committing: false,\n // === ✏ All actual action here\n _actions: [Object: null prototype] {\n 'AuthenticationService/inspectAuthentication': [Array],\n 'AuthenticationService/signIn': [Array],\n 'AuthenticationService/applySignUp': [Array],\n // ... \n\n // === ✏ Some mutations ...\n onAuthenticationInspectionStarted: [Function (anonymous)],\n completeAuthenticationInspection: [Function (anonymous)],\n // ...\n context: {\n dispatch: [Function (anonymous)],\n commit: [Function (anonymous)],\n getters: {\n currentAuthenticatedUser: [Getter],\n isAuthenticationInspectionSuccessfullyComplete: [Getter]\n },\n // === ✏ The state in undefined!\n state: undefined\n }\n}\n```\n\nI suppose I need to tell how I initializing the vuex store.\nThe working Nuxt methodology for dynamic modules is:\n\n```\n// store/index.ts\nimport Vue from \"vue\";\nimport Vuex, { Store } from \"vuex\";\n\nVue.use(Vuex);\n\nexport const store: Store = new Vuex.Store({});\n```\n\n### `nuxtServerInit` solution attempt\n\nHere is the another problem - how to integrate `nuxtServerInit` in above store initialization method? I suppose, to answer this question it's required the Vuex and vuex-module-decorators. In below `store/index.ts`, the `nuxtServerInit` even will not be called:\n\n```\nimport Vue from \"vue\";\nimport Vuex, { Store } from \"vuex\";\n\nVue.use(Vuex);\n\nexport const store: Store = new Vuex.Store({\n actions: {\n nuxtServerInit(blackbox: unknown): void {\n console.log(\"----------------\");\n console.log(blackbox);\n }\n }\n});\n```\n\nI extracted this problem to other question.\n\n========================================\n\nCode:\n```js\nconst inspectAuthentication: Middleware = async (): Promise<void> => {\n await AuthenticationService.getInstance().inspectAuthentication();\n};\n```\n\n```js\nimport {\n VuexModule,\n getModule as getVuexModule,\n Module as VuexModuleConfiguration,\n VuexAction,\n VuexMutation\n} from \"nuxt-property-decorator\";\n\n\n@VuexModuleConfiguration({\n name: \"AuthenticationService\",\n store,\n namespaced: true,\n stateFactory: true,\n dynamic: true\n})\nexport default class AuthenticationService extends VuexModule {\n\n public static getInstance(): AuthenticationService {\n return getVuexModule(AuthenticationService);\n }\n\n\n private _currentAuthenticatedUser: CurrentAuthenticatedUser | null = null;\n\n public get currentAuthenticatedUser(): CurrentAuthenticatedUser | null {\n return this._currentAuthenticatedUser;\n }\n\n\n @VuexAction({ rawError: true })\n public async inspectAuthentication(): Promise<boolean> {\n\n // This condition is always falsy after page reloading\n if (this.isAuthenticationInspectionSuccessfullyComplete) {\n return isNotNull(this._currentAuthenticatedUser);\n }\n\n\n this.onAuthenticationInspectionStarted();\n\n // The is no local storage on server side; use @nuxtjs/universal-storage instead\n const accessToken: string | null = DependenciesInjector.universalStorageService.\n getItem(AuthenticationService.ACCESS_TOKEN_KEY_IN_LOCAL_STORAGE);\n\n if (isNull(accessToken)) {\n this.completeAuthenticationInspection();\n return false;\n }\n\n\n let currentAuthenticatedUser: CurrentAuthenticatedUser | null;\n\n try {\n\n currentAuthenticatedUser = await DependenciesInjector.gateways.authentication.getCurrentAuthenticatedUser(accessToken);\n\n } catch (error: unknown) {\n\n this.onAuthenticationInspectionFailed();\n // error wrapping / rethrowing\n }\n\n\n if (isNull(currentAuthenticatedUser)) {\n this.completeAuthenticationInspection();\n return false;\n }\n\n\n this.completeAuthenticationInspection(currentAuthenticatedUser);\n\n return true;\n }\n\n @VuexMutation\n private completeAuthenticationInspection(currentAuthenticatedUser?: CurrentAuthenticatedUser): void {\n\n if (isNotUndefined(currentAuthenticatedUser)) {\n this._currentAuthenticatedUser = currentAuthenticatedUser;\n DependenciesInjector.universalStorageService.setItem(\n AuthenticationService.ACCESS_TOKEN_KEY_IN_LOCAL_STORAGE, currentAuthenticatedUser.accessToken\n );\n }\n\n // ...\n }\n}\n```\n\n```text\nimport { store } from \"~/Store\";\nimport { VuexModule, Module as VuexModuleConfiguration } from \"nuxt-property-decorator\";\n\n\n@VuexModuleConfiguration({\n name: \"AuthenticationService\",\n store,\n namespaced: true,\n stateFactory: true,\n dynamic: true,\n preserveState: true /* New */\n})\nexport default class AuthenticationService extends VuexModule {}\n```\n\n```text\nCannot read property '_currentAuthenticatedUser' of undefined\n```\n\n```js\n@VuexAction({ rawError: true })\npublic async inspectAuthentication(): Promise<boolean> {\n if (this.isAuthenticationInspectionSuccessfullyComplete) {\n // HERE ⇩\n return isNotNull(this._currentAuthenticatedUser);\n }\n}\n```\n\n```js\n{ \n store: Store {\n _committing: false,\n // === ✏ All actual action here\n _actions: [Object: null prototype] {\n 'AuthenticationService/inspectAuthentication': [Array],\n 'AuthenticationService/signIn': [Array],\n 'AuthenticationService/applySignUp': [Array],\n // ... \n\n // === ✏ Some mutations ...\n onAuthenticationInspectionStarted: [Function (anonymous)],\n completeAuthenticationInspection: [Function (anonymous)],\n // ...\n context: {\n dispatch: [Function (anonymous)],\n commit: [Function (anonymous)],\n getters: {\n currentAuthenticatedUser: [Getter],\n isAuthenticationInspectionSuccessfullyComplete: [Getter]\n },\n // === ✏ The state in undefined!\n state: undefined\n }\n}\n```\n\n```js\n// store/index.ts\nimport Vue from \"vue\";\nimport Vuex, { Store } from \"vuex\";\n\n\nVue.use(Vuex);\n\nexport const store: Store<unknown> = new Vuex.Store<unknown>({});\n```\n\n```js\nimport Vue from \"vue\";\nimport Vuex, { Store } from \"vuex\";\n\n\nVue.use(Vuex);\n\nexport const store: Store<unknown> = new Vuex.Store<unknown>({\n actions: {\n nuxtServerInit(blackbox: unknown): void {\n console.log(\"----------------\");\n console.log(blackbox);\n }\n }\n});\n```\n\n```text\nCurrentAuthenticatedUser\n```\n\n```text\nAuthenticationService.getInstance().currentAuthenticatedUser\n```\n\n```text\nnull\n```\n\n```text\nAuthenticationService\n```\n\n```text\nAuthenticationService\n```\n\n```text\nAuthenticationService.getInstance().currentAuthenticatedUser\n```\n\n```text\npreserveState\n```\n\n```text\nthis\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nstore/index.ts\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nserverPrefetch\n```\n\n```text\nrendered\n```\n\n```text\nregisterModule\n```\n\n```text\npreserveState\n```\n\n```text\nnuxtServerInit\n```\n\n```text\ncontext\n```\n\n```text\nstore\n```\n\n```text\nnuxt-property-decorator\n```\n\n```text\nthis\n```\n\n```text\nnuxt-property-decorator\n```\n\n========================================\n\nComments:\n- Thank you for the answer! Because this mechanism must work regardless of the specific component, **3rd** solution and **last** solution could be appropriate. I tried both, but there are more related problem occurred. May I ask you to check the \"Update\" section of question?\n- @TakeshiTokugawaYD, please take a look on the \"Updates\" section to see if you find it helpful\n- Let's make a verdict. You has explained why this problem occurred and common solution approach. That's why I accepted your answer and upvoted it. The issue comes down to nuxt-property-decorator/vuex-module-decorators problems which will be discussed in How to make visible the \"nuxtServerInit\" action for Nuxt.js action in the case with dynamic modules only?. Thank you for the answer again!\n- Glad to help @TakeshiTokugawaYD! :)","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":30,"totalLines":501,"estimatedTokens":3080}}722{"id":"stack-51055519","source":"stackoverflow","questionId":51055519,"title":"Allow natural back button behaviour with use case of dynamically-added query parameters","tags":["vue.js","router","vuex","back","nuxt.js"],"text":"Title: Allow natural back button behaviour with use case of dynamically-added query parameters\nTags: vue.js, router, vuex, back, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have the case that I push some parameters to the nuxt router (https://router.vuejs.org/guide/essentials/navigation.html) whenever somebody visits a page without any parameters.\n\nExample:\nsomebody visits: `/program` it will end up in `/program/first-event?year=2018&month=6`\n(First the view filters the program for current events (therefore the parameters for this year and this month) and then from the filtered events it will set the first event as active post (also by pushing it to the router).\n\nThis is all wanted and good. BUT now I detected the following problem:\nSomebody is visiting `/aboutus` and then navigates to `/program`, the router will automatically change to `/program/url-of-event-post?year=2018&month=6`.\nAssuming the user wants to go back to `/aboutus` he clicks on the browser back button. This will bring him back to: `/program` which automatically adds the post and the parameters again (effectively moving one step forward again).\n\nMeans the user is caught in clicking endlessly on the back button.\nMy approach would be to try to register if a user clicks on the back button and if so, I would not add the parameters. But I don't know how to do this.\nI thought the router would provide some 'from' property, but so far I did not find anything.\n\nI would be very happy to hear some thoughts on this. Thank you heaps in advance.\n\n========================================\n\nCode:\n```text\n/program\n```\n\n```text\n/program/first-event?year=2018&month=6\n```\n\n```text\n/aboutus\n```\n\n```text\n/program\n```\n\n```text\n/program/url-of-event-post?year=2018&month=6\n```\n\n```text\n/aboutus\n```\n\n```text\n/program\n```\n\n```text\nrouter.replace\n```\n\n========================================\n\nComments:\n- Oh that's sounds good. I will try it. Thanks a lot! Important is taht this will also trigger a router change, when watching the router, but I guess it will and I will report back here :D\n- Worked like a charm by the way!\n- @Merc can you post your actual solution to this issue?\n- @podcastfan88 Sorry I somehow never got informed about your post. I also see that 6 people would have an interest in that... So years later: `this.$router.replace({ path: `/${this.page.slug}/${firstPostInFuture.slug}`, query: this.$route.query })`. Something like this. Worth mentioning: the page's slug = `program` whereas I have a computed property that returns the slug for the first post in the future. In my example here, I just copy the current queries, but if you want somethin like the `year` `month` queries, just add them instead to your query object. I hope that helps.\n- This solution doesn't match the original title of this question.","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":64,"estimatedTokens":703}}723{"id":"stack-67737667","source":"stackoverflow","questionId":67737667,"title":"Shared stores on multi applications Nuxt","tags":["nuxt.js","vuex"],"text":"Title: Shared stores on multi applications Nuxt\nTags: nuxt.js, vuex\nSource: Stack Overflow\n\nQuestion:\nI build multi-app Nuxt project, those apps don't communicate directly between them.\nEach app has own store and I want to use a directory for shared stores. I use this approach with components and that works fine.\n\n```\n|-> app1\n| |-> store // store app1\n| | |-> moduleapp1.js\n| |-> components // component app1\n| |-> nuxt.config.js\n|\n|-> app2\n| |-> store // store app2\n| | |-> moduleapp2.js\n| |-> components // component app2\n| |-> nuxt.config.js\n|\n|-> store // shared stores for all app\n| |-> shared_module_1.js\n| |-> shared_module_2.js\n|-> components // components for all app, that works fine\n```\n\nEach app has a nuxt.config.js almost similar :\n\n```\nexport default {\n srcDir: __dirname,\n buildDir: '.nuxt/app1',\n dir: {\n static: '../static/', //shared static\n assets: '../assets/', //shared assets\n //store: allow only a string, not Array \n },\n plugins: [\n '../plugins/plugin_1', //own plugin\n './plugins/plugin_2', //shared plugin\n ],\n components: [\n '../components', //shared components\n {\n path: '../components/grid/', //shared components\n ignore: './filter/*.vue' //shared components\n\n },\n {path: './components/modal/', prefix: 'Modal'}, //own component\n {path: './components/nav/', prefix: 'Nav'}, //own component\n ]\n}\n```\n\nhttps://nuxtjs.org/docs/2.x/configuration-glossary/configuration-dir\n\nEach app uses own and shared components also plugins and that works fine.\nBut I don't find how I can do that with store, is it possible ?\n\n========================================\n\nCode:\n```text\n|-> app1\n| |-> store // store app1\n| | |-> moduleapp1.js\n| |-> components // component app1\n| |-> nuxt.config.js\n|\n|-> app2\n| |-> store // store app2\n| | |-> moduleapp2.js\n| |-> components // component app2\n| |-> nuxt.config.js\n|\n|-> store // shared stores for all app\n| |-> shared_module_1.js\n| |-> shared_module_2.js\n|-> components // components for all app, that works fine\n```\n\n```text\nexport default {\n srcDir: __dirname,\n buildDir: '.nuxt/app1',\n dir: {\n static: '../static/', //shared static\n assets: '../assets/', //shared assets\n //store: allow only a string, not Array \n },\n plugins: [\n '../plugins/plugin_1', //own plugin\n './plugins/plugin_2', //shared plugin\n ],\n components: [\n '../components', //shared components\n {\n path: '../components/grid/', //shared components\n ignore: './filter/*.vue' //shared components\n\n },\n {path: './components/modal/', prefix: 'Modal'}, //own component\n {path: './components/nav/', prefix: 'Nav'}, //own component\n ]\n}\n```\n\n```js\n// plugin/loadStore.js\n// - List of shared stores\nimport Grid from '../store/grid';\nimport Map from '../store/map';\nimport Sidebar from '../store/sidebar';\n\nexport default ({isClient, store}) => {\n\n const opts = {}\n if (isClient) {\n opts.preserveState = true;\n }\n\n store.registerModule('grid', Grid, opts);\n store.registerModule('map', Map, opts);\n store.registerModule('sidebar', Sidebar, opts);\n};\n```\n\n========================================\n\nComments:\n- Hm, I may be wrong but this **seems** impossible to me.\n- Thanks, but with components this conception works fine.\n- Being outside of the project is a totally whole different thing aka, exporting your state outside of your codebase and importing it somewhere else. It's not like it's some plain text, but some dynamic runtime values. So yeah, not the same scope at all.\n- But I'm maybe wrong. I guess that an example of what you already did could maybe prove that I'm wrong. Do you have a minimal reproducible example?\n- One solution could be using the only store directory and set `dir:{store: '../store'}` and put in all modules in this directory. That will works, but all apps'll load modules which they never use. Not perfect!","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":136,"estimatedTokens":962}}724{"id":"stack-67284620","source":"stackoverflow","questionId":67284620,"title":"nuxt does not start on Arch","tags":["nuxt.js"],"text":"Title: nuxt does not start on Arch\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI can not start my nuxt development enviroment for 2 days. Before that I had no problem. If I go back to a previous version of the same app, it is also not starting.\n\n```\nnpm run dev\n\n> KrisnaNet@1.0.0 dev\n> nuxt\n\n ERROR (node:3576) [DEP0148] DeprecationWarning: Use of deprecated folder mapping \"./\" in the \"exports\" field module resolution of the package at /home/rrd/public_html/krisnaNet/node_modules/@nuxt/components/package.json.\nUpdate this package.json to use a subpath pattern like \"./*\".\n(Use `node --trace-deprecation ...` to show where the warning was created)\n\n ╭───────────────────────────────────────╮\n │ │\n │ Nuxt @ v2.15.4 │\n │ │\n │ ▸ Environment: development │\n │ ▸ Rendering: server-side │\n │ ▸ Target: static │\n │ │\n │ Listening: http://localhost:3000/ │\n │ │\n ╰───────────────────────────────────────╯\n\nℹ Preparing project for development 16:00:33\nℹ Initial build may take a while 16:00:33\nℹ Discovered Components: .nuxt/components/readme.md 16:00:33\n✔ Builder initialized 16:00:33\n✔ Nuxt files generated 16:00:33\n\n● Client █████████████████████████ building (43%) 283/293 modules 10 active\n node_modules/setimmediate/setImmediate.js\n\n● Server █████████████████████████ building (23%) 113/121 modules 8 active\n ...ostcss-loader › sass-loader › sass-resources-loader › vue-loader › layouts/default.vue\n\nnode: ../src/coroutine.cc:134: void* find_thread_id_key(void*): Assertion `thread_id_key != 0x7777' failed.\nfish: Job 1, 'npm run dev' terminated by signal SIGABRT (Abort)\n```\n\n========================================\n\nCode:\n```sh\nnpm run dev\n\n> KrisnaNet@1.0.0 dev\n> nuxt\n\n\n ERROR (node:3576) [DEP0148] DeprecationWarning: Use of deprecated folder mapping \"./\" in the \"exports\" field module resolution of the package at /home/rrd/public_html/krisnaNet/node_modules/@nuxt/components/package.json.\nUpdate this package.json to use a subpath pattern like \"./*\".\n(Use `node --trace-deprecation ...` to show where the warning was created)\n\n\n ╭───────────────────────────────────────╮\n │ │\n │ Nuxt @ v2.15.4 │\n │ │\n │ ▸ Environment: development │\n │ ▸ Rendering: server-side │\n │ ▸ Target: static │\n │ │\n │ Listening: http://localhost:3000/ │\n │ │\n ╰───────────────────────────────────────╯\n\nℹ Preparing project for development 16:00:33\nℹ Initial build may take a while 16:00:33\nℹ Discovered Components: .nuxt/components/readme.md 16:00:33\n✔ Builder initialized 16:00:33\n✔ Nuxt files generated 16:00:33\n\n● Client █████████████████████████ building (43%) 283/293 modules 10 active\n node_modules/setimmediate/setImmediate.js\n\n● Server █████████████████████████ building (23%) 113/121 modules 8 active\n ...ostcss-loader › sass-loader › sass-resources-loader › vue-loader › layouts/default.vue\n\nnode: ../src/coroutine.cc:134: void* find_thread_id_key(void*): Assertion `thread_id_key != 0x7777' failed.\nfish: Job 1, 'npm run dev' terminated by signal SIGABRT (Abort)\n```\n\n```text\nfibers\n```\n\n========================================\n\nComments:\n- Pretty sure this is totally unrelated to arch if you did not upgraded anything. Do you have some git changes ? Maybe just typo'ed in your editor while it had your mouse focus ? What is the content of `coroutine.cc` ?\n- This is part of the fiber package. The fle is here controlc.com/27cf1c1b I reinstalled all packages, it is not a typo I guess.\n- I am having the same issue in Gitlab CI deployment. On my local machine it works just fine. Did you find a solution already?\n- it is caused by node 16 and fibers incompatibility\n- it is caused by node 16 and fibers incompatibility","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":100,"estimatedTokens":1072}}725{"id":"stack-70177053","source":"stackoverflow","questionId":70177053,"title":"reload=true not working in @click function","tags":["javascript","vue.js","nuxt.js"],"text":"Title: reload=true not working in @click function\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI was working on currency switcher. i call method on click the link and after method successful want it to reload. but reload is not working at all. currency getting stored in cookie, if i refresh page manually it gets updated in navbar too, but i want it to reload automatically once method complete.\n\nhere is the code in navbar..\n\n```\n\n \n \n {{currency}}\n \n \n \n \n {{item.fullname}} ({{item.iso}})\n \n\n```\n\nthis is method.\n\n```\nmethods: {\n setCurrency(newcurrency) {\n this.$cookies.set(`usercurrency`, newcurrency, {\n path: '/',\n maxAge: 60 * 60 * 24 * 7\n })\n // window.location.href = '/'\n }\n}\n```\n\nI thought to use `window.location.href = '/'` after setting cookie but i can't do it because i am using the same method in created hook like below code to set currency based on user country and it will say window not defined.\n\n```\ncreated() {\n const isCurrency = this.$cookies.get('usercurrency')\n const isUserCountry = this.$cookies.get('usercountry')\n if (isCurrency === undefined) {\n if (isUserCountry === undefined) {\n fetch('https://ipinfo.io/json?token=*********')\n .then((response) => response.json())\n .then((jsonResponse) => {\n const country = jsonResponse.country\n this.$cookies.set(`usercountry`, country, {\n path: '/',\n maxAge: 60 * 60 * 24 * 7,\n })\n var CurrencyParam\n switch (country) {\n case 'IN':\n case 'NP':\n CurrencyParam = 'INR'\n break\n case 'US':\n CurrencyParam = 'USD'\n break\n case 'AU':\n CurrencyParam = 'AUD'\n break\n case 'CA':\n CurrencyParam = 'CAD'\n break\n case 'GB':\n CurrencyParam = 'GBP'\n break\n case 'AE':\n CurrencyParam = 'AED'\n break\n case 'RU':\n CurrencyParam = 'RUB'\n break\n case 'JP':\n CurrencyParam = 'JPY'\n break\n case 'SG':\n CurrencyParam = 'SGD'\n break\n case 'FR':\n case 'FI':\n case 'DE':\n case 'GR':\n case 'HU':\n case 'IT':\n case 'LT':\n case 'MT':\n case 'NL':\n case 'NO':\n case 'PL':\n case 'PT':\n case 'RO':\n case 'RS':\n case 'ES':\n case 'SE':\n case 'CH':\n case 'UA':\n CurrencyParam = 'EUR'\n break\n default:\n CurrencyParam = 'USD'\n }\n this.setCurrency(CurrencyParam)\n })\n .catch((error) => {\n console.log(error)\n this.setCurrency('USD')\n })\n }\n }\n},\n```\n\n========================================\n\nCode:\n```html\n<b-dropdown position=\"is-bottom-left\" aria-role=\"menu\">\n <template #trigger>\n <a class=\"navbar-item font-bold\" role=\"button\">\n {{currency}}\n <b-icon icon=\"menu-down\"></b-icon>\n </a>\n </template>\n <b-dropdown-item v-for=\"(item, index) in currencies\" :key=\"index\" has-link aria-role=\"menuitem\">\n <a class=\"no-underline\" @click=\"setCurrency(item.iso, (reload = true))\"><span class=\"text-pink-600 font-bold\">{{item.fullname}} ({{item.iso}})</span></a>\n </b-dropdown-item>\n</b-dropdown>\n```\n\n```js\nmethods: {\n setCurrency(newcurrency) {\n this.$cookies.set(`usercurrency`, newcurrency, {\n path: '/',\n maxAge: 60 * 60 * 24 * 7\n })\n // window.location.href = '/'\n }\n}\n```\n\n```js\ncreated() {\n const isCurrency = this.$cookies.get('usercurrency')\n const isUserCountry = this.$cookies.get('usercountry')\n if (isCurrency === undefined) {\n if (isUserCountry === undefined) {\n fetch('https://ipinfo.io/json?token=*********')\n .then((response) => response.json())\n .then((jsonResponse) => {\n const country = jsonResponse.country\n this.$cookies.set(`usercountry`, country, {\n path: '/',\n maxAge: 60 * 60 * 24 * 7,\n })\n var CurrencyParam\n switch (country) {\n case 'IN':\n case 'NP':\n CurrencyParam = 'INR'\n break\n case 'US':\n CurrencyParam = 'USD'\n break\n case 'AU':\n CurrencyParam = 'AUD'\n break\n case 'CA':\n CurrencyParam = 'CAD'\n break\n case 'GB':\n CurrencyParam = 'GBP'\n break\n case 'AE':\n CurrencyParam = 'AED'\n break\n case 'RU':\n CurrencyParam = 'RUB'\n break\n case 'JP':\n CurrencyParam = 'JPY'\n break\n case 'SG':\n CurrencyParam = 'SGD'\n break\n case 'FR':\n case 'FI':\n case 'DE':\n case 'GR':\n case 'HU':\n case 'IT':\n case 'LT':\n case 'MT':\n case 'NL':\n case 'NO':\n case 'PL':\n case 'PT':\n case 'RO':\n case 'RS':\n case 'ES':\n case 'SE':\n case 'CH':\n case 'UA':\n CurrencyParam = 'EUR'\n break\n default:\n CurrencyParam = 'USD'\n }\n this.setCurrency(CurrencyParam)\n })\n .catch((error) => {\n console.log(error)\n this.setCurrency('USD')\n })\n }\n }\n},\n```\n\n```text\nwindow.location.href = '/'\n```\n\n```js\nmethods: {\n setCurrency(newcurrency, reload) {\n this.$cookies.set(`usercurrency`, newcurrency, {\n path: '/',\n maxAge: 60 * 60 * 24 * 7\n })\n if (reload) window.location.href = '/'\n }\n}\n```\n\n```text\nreload\n```\n\n```text\nsetCurrency\n```\n\n========================================\n\nComments:\n- So you're nuking the whole SPA here??\n- may be my approach is perfectly wrong here ! can you suggest some other way to achieve this as i am using nuxt. i am very new to vue and nuxtjs. i would love to your idea in implementing this\n- Usually, in Vue (or Nuxt, the same in this case), you're working with state that is reactive and updates when you touch it properly. Here, you will be nuking the whole SPA, which will have a lot of issues in terms of performance, on top of breaking everything. So yeah, this is 100% wrong. I'm not sure how you're handling the currency in your app, but you should mutate this one **only** and not nuke the page. As of how exactly, it depends and it will take a decent amount of time to rewrite properly. You could probably google on ways to handle i18n, because it is somehow similar here.\n- Why not set your currencies up in a JSON file, or at least an array? Your code would be much cleaner.\n- @Paul there are indeed several ways to improve the code here.\n- @kissu , i want to understand, how this nukes the page. i am really trying to understand everything you said, also i looked for nuxt i18n module, where i can use currency by number localization but is there any solution to redirect user to exact country, because i can see an option there to redirect using browser language but the problem is some english language countries set english united states as default, if i will put USD as currency for en-US and if user is from india has en-US in his browser, how can i redirect him to en-IN forcely or is there any other option there.\n- @V.Thakur this nukes the page because you're reloading the tab and breaking the SPA. If you google articles to understand how an SPA works, you'll see that an F5 or a paste and submit in the URL will break the SPA: you'll see your page flashing in blank. I was talking about i18n regarding the way it is implemented, you could do the same for currency but it's not directly a solution per-se.","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":258,"estimatedTokens":1835}}726{"id":"stack-68929582","source":"stackoverflow","questionId":68929582,"title":"How to reference an external function in nuxt.config?","tags":["vue.js","nuxt.js"],"text":"Title: How to reference an external function in nuxt.config?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSo basically I'm setting up an app using nuxt, and within the configuration's `generate` property I need to run a recursive function to build the sites route tree dynamically. The function is rather large so I dont want it to be in the config file itself\n\nIve tried doing it this way, but think Im way off\n\n```\nimport {buildChildRoutes} from 'routeGenerator'\n\nexport default {\n generate: {\n routes(){\n var response = await this.$deliveryClient\n .itemsFeedAll() \n .toPromise();\n\n return buildChildRoutes(response)\n })\n```\n\nhas anyone done something like this before? i would assume its common and im just missing something in the documentation\n\n========================================\n\nCode:\n```js\nimport {buildChildRoutes} from 'routeGenerator'\n\nexport default {\n generate: {\n routes(){\n var response = await this.$deliveryClient\n .itemsFeedAll() \n .toPromise();\n\n return buildChildRoutes(response)\n })\n```\n\n```text\ngenerate\n```\n\n```js\nimport getRoutes from './utils/route-generator.js'\n\nconst dynamicRoutes = () => {\n return new Promise((resolve) => {\n resolve(getRoutes())\n })\n}\n\nexport default {\n generate: {\n routes: dynamicRoutes\n }\n}\n```\n\n```text\nnuxt.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":65,"estimatedTokens":336}}727{"id":"stack-69062362","source":"stackoverflow","questionId":69062362,"title":"How to use .env value in nuxt.config.js with runtime config","tags":["javascript","vue.js","nuxt.js"],"text":"Title: How to use .env value in nuxt.config.js with runtime config\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm searching how to use a .env value in nuxt.config.js with runtime config.\n\nDeclare it, to use it in \"normal\" code is ok.\n\n```\npublicRuntimeConfig: {\n URL_API: process.env.URL_API || 'http://localhost:8000/',\n },\n```\n\nBut I want use .env value like this in my nuxt.config.js\n\n```\nauth: {\n strategies: {\n local: {\n token: {\n property: 'token',\n required: true,\n maxAge: 1000 * 60 * 60\n },\n user: {\n property: 'user',\n autoFetch: false\n },\n clientID: true,\n endpoints: {\n login: { url: `${process.env.URL_API}/auth/login`, method: 'post' },\n logout: { url: `${process.env.URL_API}/auth/logout`, method: 'post' },\n },\n tokenType: ''\n }\n },\n redirect: {\n login: '/auth/login',\n logout: '/',\n callback: '/auth/login',\n home: '/'\n }\n },\n```\n\nAny idea?\n\n========================================\n\nTop Answer:\nYou can use dotenv package to use variables from .env file in nuxt.config.js.\n\nnuxt.config.js file should look like this:\n\n```\n// your imports here\n\nrequire('dotenv').config()\n\n// nuxt config here\n```\n\n========================================\n\nCode:\n```text\npublicRuntimeConfig: {\n URL_API: process.env.URL_API || 'http://localhost:8000/',\n },\n```\n\n```text\nauth: {\n strategies: {\n local: {\n token: {\n property: 'token',\n required: true,\n maxAge: 1000 * 60 * 60\n },\n user: {\n property: 'user',\n autoFetch: false\n },\n clientID: true,\n endpoints: {\n login: { url: `${process.env.URL_API}/auth/login`, method: 'post' },\n logout: { url: `${process.env.URL_API}/auth/logout`, method: 'post' },\n },\n tokenType: ''\n }\n },\n redirect: {\n login: '/auth/login',\n logout: '/',\n callback: '/auth/login',\n home: '/'\n }\n },\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nprocess.env.MY_VARIABLE\n```\n\n```text\n// your imports here\n\nrequire('dotenv').config()\n\n// nuxt config here\n```\n\n========================================\n\nComments:\n- In NuxtJS, there is runtime config, which allow us to not use dotenv. I'm searching to use .env from with runtime config, not dotenv package\n- Please do not use `dotenv` since it's already baked in.\n- What does \"It is working if you're linking to an external file tho\" mean exactly?\n- @kano external file as in a `plugin`, rather than directly into the `nuxt.config.js` file. This is quite an old answer tho.","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":126,"estimatedTokens":632}}728{"id":"stack-76562209","source":"stackoverflow","questionId":76562209,"title":"Nuxt 3 can't load Material Design Icons with Vuetify in production build","tags":["nuxt.js","vuetify.js","nuxt3.js"],"text":"Title: Nuxt 3 can't load Material Design Icons with Vuetify in production build\nTags: nuxt.js, vuetify.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt 3 with Vuetify 3 and deploying with Amplify. In my web application, in local build the v-icon can display the icon correctly. But in the deployed app, the icons sometimes doesn't display properly.\n\nCorrect icon\n\nIncorrect icon\n\nI checked the network tab when the error happened but the font is already loaded\n\nNetwork tab 1\n\nNetwork tab 2\n\nCan anyone help me with this issue?\n\nThis is how i use the v-icon of Vuetify:\n\n```\n\n```\n\nI've installed @mdi/font and vuetify\n\n```\n\"dependencies\": {\n \"@mdi/font\": \"^7.2.96\",\n \"vuetify\": \"^3.2.1\"\n}\n```\n\nMy nuxt config:\n\n```\nexport default defineNuxtConfig({\n ssr: false,\n css: [\n 'vuetify/styles',\n '~/assets/css/main.css',\n '@mdi/font/css/materialdesignicons.min.css',\n ],\n})\n```\n\nMy Vuetify plugin:\n\n```\nexport default defineNuxtPlugin((nuxtApp) => {\n const vuetify = createVuetify({\n icons: {\n defaultSet: 'mdi',\n aliases,\n sets: {\n mdi,\n },\n },\n components: {\n ...labs,\n ...components,\n },\n directives,\n })\n\n nuxtApp.vueApp.use(vuetify)\n})\n```\n\nMy Amplify build setting:\n\n```\nversion: 1\nfrontend:\n phases:\n preBuild:\n commands:\n - yarn install\n build:\n commands:\n - yarn generate \n artifacts:\n # IMPORTANT - Please verify your build output directory\n baseDirectory: '.output/public'\n files:\n - '**/*'\n cache:\n paths:\n - node_modules/**/*\n```\n\n========================================\n\nCode:\n```js\n<v-icon icon=\"mdi-calendar-month-outline\" />\n```\n\n```json\n\"dependencies\": {\n \"@mdi/font\": \"^7.2.96\",\n \"vuetify\": \"^3.2.1\"\n}\n```\n\n```js\nexport default defineNuxtConfig({\n ssr: false,\n css: [\n 'vuetify/styles',\n '~/assets/css/main.css',\n '@mdi/font/css/materialdesignicons.min.css',\n ],\n})\n```\n\n```js\nexport default defineNuxtPlugin((nuxtApp) => {\n const vuetify = createVuetify({\n icons: {\n defaultSet: 'mdi',\n aliases,\n sets: {\n mdi,\n },\n },\n components: {\n ...labs,\n ...components,\n },\n directives,\n })\n\n nuxtApp.vueApp.use(vuetify)\n})\n```\n\n```yaml\nversion: 1\nfrontend:\n phases:\n preBuild:\n commands:\n - yarn install\n build:\n commands:\n - yarn generate \n artifacts:\n # IMPORTANT - Please verify your build output directory\n baseDirectory: '.output/public'\n files:\n - '**/*'\n cache:\n paths:\n - node_modules/**/*\n```\n\n========================================\n\nComments:\n- Did you figure out the issue?\n- @FreddyDaniel Had the same issue, switching to SVG icons resolved it\n- You can accept this answer :)","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":164,"estimatedTokens":659}}729{"id":"stack-58565115","source":"stackoverflow","questionId":58565115,"title":"Nuxt - dynamic params after building does not work","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Nuxt - dynamic params after building does not work\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn a Nuxt (\"spa\" mode) project I have a url with a dynamic param `/shop/:product`, which can be as such:\n\n```\n/shop/ipad-128gb-rose-gold\n /shop/subway-gift-card\n /shop/any-string\n```\n\netc.\n\nUsing this directory structure works fine in development environment:\n\n```\npages/\n shop/\n _product.vue\n```\n\nHowever it does not work in production. Looking to the generated `bin/` folder I see that there is nothing inside `shop/` directory. And I see that Nuxt mentions a solution here: https://nuxtjs.org/api/configuration-generate/#routes\n\nBut in my situation, I don't know what the `:product` param will be (could be any string).\n\nI am fetching the `product` details in `pages/shop/_product.vue` from the server (if it exists), otherwise handling the error. So now how do I do that in a production build?\n\nI think I am misunderstanding the Nuxt solution -- am I really supposed to generate *all* possible routes for every existing product slug??\n\n========================================\n\nTop Answer:\nWhen you generate static pages, it produces directories and index.html in each one. How did you expect to have it dynamic if you serve static HTML?\n\nYou have 2 solutions:\n\ndon't use `npm run generate`. Run nuxt on the server. Using this solution, you avoid ajax in browser. Instead, nuxt performs it and sends the HTML to the browser. Good for SEO.\n\nhave your web server (nginx) point all requests to `/index.html` - at that point, javascript takes over and it can correctly find the slug and query the products via ajax. Bad for SEO because you need to use ajax to get the content after page finishes loading.\n\nDocumentation and configuration about this can be found at nuxt's web.\n\n========================================\n\nCode:\n```html\n/shop/ipad-128gb-rose-gold\n /shop/subway-gift-card\n /shop/any-string\n```\n\n```text\npages/\n shop/\n _product.vue\n```\n\n```text\n/shop/:product\n```\n\n```text\nbin/\n```\n\n```text\nshop/\n```\n\n```text\n:product\n```\n\n```text\nproduct\n```\n\n```text\npages/shop/_product.vue\n```\n\n```js\n// nuxt.config.js\n\nexport default {\n ...\n generate: {\n fallback: true\n }\n}\n```\n\n```text\ndist/\n```\n\n```text\nnpm run generate\n```\n\n```text\n/index.html\n```\n\n========================================\n\nComments:\n- RE: When you generate static pages, it produces directories and index.html in each one. How did you expect to have it dynamic if you serve static HTML? During development it works just as expected, this is why -- I didn't realize what the built/generated product would look like in the end, until now. RE: don't use npm run generate. Run nuxt on the server. Using this solution, you avoid ajax in browser. Instead, nuxt performs it and sends the HTML to the browser. Good for SEO. Does this mean I should write a server.js, and within that have Nuxt handle requests?\n- Sorry for late reply, StackOverflow moderation team prevented me to reply. What you should do is run Nuxt in SSR mode. You write code as usual, when you deploy you run `npm run production` on the server. You use nginx to route requests to nuxt and to terminate SSL.\n- Does nothing for me. Still get 404 refreshing any slug page.","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":112,"estimatedTokens":812}}730{"id":"stack-52193097","source":"stackoverflow","questionId":52193097,"title":"Populate router with external json","tags":["vue.js","nuxt.js"],"text":"Title: Populate router with external json\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI would like to add routes from an external json file, which can change at runtime, to my Nuxt application. A similar topic can be found here.\n\nI've overridden the default Nuxt router with my own implementation. If I import the routes async using axios + `router.addRoutes()`, I seem to loose the server side rendering. It seems like `createRouter` will have async support, but it's not in an official release of Nuxt yet.\n\nHow do I import a js/json file *synchronously* to my `router.js` below, so that I can populate the routes? I want to be able to configure the routes at runtime, so I don't want it to be a part of the bundle.\n\n**modules/router.js:**\n\n```\nconst path = require('path')\n\nmodule.exports = function () {\n this.nuxt.options.build.createRoutes = () => {}\n this.addTemplate({\n fileName: 'router.js',\n src: path.resolve(`${this.options.srcDir}`, 'router.js')\n })\n}\n```\n\n**nuxt.config.js:**\n\n```\nmodules: ['~/modules/router']\n```\n\n**router.js:**\n\n```\nimport Vue from 'vue'\nimport Router from 'vue-router'\n\nVue.use(Router)\n\nexport function createRouter () {\n const router = new Router({\n mode: 'history',\n routes: [/* ... */]\n })\n\n return router\n}\n```\n\n========================================\n\nTop Answer:\nSo `await` would be an answer but I guess you already tried that? So, something like this.\n\n```\nconst routeFile = await fetch('pathToTheJsonFile');\nconst routes = await routeFile.json();\n```\n\nIn case you can't make the method async, as a workaround maybe use jQuery. I don't like this but if there's no other option, for now, use `async: false` in jQuery get.\n\n```\njQuery.ajax({\n url: 'pathToYourJsonRoutes',\n success: function (result) {\n\n },\n async: false\n});\n```\n\n========================================\n\nCode:\n```text\nconst path = require('path')\n\nmodule.exports = function () {\n this.nuxt.options.build.createRoutes = () => {}\n this.addTemplate({\n fileName: 'router.js',\n src: path.resolve(`${this.options.srcDir}`, 'router.js')\n })\n}\n```\n\n```text\nmodules: ['~/modules/router']\n```\n\n```text\nimport Vue from 'vue'\nimport Router from 'vue-router'\n\nVue.use(Router)\n\nexport function createRouter () {\n const router = new Router({\n mode: 'history',\n routes: [/* ... */]\n })\n\n return router\n}\n```\n\n```text\nrouter.addRoutes()\n```\n\n```text\ncreateRouter\n```\n\n```text\nrouter.js\n```\n\n```text\nsync-request\n```\n\n```text\nconst routeFile = await fetch('pathToTheJsonFile');\nconst routes = await routeFile.json();\n```\n\n```text\njQuery.ajax({\n url: 'pathToYourJsonRoutes',\n success: function (result) {\n\n },\n async: false\n});\n```\n\n```text\nawait\n```\n\n```text\nasync: false\n```\n\n========================================\n\nComments:\n- i think you could import your json file like `import myroutes from 'thepath/routes.json'` and `... mode:'hidtory',routes:myroutes...`\n- @boussadjrabrahim If I do that, it will be part of the bundle when I build.\n- yes i understood, did you try use axios to accomplish that?\n- @boussadjrabrahim Yeah I've tried the async method as I mentioned but the load needs to execute synchronously at the moment\n- Did you consider to use a NPM package like this?\n- @P3trur0 Not sure how I missed that, feel free to post it as an answer :)\n- \"So await would be an answer\" - no, I want to load data synchronously, as mentioned.\n- Correct me if I'm wrong but if you don't want the code execution to continue until the promise is resolved, this will solve that issue. Routes should be loaded. If you want it sync, then unfortunately at least for the moment you'll need jquery. With axios I think it is not possible currently.","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":156,"estimatedTokens":920}}731{"id":"stack-68917041","source":"stackoverflow","questionId":68917041,"title":"Nuxt router leads to wrong link after page reload","tags":["javascript","vue.js","nuxt.js","server-side-rendering"],"text":"Title: Nuxt router leads to wrong link after page reload\nTags: javascript, vue.js, nuxt.js, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nFirst, to demonstrate what I mean, I've set up a demo Nuxt blog at https://debadeepsen.com/nuxtblog/. It has the articles populated by the `@nuxt/content` package. The deployed website has been generated via the `nuxt generate` command and as such, is fully static. Now perform the following actions -\n\n- Go to the homepage and click on any of the links.\n\n- It takes you to the article you requested.\n\n- From the article page, you can click on any other link, which'll take you to a different article.\n\nThe steps taken above lead to results that are expected. But now, reload any of the article pages. You will notice the following -\n\n- A trailing slash (/) has been added to the URL in the address bar (I haven't tested on all browsers, but this appears to happen on at least Chromium-based ones).\n\n- The URLs for the links now have the current slug segment as part of the base URL, presumably due to the above occurrence. So for example, the second link now points to either https://debadeepsen.com/nuxtblog/what-is-settimeout/what-is-settimeout or https://debadeepsen.com/nuxtblog/vintage-photo-effect-with-css/what-is-settimeout (depending on which page you reloaded).\n\nObviously, these pages don't exist, and therefore the links are now broken.\n\nMy code is pretty straightforward. Here's the navigation menu -\n\n```\n\n \n \n {{ article.title }}\n \n \n\n```\n\nThe state variable `list` has correct data in it, no problem there.\n\nIn my `nuxt.config.js`, I have -\n\n```\nexport default {\n // ...\n \n router: {\n base: '/nuxtblog/'\n },\n\n // ...\n}\n```\n\nSo, what am I doing wrong here and how can I fix this problem?\n\n========================================\n\nCode:\n```html\n<ul>\n <li v-for=\"article in list\" :key=\"article.slug\">\n <nuxt-link :to=\"article.slug\">\n {{ article.title }}\n </nuxt-link>\n </li>\n</ul>\n```\n\n```js\nexport default {\n // ...\n \n router: {\n base: '/nuxtblog/'\n },\n\n // ...\n}\n```\n\n```text\n@nuxt/content\n```\n\n```text\nnuxt generate\n```\n\n```text\nlist\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nto\n```\n\n```text\n/\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":99,"estimatedTokens":546}}732{"id":"stack-57986183","source":"stackoverflow","questionId":57986183,"title":"WorkBox is fetching wrong urlPattern","tags":["vuejs2","nuxt.js","workbox"],"text":"Title: WorkBox is fetching wrong urlPattern\nTags: vuejs2, nuxt.js, workbox\nSource: Stack Overflow\n\nQuestion:\nI'm using **Nuxt.js** framework and my WorkBox config looks like below\n\n```\nworkbox: {\n workboxURL: 'https://cdn.jsdelivr.net/npm/workbox-sw@4.3.1/build/workbox-sw.min.js',\n cacheAssets: false,\n offline: false,\n runtimeCaching: [\n {\n urlPattern: '^/$|/(?:about|contact)$',\n handler: 'cacheFirst',\n strategyOptions: {\n cacheName: 'test-cache-v1',\n cacheExpiration: {\n maxEntries: 5,\n maxAgeSeconds: 10\n }\n }\n },\n {\n urlPattern: '/.*',\n handler: 'networkOnly',\n },\n ]\n}\n```\n\nHere `urlPattern: '^/$|/(?:about|contact)$'` suppose to match all 3 requests:\n\n```\n/\n/about\n/contact\n```\n\nBut only `/about` and `/contact` is matched and `/` is being handled by next cache strategy `urlPattern: '/.*'` which is networkOnly.\n\nNot sure why WorkBox is not able to handle `/` request in `cacheFirst` strategy\n\nThis what **ServiceWork.js** file content looks like\n\n```\nworkbox.routing.registerRoute(new RegExp('^/$|/(?:about|contact)$'), workbox.strategies.cacheFirst({\"cacheName\":\"test-cache-v1\",\"cacheExpiration\":{\"maxEntries\":5,\"maxAgeSeconds\":10}}), 'GET')\n\nworkbox.routing.registerRoute(new RegExp('/.*'), workbox.strategies.networkOnly({}), 'GET')\n```\n\n========================================\n\nCode:\n```text\nworkbox: {\n workboxURL: 'https://cdn.jsdelivr.net/npm/workbox-sw@4.3.1/build/workbox-sw.min.js',\n cacheAssets: false,\n offline: false,\n runtimeCaching: [\n {\n urlPattern: '^/$|/(?:about|contact)$',\n handler: 'cacheFirst',\n strategyOptions: {\n cacheName: 'test-cache-v1',\n cacheExpiration: {\n maxEntries: 5,\n maxAgeSeconds: 10\n }\n }\n },\n {\n urlPattern: '/.*',\n handler: 'networkOnly',\n },\n ]\n}\n```\n\n```text\n/\n/about\n/contact\n```\n\n```text\nworkbox.routing.registerRoute(new RegExp('^/$|/(?:about|contact)$'), workbox.strategies.cacheFirst({\"cacheName\":\"test-cache-v1\",\"cacheExpiration\":{\"maxEntries\":5,\"maxAgeSeconds\":10}}), 'GET')\n\nworkbox.routing.registerRoute(new RegExp('/.*'), workbox.strategies.networkOnly({}), 'GET')\n```\n\n```text\nurlPattern: '^/$|/(?:about|contact)$'\n```\n\n```text\n/about\n```\n\n```text\n/contact\n```\n\n```text\n/\n```\n\n```text\nurlPattern: '/.*'\n```\n\n```text\n/\n```\n\n```text\ncacheFirst\n```\n\n```text\nhttp://localhost:3000\n```\n\n```text\n^/$\n```\n\n```text\n^/$\n```\n\n```text\n^http://localhost:3000[/]?$\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":135,"estimatedTokens":612}}733{"id":"stack-77506933","source":"stackoverflow","questionId":77506933,"title":"What is the differences between Modules & Layers in Nuxt 3?","tags":["vue.js","nuxt.js"],"text":"Title: What is the differences between Modules & Layers in Nuxt 3?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have spent several hours learning about modules and layers in Nuxt 3, but I'm unsure about the exact differences between them. With layers, we have the ability to components, pages, composables, and configurations between multiple projects in a monorepo. On the other hand, modules also allow us to achieve this, but with an additional step of configuration. I would like to understand if there are any distinctions between them in terms of their use cases.\n\n========================================\n\nTop Answer:\n### Layers\n\nBest when used internally. I believe they use modules under the hood.\n\n### Modules\n\nBetter for sharing publicly with others (e.g. via npm package). There is a much better sharing ecosystem around modules.\n\n========================================\n\nCode:\n```text\nextends\n```\n\n========================================\n\nComments:\n- This recent video from the latest nuxt nation conference can give a clear vision about the difference youtu.be/dWXRiBQw_lE?t=97","metadata":{"transformedAt":"2026-08-18T18:33:07.889Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":29,"estimatedTokens":277}}734{"id":"stack-54280875","source":"stackoverflow","questionId":54280875,"title":"Nuxt.js Store, dispatch action to other store","tags":["vue.js","vuex","nuxt.js"],"text":"Title: Nuxt.js Store, dispatch action to other store\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have two stores on my Nuxt.js app and I need to dispatch an action to another store.\n\n```\nexport const actions = {\n addToCart({ state, commit, dispatch }) {\n dispatch('CartLoadingStore/enableLoadingBar')\n\n this.$axios\n .post('something')\n .then(response => {\n (...)\n dispatch('CartLoadingStore/disableLoadingBar')\n })\n },\n}\n```\n\nIt seems to me like I cannot dispatch an action to a different store. Is that right? Or is there a way to do so?\n\nThe above will result in the error:\n\n```\n[vuex] unknown local action type: CartLoadingStore/enableLoadingBar, global type: StoreTheActionDispatchedFrom/CartLoadingStore/enableLoadingBar\n```\n\n========================================\n\nCode:\n```text\nexport const actions = {\n addToCart({ state, commit, dispatch }) {\n dispatch('CartLoadingStore/enableLoadingBar')\n\n this.$axios\n .post('something')\n .then(response => {\n (...)\n dispatch('CartLoadingStore/disableLoadingBar')\n })\n },\n}\n```\n\n```text\n[vuex] unknown local action type: CartLoadingStore/enableLoadingBar, global type: StoreTheActionDispatchedFrom/CartLoadingStore/enableLoadingBar\n```\n\n```text\ndispatch('CartLoadingStore/disableLoadingBar', null, { root: true })\n```\n\n========================================\n\nComments:\n- Thanks Aldarund. Is there a documentation for this? Couldn't find anything in the nuxt docs..\n- @mauxtin i updated answer with link to docs. Since its vuex its stated in docs for vuex","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":61,"estimatedTokens":391}}735{"id":"stack-61653257","source":"stackoverflow","questionId":61653257,"title":"Unable to use $fetchState in Nuxt 2.12","tags":["javascript","vue.js","fetch","nuxt.js"],"text":"Title: Unable to use $fetchState in Nuxt 2.12\nTags: javascript, vue.js, fetch, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSo I'm trying to use the new functionality describe in the documentation.\n\nHowever I'm ending up getting this error :\n\n Property or method \"$fetchState\" is not defined on the instance but referenced during render.\n\nEven though my component define clearly the fetch() method and I manage to get something out of it.\n\n```\n\n \n Fetching posts...\n\n Error while fetching posts\n\n \n \n \n \n \n\nimport { mapState } from 'vuex'\n\nexport default {\n async fetch({ store, error }) {\n try {\n await store.dispatch('home/fetchContent')\n } catch (e) {\n error({\n statusCode: 503,\n message: 'Unable to fetch'\n })\n }\n },\n computed: mapState({\n content: (state) => state.home.content\n })\n}\n\n```\n\nHas anybody ever encountered that before ?\n\n========================================\n\nCode:\n```text\n<template>\n <div v-if=\"$fetchState\">\n <p v-if=\"$fetchState.pending\">Fetching posts...</p>\n <p v-else-if=\"$fetchState.error\">Error while fetching posts</p>\n <div v-else>\n <div v-if=\"content.content1\" v-html=\"content.content1\" />\n <div v-if=\"content.content2\" v-html=\"content.content2\" />\n </div>\n </div>\n</template>\n<script>\nimport { mapState } from 'vuex'\n\nexport default {\n async fetch({ store, error }) {\n try {\n await store.dispatch('home/fetchContent')\n } catch (e) {\n error({\n statusCode: 503,\n message: 'Unable to fetch'\n })\n }\n },\n computed: mapState({\n content: (state) => state.home.content\n })\n}\n</script>\n```\n\n```text\nasync fetch() {\n const { store, error } = this.$nuxt.context\n\n try {\n await store.dispatch('home/fetchContent')\n } catch (e) {\n error({\n statusCode: 503,\n message: 'Unable to fetch'\n })\n }\n },\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":97,"estimatedTokens":480}}736{"id":"stack-73790121","source":"stackoverflow","questionId":73790121,"title":"Nuxt 3 useFetch sometimes returns null","tags":["nuxt.js","server-side-rendering","nuxt3.js"],"text":"Title: Nuxt 3 useFetch sometimes returns null\nTags: nuxt.js, server-side-rendering, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI want to get some data from HTTP API and display it on the page:\n\n```\n\n \n Kyiv Time: {{ timeData.utc_datetime }}\n \n\nconst { data: timeData } = await useFetch('https://worldtimeapi.org/api/timezone/Europe/Kiev')\n\n```\n\nSometimes page loads correctly, and sometimes I got an error `Cannot read properties of null (reading 'utc_datetime')` in the template. So await doesn't really wait for the HTTP request.\n\nHow can I wait for HTTP request during SSR (and client-side as well)?\n\nMy nuxt config is empty, here the project sources\n\n========================================\n\nCode:\n```html\n<template>\n <div>\n Kyiv Time: {{ timeData.utc_datetime }}\n </div>\n</template>\n\n<script setup>\nconst { data: timeData } = await useFetch('https://worldtimeapi.org/api/timezone/Europe/Kiev')\n</script>\n```\n\n```text\nCannot read properties of null (reading 'utc_datetime')\n```\n\n```html\n<div v-if=\"data\">\n...\n</div>\n<div v-else>\n...\n</div>\n```\n\n```js\nif (error.value) {\n throw createError(...)\n}\n```\n\n```text\ndata\n```\n\n```text\nerror\n```\n\n```text\ndata\n```\n\n```text\nnull\n```\n\n========================================\n\nComments:\n- The fetch hook is not blocking. Give a search to `fetch vs asyncData`. You can either put conditionals + non blocking or use a blocking approach.\n- `await useFetch` should be blocking. `fetch` and `useLazyFetch` are not.\n- @some-user oh yeah? I need to update my knowledge there apparently!","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":79,"estimatedTokens":382}}737{"id":"stack-58810897","source":"stackoverflow","questionId":58810897,"title":"Nuxt/Vue.js - Dynamically loading in a child component based on a prop","tags":["javascript","vue.js","vuejs2","nuxt.js"],"text":"Title: Nuxt/Vue.js - Dynamically loading in a child component based on a prop\nTags: javascript, vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a `sectionHeader.vue` component that I want to use on lots of different pages. Inside that `sectionHeader.vue` is a `` element (that I am using for some robust three.js animations) that I dynamically want to change inside of each header through props. I'd like to get this working to take advantange of Vue's inherent code-splitting so that each page doesn't load every single other pages animation js code, only the code that is relevant to it.\n\nI'm attempting to dynamically load this in using dynamic components but I don't think this is what I'm looking for...\n\nMy folder structure:\n\n```\ncomponents\n animations\n robust-animation-1.vue\n robust-animation-2.vue\n maybe-like-15-more-of-these.vue\n headings\n heading2.vue\n SectionHeader.vue\npages\n index.vue\n```\n\npages/index.vue:\n\n```\n\n```\n\ncomponents/SectionHeader.vue:\n\n```\n\n \n \n \n {{canvas}} \n \n\nimport heading2 from './headings/heading2';\n\nexport default {\n components: {\n heading2\n },\n props: [\n 'postTitle', 'className', 'canvas'\n ]\n}\n\n```\n\ncomponents/animations/robust-animation-1.vue:\n\n```\n\n \n \n \n\n// 200 lines of js here that manipulates the above canvas\n\n```\n\nMy `heading2` component works great, but no matter what I try I can't figure out how to dynamically pull in my animation component. I get varying degrees of the below error:\n\n```\nclient.js 76 DOMException: Failed to execute 'createElement' on 'Document': The tag name provided ('./animations/robust-animation-1') is not a valid name.\n```\n\nI looked into scoped slots, and that looks close to what I need, but not exactly. Is there a better way to do what I'm attempting?\n\n========================================\n\nCode:\n```text\ncomponents\n animations\n robust-animation-1.vue\n robust-animation-2.vue\n maybe-like-15-more-of-these.vue\n headings\n heading2.vue\n SectionHeader.vue\npages\n index.vue\n```\n\n```js\n<sectionHeader post-title=\"Menu\" class-name=\"menu\" canvas=\"./animations/robust-animation-1\"></sectionHeader>\n```\n\n```js\n<template>\n <section class=\"intro section-intro\" :class=\"className\">\n <heading2 :post-title=\"postTitle\"></heading2>\n <component v-bind:is=\"canvas\"></component> <!-- this is what i am dynamically trying to load --> \n {{canvas}} <!-- this echos out ./animations/robust-animation-1 -->\n </section>\n</template>\n\n<script>\nimport heading2 from './headings/heading2';\n\nexport default {\n components: {\n heading2\n },\n props: [\n 'postTitle', 'className', 'canvas'\n ]\n}\n</script>\n```\n\n```js\n<template>\n <div>\n <canvas class=\"prowork-canvas\" width=\"960\" height=\"960\"></canvas>\n </div>\n</template>\n\n<script>\n// 200 lines of js here that manipulates the above canvas\n</script>\n```\n\n```text\nclient.js 76 DOMException: Failed to execute 'createElement' on 'Document': The tag name provided ('./animations/robust-animation-1') is not a valid name.\n```\n\n```text\nsectionHeader.vue\n```\n\n```text\nsectionHeader.vue\n```\n\n```text\n<canvas>\n```\n\n```text\nheading2\n```\n\n```text\ncomponents\n animations\n robust-animation-1.vue\n robust-animation-2.vue\n maybe-like-15-more-of-these.vue\n headings\n heading2.vue\n SectionHeader.vue\npages\n index.vue\n```\n\n```text\n<section-header post-title=\"Menu\" class-name=\"menu\" canvas=\"./animations/robust-animation-1\">\n </section-header>\n <script>\n import SectionHeader from \"../components/SectionHeader\";\n\n export default {\n name: 'PageIndex',\n components: {SectionHeader}\n }\n </script>\n```\n\n```text\n<template>\n <div>\n post_title {{postTitle}}\n <br/>\n class-name {{className}}\n <br/>\n canvas {{canvas}}\n <br/>\n <heading2 post-title=\"postTitle\"></heading2>\n <br/>\n <component v-bind:is=\"stepComponent\"></component>\n </div>\n</template>\n\n<script>\n import Heading2 from \"./headings/heading2\";\n\n export default {\n name: \"SectionHeader\",\n components: {\n Heading2,\n },\n props: ['postTitle', 'className', 'canvas'],\n computed: {\n stepComponent() {\n let data = this.canvas.split('/')[2];\n return () => import(`./animations/${data}`);\n }\n },\n }\n</script>\n```\n\n```text\n<template>\n <div>\n From - robust-animation-1\n </div>\n</template>\n\n<script>\n export default {\n name: \"robust-animation-1\"\n }\n</script>\n```\n\n```text\npost_title Menu \nclass-name menu \ncanvas ./animations/robust-animation-1 \npostTitle \nFrom - robust-animation-1\n```\n\n```text\nprop\n```\n\n```text\ncomputed\n```\n\n========================================\n\nComments:\n- Can you provide a codesandbox with minimal code?","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":242,"estimatedTokens":1188}}738{"id":"stack-59994004","source":"stackoverflow","questionId":59994004,"title":"[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content ( Nuxt / Vue / lerna monorepo )","tags":["vue.js","webpack","nuxt.js","vue-cli","lerna"],"text":"Title: [Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content ( Nuxt / Vue / lerna monorepo )\nTags: vue.js, webpack, nuxt.js, vue-cli, lerna\nSource: Stack Overflow\n\nQuestion:\nI am trying to run a basic Nuxt app with an external Vue component built using vue-cli inside a lerna monorepo.\n\nThe page briefly shows component content (server rendered) and then it disappears throwing the following errors.\n\n`\"export 'default' (imported as 'Header') was not found in 'a2b-header'`\n\nfollowed by\n\n`Mismatching childNodes vs. VNodes: NodeList(7) [svg, text, div#app, text, h2.subtitle, text, div.links] (7) [VNode, VNode, VNode, VNode, VNode, VNode, VNode]`\n\nand finally a red Vue warning\n\n`[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside , or missing . Bailing hydration and performing full client-side render.`\n\nThe setup I am using for the external component is **package.json**:\n\n```\n{\n \"name\": \"a2b-header\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"main\": \"./dist/a2b-header.umd.js\",\n \"scripts\": {\n \"serve\": \"vue-cli-service serve\",\n \"build\": \"vue-cli-service build --target lib --name a2b-header src/main.js\",\n \"lint\": \"vue-cli-service lint\"\n },\n \"dependencies\": {\n \"core-js\": \"^3.4.3\",\n \"vue\": \"^2.6.10\"\n },\n ...\n}\n```\n\nmy **main.js** looks like below:\n\n```\nimport Header from './Header.vue'\n\nexport default Header\n```\n\nand component file itself **Header.vue** is:\n\n```\n\n \n \n\n### Welcome to Your Vue.js App\n\n \n\nexport default {\n name: 'Header'\n}\n\n#app {\n font-family: 'Avenir', Helvetica, Arial, sans-serif;\n text-align: center;\n color: #2c3e50;\n margin-top: 60px;\n}\n\n```\n\nthat all is being imported in the Nuxt project **index.vue** using simple:\n\n```\nimport Header from 'a2b-header'\n```\n\nand.... it does not work. I am thinking the mismatch of SSR vs clients is connected to the incorrect export, probably solvable by some webpack config but after trying many different things I am rly struggling here.\n\nThe reason I want this to get it to work is that in the monorepo we plan to have various Vue applications (both SPA and and Nuxt )and the ability to encapsulate common code in components reusable across different projects is crucial.\n\n========================================\n\nTop Answer:\nWrap your component with ` `\n\nGo to the official nuxt docs for more info:\n\nhttps://nuxtjs.org/docs/2.x/features/nuxt-components#the-client-only-component\n\n========================================\n\nCode:\n```text\n{\n \"name\": \"a2b-header\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"main\": \"./dist/a2b-header.umd.js\",\n \"scripts\": {\n \"serve\": \"vue-cli-service serve\",\n \"build\": \"vue-cli-service build --target lib --name a2b-header src/main.js\",\n \"lint\": \"vue-cli-service lint\"\n },\n \"dependencies\": {\n \"core-js\": \"^3.4.3\",\n \"vue\": \"^2.6.10\"\n },\n ...\n}\n```\n\n```text\nimport Header from './Header.vue'\n\nexport default Header\n```\n\n```text\n<template>\n <div id=\"app\">\n <h1>Welcome to Your Vue.js App</h1>\n </div>\n</template>\n\n<script>\nexport default {\n name: 'Header'\n}\n</script>\n\n<style>\n#app {\n font-family: 'Avenir', Helvetica, Arial, sans-serif;\n text-align: center;\n color: #2c3e50;\n margin-top: 60px;\n}\n</style>\n```\n\n```text\nimport Header from 'a2b-header'\n```\n\n```text\n\"export 'default' (imported as 'Header') was not found in 'a2b-header'\n```\n\n```text\nMismatching childNodes vs. VNodes: NodeList(7) [svg, text, div#app, text, h2.subtitle, text, div.links] (7) [VNode, VNode, VNode, VNode, VNode, VNode, VNode]\n```\n\n```text\n[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.\n```\n\n```text\nextend (config, ctx) {\n config.resolve.symlinks = false\n }\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n<ClientOnly> <YourComponent> </ClientOnly>\n```\n\n========================================\n\nComments:\n- Thanks for reply! I do not want to use no-ssr as that component should be rendered correctly on the server, it will have no references to DOM and zero manipulations.\n- I have also tried the stack trace inspection, it is weird... but the elm and vnode.elm are identical.\n- Hooray! Thanks a lot! This solved the issue for me. I had a component that generated a list with v-for from a dynamically changing array. Wrapping the whole component in ` fixed the issue!","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":178,"estimatedTokens":1147}}739{"id":"stack-59292838","source":"stackoverflow","questionId":59292838,"title":"Nuxt: Difference nuxtServerInit vs Mddleware vs Plugin","tags":["nuxt.js"],"text":"Title: Nuxt: Difference nuxtServerInit vs Mddleware vs Plugin\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhat is the difference between\n1) nuxtServerInit\n2) Middleware\n3) Plugin\n\nAnd when is it processed on server side and when is it process on client side.\n\n========================================\n\nCode:\n```text\nthis\n```\n\n========================================\n\nComments:\n- Thank you for the great answer: I thought that on every nuxt request the state will be reseted. But information which I add to the head persist in my case: stackoverflow.com/questions/59300315/… Is this a Nuxt bug?\n- I left an answer on that post, but long story short: I'm not sure. I do have a possible solution to your problem though","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":24,"estimatedTokens":182}}740{"id":"stack-66496792","source":"stackoverflow","questionId":66496792,"title":"Nuxt + SurveyJS : When using nuxt generate or nuxt build - get a maximum call stack size exceeded","tags":["vue.js","nuxt.js","surveyjs"],"text":"Title: Nuxt + SurveyJS : When using nuxt generate or nuxt build - get a maximum call stack size exceeded\nTags: vue.js, nuxt.js, surveyjs\nSource: Stack Overflow\n\nQuestion:\nI have survey-vue (surveyJS) working well on dev, but when I attempt to deploy I get a maximum call stack size exceeded error when landing on a page with the survey component.\nI was thinking it's how I'm importing the plugin but I'm not sure.\n\nplugins/survey-vue.js\n\n```\nimport Vue from \"vue\";\nimport * as surveyVue from \"survey-vue\";\n\nVue.use(surveyVue);\n```\n\nnuxt.config.js\n\n```\nplugins: [\n ...\n {\n src: '~/plugins/survey-vue',\n mode: 'client'\n },\n]\n```\n\ncomponents/Survey.vue\n\n```\n\n \n \n \n\nimport * as surveyVue from \"survey-vue\";\nexport default {\n props: {\n json: {\n type: Object\n },\n results: {\n type: Object\n }\n },\n data() {\n const jsonSurvey = this.json;\n const survey = new surveyVue.Model(jsonSurvey);\n\n // style the survey \n var myCss = {...};\n \n survey.onComplete.add(survey => {\n this.result = survey.data;\n this.sendResults()\n })\n\n survey.css = myCss\n return {\n surveyRender: survey,\n result: []\n }\n },\n methods: {\n sendResults () {\n this.$emit('resultCaptured', this.result)\n }\n },\n created () {\n\n }\n}\n\n```\n\npages/.vue\n\n```\n\n \n \n \n \n \n \n \n\n....\n```\n\nAny insight here is appreciated. Have been trying to debug this for several days to no avail.\n\n========================================\n\nCode:\n```js\nimport Vue from \"vue\";\nimport * as surveyVue from \"survey-vue\";\n\nVue.use(surveyVue);\n```\n\n```js\nplugins: [\n ...\n {\n src: '~/plugins/survey-vue',\n mode: 'client'\n },\n]\n```\n\n```html\n<template>\n <div id=\"surveyElement\" class=\"w-full inline-block\">\n <survey :survey=\"surveyRender\" />\n </div>\n</template>\n\n<script>\nimport * as surveyVue from \"survey-vue\";\nexport default {\n props: {\n json: {\n type: Object\n },\n results: {\n type: Object\n }\n },\n data() {\n const jsonSurvey = this.json;\n const survey = new surveyVue.Model(jsonSurvey);\n\n // style the survey \n var myCss = {...};\n \n survey.onComplete.add(survey => {\n this.result = survey.data;\n this.sendResults()\n })\n\n survey.css = myCss\n return {\n surveyRender: survey,\n result: []\n }\n },\n methods: {\n sendResults () {\n this.$emit('resultCaptured', this.result)\n }\n },\n created () {\n\n }\n}\n</script>\n```\n\n```html\n<template>\n <div class=\"flex flex-col justify-center mx-auto w-full md:w-1/2 px-4\">\n <div class=\"w-auto mx-auto p-4 mt-12\" v-if=\"surveyCreated\">\n <client-only>\n <survey :json=\"json\" :results=\"reportedSymptoms\"></survey>\n </client-only>\n </div>\n </div>\n</template>\n....\n```\n\n========================================\n\nComments:\n- This error usually comes from an infinite loop.\n- Fixed: I had called my component Survey.vue which is the same name reserved for the plugin's survey. Changed my component file to SurveyComponent.vue and it resolved. Thanks @kissu for getting the wheels turning\n- Indeed, the Vue styleguide recommend to prefix all your components to avoid such collisions: vuejs.org/v2/style-guide/…\n- Makes a lot of sense!","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":182,"estimatedTokens":781}}741{"id":"stack-47844836","source":"stackoverflow","questionId":47844836,"title":"Nuxtjs with scrollmagic gives me \"window is not defined\"","tags":["window","undefined","scrollmagic","nuxt.js"],"text":"Title: Nuxtjs with scrollmagic gives me \"window is not defined\"\nTags: window, undefined, scrollmagic, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to use scrollmagic with nuxtjs.\n\nI installed scrollmagic via npm. \n\n```\nnpm install scrollmagic\n```\n\nIn my nuxt.config.js file i added \n\n```\nbuild: {\n vendor: ['scrollmagic']\n},\n```\n\nAnd in my pages/index.vue file i simply imported it.\n\n```\nimport ScrollMagic from 'scrollmagic'\n```\n\nBut this results only in this error \n\n [vue-router] Failed to resolve async component default:\n ReferenceError: window is not defined [vue-router] uncaught error\n during route navigation: ReferenceError: window is not defined\n at C:\\pathto\\node_modules\\scrollmagic\\scrollmagic\\uncompressed\\ScrollMagic.js:37:2\n at C:\\pathto\\node_modules\\scrollmagic\\scrollmagic\\uncompressed\\ScrollMagic.js:22:20\n at Object. (C:\\pathto\\node_modules\\scrollmagic\\scrollmagic\\uncompressed\\ScrollMagic.js:27:2)\n\nHow can i fix this?\n\n========================================\n\nCode:\n```text\nnpm install scrollmagic\n```\n\n```text\nbuild: {\n vendor: ['scrollmagic']\n},\n```\n\n```text\nimport ScrollMagic from 'scrollmagic'\n```\n\n```text\nimport ScrollMagic from 'scrollmagic'\n```\n\n```text\nmodule.exports = {\n build: {\n vendor: ['scrollmagic']\n },\n plugins: [\n // ssr: false to only include it on client-side\n { src: '~/plugins/scrollmagic.js', ssr: false }\n ]\n}\n```\n\n```text\n<script>\nlet scrollmagic\nif (process.client) {\n scrollmagic = require('scrollmagic')\n// use scrollmagic\n}\n</script>\n```\n\n```text\nif (process.client) {}\n```\n\n========================================\n\nComments:\n- This solved the issue about \"window is not defined\" but now I'm getting this `ERROR calling setTween() due to missing Plugin 'animation.gsap'. Please make sure to include plugins/animation.gsap.js`. Have yet to find a solution for NuxtJS... Any idea on this?\n- Did you add a file to your plugins folder called \"animation.gsap.js\"? If so, are you sure that there are no typos?","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":90,"estimatedTokens":496}}742{"id":"stack-74791302","source":"stackoverflow","questionId":74791302,"title":"Issues with setting up HTTPS on localhost with Nuxt 3","tags":["ssl","https","nuxt.js","nuxt3.js"],"text":"Title: Issues with setting up HTTPS on localhost with Nuxt 3\nTags: ssl, https, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to set up to run Nuxt 3 with HTTPS for localhost. I've looked at other guides and questions that were already asked online, but they all seem to be using older versions of Nuxt and for some reason, that way does not work anymore. For example, I've tried using this link as a reference on how to set up my *nuxt.config.ts* file, however, it's not working out for me.\n\nWhen using the server property, I'm getting the error \"server does not exist in type NuxtConfig\", however, devServer seems to not give me any errors at least (still not working). Here's my\n`nuxt.config.file`\n\n```\nimport { fileURLToPath } from \"node:url\"\n\nexport default defineNuxtConfig({\n css: [\"~/assets/global.scss\"],\n experimental: {\n reactivityTransform: true,\n },\n app: {\n head: {\n htmlAttrs: {\n lang: \"en\",\n },\n },\n },\n devServer: {\n https: {\n key: fileURLToPath(new URL(\"~/certs/localhost-key.pem\", import.meta.url)),\n cert: fileURLToPath(new URL(\"~/certs/localhost.pem\", import.meta.url)),\n },\n },\n})\n```\n\nSSL certificate is created and self-signed using `mkcert`.\n\nAfter I generate the SSL certificate and install everything and try to access https://localhost:3000, I get the error \"SSL_ERROR_RX_RECORD_TOO_LONG\".\n\nI'd really appreciate if someone could help me out with this. I've never done this before so not really sure what I am doing and it's taking a while already to solve.\n\n========================================\n\nTop Answer:\nIt seems I managed to find a way to set up HTTPS on localhost in the end.\n\nHere's how I did it:\n\nFirst I followed this short guide to set up & self-sign the SSL certificate. I also changed `nuxt dev` from the `package.json` file to the following `nuxt dev --https --ssl-cert localhost.pem --ssl-key localhost-key.pem`.\n\nHowever, this gave me a `500 fetch failed` error. This was solved by following this thread, which basically stated that you need to add the `NODE_TLS_REJECT_UNAUTHORIZED=0` environment variable.\n\nNow everything seems to be working perfectly!\n\n========================================\n\nCode:\n```js\nimport { fileURLToPath } from \"node:url\"\n\nexport default defineNuxtConfig({\n css: [\"~/assets/global.scss\"],\n experimental: {\n reactivityTransform: true,\n },\n app: {\n head: {\n htmlAttrs: {\n lang: \"en\",\n },\n },\n },\n devServer: {\n https: {\n key: fileURLToPath(new URL(\"~/certs/localhost-key.pem\", import.meta.url)),\n cert: fileURLToPath(new URL(\"~/certs/localhost.pem\", import.meta.url)),\n },\n },\n})\n```\n\n```text\nnuxt.config.file\n```\n\n```text\nmkcert\n```\n\n```text\nexport default defineNuxtConfig({\n devServer: {\n https: {\n key: 'localhost-key.pem',\n cert: 'localhost.pem'\n }\n },\n})\n```\n\n```text\nNODE_TLS_REJECT_UNAUTHORIZED=0\n```\n\n```text\nnuxt dev\n```\n\n```text\npackage.json\n```\n\n```text\nnuxt dev --https --ssl-cert localhost.pem --ssl-key localhost-key.pem\n```\n\n```text\n500 fetch failed\n```\n\n```text\nNODE_TLS_REJECT_UNAUTHORIZED=0\n```\n\n========================================\n\nComments:\n- Using webpack or vite? Check that one also: nuxt.com/docs/api/configuration/nuxt-config/#https\n- @kissu using vite. Also, I believe your link is the same as the one that I've included in my post?\n- Oh right, I was mainly wondering if you should not replace `devServer` by `server`. Not sure which one is a typo but it used to be just `server` as far as I remember. Also because having certificates locally on production seems quite wrong to me.\n- Yeah from all the examples I've seen, everyone seems to be using `server`. If I try to use it in the Nuxt config file, I get the error \"Object literal may only specify known properties, and 'server' does not exist in type 'NuxtConfig' \". Also, I'm not going to use self-signed certificates on production, it's for development only at the moment.\n- Maybe give a try to that one: github.com/nuxt/framework/discussions/7477\n- It seems following this guide: storyblok.com/faq/setting-up-https-on-localhost-in-nuxt-3 works and sets up HTTPS to work for development. However, now I'm getting a `500 fetch failed ()` error.\n- nuxt 3 docs in regards of devServer and https seem completely broken / misleading at this moment. Kind of a bummer considering, it should be a stable release now. + nuxtConfig devServer options, filled out according to TS schema, seem to have no effect. Your solution woked 👏\n- How to enable ssl for network ip or 127.0.0.1?\n- I've used your method, but on \"npm run dev\" i'm getting the following error, as per your answer, sounds as though you didn't need to create those files? - \" ERROR ENOENT: no such file or directory, open 'localhost-key.pem' \"\n- Yeah I get errors saying those files don't exist. Do we create them manually? Surely Nuxt 3 has a way to run localhost HTTPS without manually setting up SSL certs etc?\n- `nuxt dev --host --https` was sufficient for me","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":137,"estimatedTokens":1258}}743{"id":"stack-76198151","source":"stackoverflow","questionId":76198151,"title":"Nuxt 3 How to implement CORS?","tags":["nuxt.js","nuxt3.js"],"text":"Title: Nuxt 3 How to implement CORS?\nTags: nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nThis is related to my other question about Nuxt 3 security for API's. How do I add CORS? Currently, using the Helmet module is not working for me.\n\nThis is the link in my previous question\nNuxt 3 Prevent Other Wesbsites, Applications, or Domains from accessing my APIs?\n\n========================================\n\nTop Answer:\nIn my case, allow outside people to get login. I do it like this; it works for me:\n\n```\nexport default defineNuxtConfig({\n routeRules: {\n '/api/auth/**': {\n cors: true,\n },\n },\n}\n```\n\n========================================\n\nCode:\n```js\nexport default defineEventHandler((event) => {\n const headers = {\n 'Access-Control-Allow-Origin': 'Same-Origin',\n 'crossOriginResourcePolicy': 'same-origin',\n 'crossOriginOpenerPolicy': 'same-origin',\n 'crossOriginEmbedderPolicy': 'require-corp',\n 'contentSecurityPolicy': \"default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests\",\n 'X-XSS-Protection': 1\n }\n setHeaders(event, headers)\n\n})\n```\n\n```text\n~/server/middleware/cors.ts\n```\n\n```text\nexport default defineNuxtConfig({\n routeRules: {\n '/api/**': {\n proxy: { to: \"https:/backend/**\" },\n },\n },\n}\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nexport default defineNuxtConfig({\n routeRules: {\n '/api/auth/**': {\n cors: true,\n },\n },\n}\n```\n\n========================================\n\nComments:\n- How i can restrict server routes to be accessible only with in the app not from the external resources?","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":75,"estimatedTokens":455}}744{"id":"stack-76591837","source":"stackoverflow","questionId":76591837,"title":"How to receive props in child component in Nuxt 3","tags":["nuxt.js","strapi","nuxt3.js"],"text":"Title: How to receive props in child component in Nuxt 3\nTags: nuxt.js, strapi, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI have searched a lot of places online but can't seem to find a clear and straight to the point answer anywhere.\nGiven this loop in a parent component to out a list of child component, I am sending an object as props to a child component like this\n\n```\n\n \n\n```\n\nEach `review Object` will be in this format\n\n```\n{\n \"_id\": \"58c03ac18060197ca0b52d51\",\n \"author\": 3,\n \"user\": 2,\n \"comment\": \"I tried this place last week and it was incredible! Amazing selection of local and imported brews and the food is to die for! \",\n \"score\": 5,\n \"date\": \"2017-03-08T17:09:21.627Z\"\n}\n```\n\nMy question is how do I retrieve the props in the child component using `defineProps()` here:\n\n```\n\nimport ReviewStyles from \"./review.module.css\"\n\nconst props = defineProps()\n\n```\n\nThanks in advance\n\n========================================\n\nCode:\n```text\n<div v-for=\"review in reviews\">\n <ReviewsReview v:bind={review} :key=\"venuceReview.id\" />\n</div>\n```\n\n```text\n{\n \"_id\": \"58c03ac18060197ca0b52d51\",\n \"author\": 3,\n \"user\": 2,\n \"comment\": \"I tried this place last week and it was incredible! Amazing selection of local and imported brews and the food is to die for! \",\n \"score\": 5,\n \"date\": \"2017-03-08T17:09:21.627Z\"\n}\n```\n\n```text\n<script setup>\nimport ReviewStyles from \"./review.module.css\"\n\nconst props = defineProps()\n</script>\n```\n\n```text\nreview Object\n```\n\n```text\ndefineProps()\n```\n\n```js\n<template>\n <div>\n <div v-for=\"review in reviews\">\n <SingleReview :review=\"review\" :key=\"review._id\" />\n </div>\n </div>\n</template>\n```\n\n```js\n<script setup>\nconst props = defineProps({\n review: {\n type: Object,\n required: true,\n },\n});\nconst { review } = props;\n</script>\n```\n\n```text\npages/index.vue\n```\n\n```text\nreview\n```\n\n```text\nreview\n```\n\n```text\ncomponents/singleReview.vue\n```\n\n```text\nreview\n```\n\n========================================\n\nComments:\n- Easy and straight to the point. Thank you very much.","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":121,"estimatedTokens":510}}745{"id":"stack-70173603","source":"stackoverflow","questionId":70173603,"title":"Nuxt add GTM (noscript) to body tag on every page / route","tags":["vue.js","nuxt.js","google-tag-manager"],"text":"Title: Nuxt add GTM (noscript) to body tag on every page / route\nTags: vue.js, nuxt.js, google-tag-manager\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement Google Tag Manager on a Nuxt app and am stuck on how to add the noscript tag to the app on every page / route inside the opening body tag. I tried creating a static script and adding the file through the nuxt config:\n\n```\n{ src: \"/scripts/gtm.js\", body: true }\n```\n\nwhich added the file to the body but was throwing errors due to the noscript tag and nested iframe from gtm. Not sure if there is a better way to inject the actual script directly inside the body\n\n```\n\n```\n\n========================================\n\nTop Answer:\nThe head property in your `nuxt.config.js` lets you define all the meta data and scripts that appear on each page. It looks like you can add a noscript section for what you need.\n\n========================================\n\nCode:\n```js\n{ src: \"/scripts/gtm.js\", body: true }\n```\n\n```html\n<!-- Google Tag Manager (noscript) -->\n<noscript><iframe\nsrc=\"https://www.googletagmanager.com/ns.html?id=GT\nM-4BXKY65\"\nheight=\"0\" width=\"0\"\nstyle=\"display:none;visibility:hidden\"></iframe></n\noscript>\n<!-- End Google Tag Manager (noscript) -->\n```\n\n```text\n<noscript>\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n<template>\n <noscript v-html=\"iFrameCode\" />\n</template>\n\n<script>\nexport default {\n data() {\n return {\n iFrameCode: '<iframe src=\"https://www.googletagmanager.com/ns.html?id=GTM-XYXYXYX\" height=\"0\" width=\"0\" style=\"display: none; visibility: hidden\" />',\n }\n },\n}\n</script>\n```\n\n```text\nnoscript\n```\n\n```text\nlayouts/default.vue\n```\n\n```text\nbody\n```\n\n```text\nreturn {\n head: {\n script: [\n {\n type: 'text/javascript',\n body: true,\n innerHTML: '(function(d){'\n +'var b=d.getElementsByTagName(\"div\")[0],'\n +'n=d.createElement(\"noscript\"),'\n +'i=d.createElement(\"iframe\"),'\n +'c1=d.createComment(\"Google Tag Manager (noscript)\"),'\n +'c2=d.createComment(\"End Google Tag Manager (noscript)\");'\n +'i.src=\"https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX\";'\n +'i.style.height=\"0\";'\n +'i.style.width=\"0\";'\n +'i.style.display=\"none\";'\n +'i.style.visibility=\"hidden\";'\n +'n.appendChild(i);'\n +'b.parentNode.insertBefore(c1,b);'\n +'b.parentNode.insertBefore(n,b);'\n +'b.parentNode.insertBefore(c2,b);'\n +'})(document);'\n },\n ]\n }\n}\n```\n\n```text\n<noscript>\n```\n\n```text\n<body>\n```\n\n```text\n<div>\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n<script>\n```\n\n```text\n<script>\n```\n\n```text\n<head>\n```\n\n```text\nGTM-XXXXXXX\n```\n\n```text\nnoscript: [\n {\n children: `<iframe src=\"https://www.googletagmanager.com/ns.html?id=${process.env.GOOGLE_TAG_MANAGER_ID}\" height=\"0\" width=\"0\" style=\"display:none;visibility:hidden\"></iframe>`,\n type: 'text/html',\n body: true\n }\n],\n```\n\n```text\nuseHead({\n noscript: [{\n innerHTML: `\n <iframe src=\"https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXXX\"\n height=\"0\" width=\"0\" style=\"display:none;visibility:hidden\"></iframe>\n `,\n tagPosition: 'bodyOpen'\n }]\n})\n```\n\n```text\nnoscript\n```\n\n```text\ninnerHTML\n```\n\n```text\ntagPosition\n```\n\n```text\n<body>\n```\n\n========================================\n\nComments:\n- Does it really make sense to add a noscript tag to a javascript based page?\n- FYI Nuxt can render almost all of your page statically and later make it interactive (with JS), so it's not a bad idea at all to warn users why they might be missing out on some of the interactivity. E.g. it can prerender a form but a user won't be able to submit it.\n- I get it, thank you for input. I don't know much about GTM (first time implementing). Vendor sends me that script and says please put this on every page after body tag. Thats why I asked the question :)\n- Yes, vendors often send those snippets with noscript. That's considered best practice on their side. We just throw away the noscript part and the vendor never frowns upon it. Even when it's not a JS-rendered front-end of an SPA. People nowadays don't disable JS.\n- It interpolates the string as an actual `iframe` and since that one is an HTML tag (not some JS running), it's working. Looks totally fine for me.\n- @kissu Yes, exactly.\n- Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. **Would you kindly edit your answer to include additional details for the benefit of the community?**","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":185,"estimatedTokens":1202}}746{"id":"stack-56569353","source":"stackoverflow","questionId":56569353,"title":"Vue-Lottie and Nuxt","tags":["vue.js","nuxt.js","lottie"],"text":"Title: Vue-Lottie and Nuxt\nTags: vue.js, nuxt.js, lottie\nSource: Stack Overflow\n\nQuestion:\nAnyone get Vue-Lottie working with Nuxt? I tried to import it as Vue-Lotti said to:\n\n`import Lottie from './lottie.vue';`\n\nthis says it cant find the package.\n\nThen I tried how Nuxt had it:\n\n`import Lottie from 'vue-lottie';`\n\nthis gives me an \"Unexpected token What am I missing?\n\n========================================\n\nTop Answer:\nIf you want to use vue-lottie, you need to import the right lottie.vue component, located in your node_modules folder:\n\n```\nimport Lottie from 'vue-lottie/src/lottie.vue'\n```\n\nHope it works.\n\n========================================\n\nCode:\n```text\nimport Lottie from './lottie.vue';\n```\n\n```text\nimport Lottie from 'vue-lottie';\n```\n\n```text\nlottie-web\n```\n\n```text\nvue-lottie\n```\n\n```text\nnpm install lottie-web\n```\n\n```text\nimport lottie from 'lottie-web/build/player/lottie';\n```\n\n```text\nvue-lottie\n```\n\n```text\nimport lottie from 'lottie-web'\n```\n\n```text\nimport Lottie from 'vue-lottie/src/lottie.vue'\n```\n\n```text\nimport lottie from 'lottie-web';\n\nexport default ({ app }, inject) => {\n inject('lottie', lottie);\n};\n```\n\n```text\nplugins: [{ src: '~/plugins/lottie', mode: 'client' }],\n```\n\n```text\n<template>\n <div\n ref=\"animationElement\"\n class=\"animation\"\n @mouseover=\"open\"\n @focus=\"open\"\n @mouseleave=\"close\"\n @blur=\"close\"\n />\n</template>\n<script>\nexport default {\n mounted() {\n this.$lottie.loadAnimation({\n container: this.$refs.animationElement, // the dom element that will contain the animation\n loop: false,\n autoplay: false,\n path: 'your_path/lottie.json', // the path to the animation json\n })\n },\n methods: {\n close() {\n this.$lottie.setSpeed(1)\n this.$lottie.setDirection(1)\n this.$lottie.play()\n },\n open() {\n this.$lottie.setSpeed(1.5)\n this.$lottie.setDirection(-1)\n this.$lottie.play()\n },\n },\n}\n</script>\n```\n\n```text\nexport default defineNuxtConfig({\n plugins: [{ src: '~/plugins/lottie', mode: 'client' }],\n})\n```\n\n```text\nimport lottie from 'lottie-web'\n \nexport default defineNuxtPlugin((nuxtApp) => nuxtApp.provide('lottie', lottie))\n```\n\n```text\n<script setup>\n const nuxtApp = useNuxtApp();\n\n onMounted(() => { \n nuxtApp.$lottie.loadAnimation({ ... });\n```\n\n```text\nNuxt 3\n```\n\n```text\nComposition API\n```\n\n========================================\n\nComments:\n- I cannot really make it work. What should I add on the ``?\n- You should insert the element ref to the `container` field of the parameter in the `loadAnimation`, for example: ``` onMounted(() => { nuxtApp.$lottie.loadAnimation({ container: document.getElementById('menu-burger'), name: 'menu-burger', renderer: 'svg', loop: true, autoplay: true, path: '/animations/menu-burger.json', }); } ```\n- In other words, the best and safe way is to dedicate an HTML element by id. For example, you can add a `` with an `id` you can refer to in your `` area. LIke this: ` `. And get it by standard `getElementById` function: `nuxtApp.$lottie.loadAnimation({ container: document.getElementById('menu-burger'), ... });`","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":150,"estimatedTokens":790}}747{"id":"stack-60716983","source":"stackoverflow","questionId":60716983,"title":"How to use SSR with Nuxt.js on Netlify","tags":["nuxt.js","server-side-rendering","netlify"],"text":"Title: How to use SSR with Nuxt.js on Netlify\nTags: nuxt.js, server-side-rendering, netlify\nSource: Stack Overflow\n\nQuestion:\nThe way I understand is Server Side Rendering (SSR) is where the server renders the page and then sends chunks of data to the browser via one stream as opposed to the browser (client) loading the HTML page and then making the requests for all the JS/CSS etc. \n\nThis is the behaviour I would like to support for my webpage. But following their guide for Netlify, generates static HTML pages as normal with links to all the external dependencies? \n\nIn that case won't running `npm run generate` disable SSR? Or am I completely misunderstanding how this works?\n\n========================================\n\nTop Answer:\n*Edit 01/12/2021:*\n\nThe original answer was to help anyone with Nuxt 2 and SSR on serverless platforms, but as of Nuxt 3 Beta, they have implemented SSR for Netlify: https://nuxt.com/deploy/netlify\n\n*Original Answer:*\n\nYou can achieve it on Vercel with Vercel Builder for Nuxt. It adapts your project to use a serverless function and render your project with it. :\nhttps://github.com/nuxt/vercel-builder\n\nTaken from the readme:\n\n### How it works\n\n*This Vercel builder takes a Nuxt application defined by a nuxt.config.js (or .ts) entrypoint and deploys it as a serverless function in a Vercel environment.*\n\n*It features built-in caching of node_modules and the global yarn cache (even when dependencies change) and a multi-stage build for fast and small deployments.*\n\n========================================\n\nCode:\n```text\nnpm run generate\n```\n\n========================================\n\nComments:\n- A link to a potential solution is always welcome, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline.\n- @AbhishekDutt Noted and thank you\n- Thanks for the alternative Ciril. I should note that as of Nuxt 3 (this question with Nuxt 2) Netlify now has support for Nuxt and SSR\n- Yes, you are right. I should have added this to my reply. It's a shame Netlify didn't implement something like this for Nuxt 2, since a lot of projects are still build with that. As of now Nuxt 3 is still in beta.","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":45,"estimatedTokens":579}}748{"id":"stack-60889759","source":"stackoverflow","questionId":60889759,"title":"Moving Nuxt store to modules mode generates 'getters should be function' error","tags":["vuex","nuxt.js"],"text":"Title: Moving Nuxt store to modules mode generates 'getters should be function' error\nTags: vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSince classic mode is going to be deprecated soon, I'm trying to move my store to modules mode. However I do want to keep state, actions, mutations and getters in separate files. So lets say I currently only have one module - auth. This is my store structure:\n\n```\nstore\n |_ modules\n | |_auth\n | |_actions.js\n | |_getters.js\n | |_mutations.js\n | |_state.js\n |\n |_actions.js\n |_auth.js\n |_getters.js\n |_index.js\n |_mutations.js\n |_state.js\n```\n\n`store\\modules\\auth\\state.js` currently has only one property:\n\n```\nexport const state = () => {\n return {\n token: null\n }\n}\n```\n\nThis is `store\\modules\\auth\\getters.js`\n\n```\nexport const getters = {\n isAuthenticated(state) {\n return !!state.token\n }\n}\n```\n\nThen in my `store\\auth.js`:\n\n```\nimport {actions} from './modules/auth/actions'\nimport {getters} from './modules/auth/getters'\nimport {mutations} from './modules/auth/mutations'\nimport {state} from './modules/auth/state'\n\nexport {\n actions,\n getters,\n mutations,\n state\n}\n```\n\nAnd finally in my `store\\index.js` I only have this code:\n\n```\nexport default {\n namespaced: true,\n strict: true\n}\n```\n\nThis gives me the following error:\n`[vuex] getters should be function but \"getters.getters\" in module \"modules.auth\" is {}.`\n\nI've been scratching my head for hours now and don't know how to tackle that. \n\nI tried to do something like that, for example:\n\n```\nexport const getters = () => {\n return {\n isAuthenticated: state => !!state.token\n }\n}\n```\n\nThat did compile, but in the console it threw another error:\n`[vuex] unknown getter: auth/isAuthenticated`\n\nAnd it also gives me this warning:\n`store/modules/auth/state.js should export a method that returns an object`\n\nAnd there I thought I do that...\n\nAny ideas, please?\n\n========================================\n\nCode:\n```text\nstore\n |_ modules\n | |_auth\n | |_actions.js\n | |_getters.js\n | |_mutations.js\n | |_state.js\n |\n |_actions.js\n |_auth.js\n |_getters.js\n |_index.js\n |_mutations.js\n |_state.js\n```\n\n```js\nexport const state = () => {\n return {\n token: null\n }\n}\n```\n\n```js\nexport const getters = {\n isAuthenticated(state) {\n return !!state.token\n }\n}\n```\n\n```js\nimport {actions} from './modules/auth/actions'\nimport {getters} from './modules/auth/getters'\nimport {mutations} from './modules/auth/mutations'\nimport {state} from './modules/auth/state'\n\nexport {\n actions,\n getters,\n mutations,\n state\n}\n```\n\n```js\nexport default {\n namespaced: true,\n strict: true\n}\n```\n\n```text\nexport const getters = () => {\n return {\n isAuthenticated: state => !!state.token\n }\n}\n```\n\n```text\nstore\\modules\\auth\\state.js\n```\n\n```text\nstore\\modules\\auth\\getters.js\n```\n\n```text\nstore\\auth.js\n```\n\n```text\nstore\\index.js\n```\n\n```text\n[vuex] getters should be function but \"getters.getters\" in module \"modules.auth\" is {}.\n```\n\n```text\n[vuex] unknown getter: auth/isAuthenticated\n```\n\n```text\nstore/modules/auth/state.js should export a method that returns an object\n```\n\n```text\nexport default {\n isAuthenticated(state) {\n return !!state.token\n }\n}\n```\n\n```text\nexport default () => ({\n token: null\n})\n```\n\n```text\nstore\n |_auth\n | |_actions.js\n | |_getters.js\n | |_mutations.js\n | |_state.js\n |\n |_actions.js\n |_getters.js\n |_mutations.js\n |_state.js\n```\n\n```text\nauth\n```\n\n```text\nmodules\n```\n\n```text\nstore\n```\n\n```text\nindex.js\n```\n\n```text\nauth.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":234,"estimatedTokens":870}}749{"id":"stack-59690194","source":"stackoverflow","questionId":59690194,"title":"Apollo+GraphQL - Heuristic Fragment Manual Matching","tags":["graphql","nuxt.js","apollo","vue-apollo"],"text":"Title: Apollo+GraphQL - Heuristic Fragment Manual Matching\nTags: graphql, nuxt.js, apollo, vue-apollo\nSource: Stack Overflow\n\nQuestion:\nI have a headless Craft CMS that is returning data to my Nuxtjs app through a GraphQL endpoint through Apollo. I have a field that can return one of three different block types: `richText`, `image`, and `pullQuote`.\n\nMy GraphQL endpoint looks like this:\n\n```\nquery($section:[String], $slug:[String]) {\n entries(section: $section, slug: $slug) {\n id,\n title,\n uri,\n ... on blog_blog_Entry{\n contentEngine{\n __typename,\n ...on contentEngine_richText_BlockType{\n __typename,\n id,\n richText\n fontColor,\n backgroundColor\n }\n ...on contentEngine_image_BlockType{\n __typename,\n id,\n backgroundColor,\n imageWidth,\n image {\n id,\n url\n }\n }\n ...on contentEngine_pullQuote_BlockType{\n __typename,\n id,\n backgroundColor,\n fontColor,\n quote\n }\n }\n }\n }\n}\n```\n\nIt returns data just fine, but I'm getting this error when trying to use it within my Nuxt component:\n\n You are using the simple (heuristic) fragment matcher, but your queries contain union or interface types. Apollo Client will not be able to accurately map fragments. To make this error go away, use the `IntrospectionFragmentMatcher` as described in the docs: https://www.apollographql.com/docs/react/advanced/fragments.html#fragment-matcher\n\nThe infuriating thing is that this documentation leads to a 404. I've found a few other GitHub tickets that reference this link, so I'm not sure what steps I should be following.\n\nI think what I need to do is to teach Apollo's memory cache. Since my response isn't that complicated, I think I can get away with Defining PossibleTypes manually.\n\nI've tried the following, but I don't think I'm understanding how to set this up properly:\n\n```\nconst cache = new InMemoryCache({\n possibleTypes: {\n contentEngine: [\n \"contentEngine_richText_BlockType\", \n \"contentEngine_pullQuote_BlockType\", \n \"contentEngine_image_BlockType\"\n ],\n },\n});\n```\n\nAny help for getting around this issue would be a huge help.\n\n WARNING: heuristic fragment matching going on!\n\n========================================\n\nTop Answer:\nI struggled with this myself, but after @mylesthe.dev (who responded above) spoke to me directly to provide fantastic support and some examples, I figured it out. So for anyone else still struggling like I was, here's the code (thanks to his work) which finally got things working for me:\n\nFirst of all, in your nuxt.config.js set up your apollo configs:\n\n```\n// Apollo config and endpoint for graph ql\napollo: {\n includeNodeModules: true,\n clientConfigs: {\n default: '@/apollo/client-configs/default.js' // This is where you'll set up the client and import the possible fragment types\n }\n},\n```\n\nNow we create the apollo client set up with the fragment schema file (which we'll create) in `apollo/client-configs/default.js`\n\n```\nimport { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';\nimport schema from './schema.json';\nconst fragmentMatcher = new IntrospectionFragmentMatcher({\n introspectionQueryResultData: schema\n })\n\nexport default ({req, app}) => {\n const token = process.env.GRAPHQL_TOKEN\n return {\n httpEndpoint: process.env.API_ENDPOINT,\n getAuth: () => `Bearer ${token}`, // remove if you're using the public schema\n cache: new InMemoryCache({ fragmentMatcher }),\n }\n}\n```\n\nNow save an empty `schema.json` file in `apollo/client-configs/`.\n\nNext we need to set up the script to query and generate this schema on `nuxtServerInit`. You'll need `fs` to write your schema file. You can install it with NPM: `npm install --save fs`.\n\nOnce installed, go back to your nuxt.config and add fs to the build:\n\n```\nbuild: {\n extend (config, ctx) {\n config.node = {\n fs: 'empty'\n }\n }\n}\n```\n\nThen in your `store/index.js`:\n\n```\nimport Vuex from 'vuex';\nimport fetch from 'node-fetch';\nimport fs from 'fs';\n\nconst createStore = () => {\n return new Vuex.Store({\n actions: {\n async nuxtServerInit({commit}, {app}) {\n\n // only update fragements locally\n if (process.env.NODE_ENV == 'local') {\n \n // LOAD FRAGMENT TYPES AND STORE IN FILE\n // APOLLO READS THIS FILE LATER\n fetch(process.env.API_ENDPOINT, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', authorization: 'Bearer ' + process.env.GRAPHQL_TOKEN, },\n body: JSON.stringify({\n variables: {},\n query: `\n {\n __schema {\n types {\n kind\n name\n possibleTypes {\n name\n }\n }\n }\n }\n `,\n }),\n })\n .then(result => result.json())\n .then(result => {\n // here we're filtering out any type information unrelated to unions or interfaces\n const filteredData = result.data.__schema.types.filter(\n type => type.possibleTypes !== null,\n );\n result.data.__schema.types = filteredData;\n fs.writeFile('./apollo/client-configs/schema.json', JSON.stringify(result.data), err => {\n if (err) {\n console.error('Error writing fragmentTypes file', err);\n }\n });\n });\n\n }\n \n },\n }\n });\n};\n\nexport default createStore\n```\n\nYour schema should now be generated locally to the schema file and that file will be stored in the apollo cache.\n\n========================================\n\nCode:\n```text\nquery($section:[String], $slug:[String]) {\n entries(section: $section, slug: $slug) {\n id,\n title,\n uri,\n ... on blog_blog_Entry{\n contentEngine{\n __typename,\n ...on contentEngine_richText_BlockType{\n __typename,\n id,\n richText\n fontColor,\n backgroundColor\n }\n ...on contentEngine_image_BlockType{\n __typename,\n id,\n backgroundColor,\n imageWidth,\n image {\n id,\n url\n }\n }\n ...on contentEngine_pullQuote_BlockType{\n __typename,\n id,\n backgroundColor,\n fontColor,\n quote\n }\n }\n }\n }\n}\n```\n\n```js\nconst cache = new InMemoryCache({\n possibleTypes: {\n contentEngine: [\n \"contentEngine_richText_BlockType\", \n \"contentEngine_pullQuote_BlockType\", \n \"contentEngine_image_BlockType\"\n ],\n },\n});\n```\n\n```text\nrichText\n```\n\n```text\nimage\n```\n\n```text\npullQuote\n```\n\n```text\nIntrospectionFragmentMatcher\n```\n\n```text\npossibleTypes\n```\n\n```text\napollo-client\n```\n\n```text\n@apollo/client\n```\n\n```text\npossibleTypes\n```\n\n```text\ncontentEngine\n```\n\n```text\ncontentEngine\n```\n\n```text\napollo-client\n```\n\n```text\nIntrospectionFragmentMatcher\n```\n\n```js\nimport possibleTypes from './possibleTypes.json';\nimport { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';\nconst fragmentMatcher = new IntrospectionFragmentMatcher({\n introspectionQueryResultData: possibleTypes\n})\n```\n\n```js\ncache: new InMemoryCache({\n fragmentMatcher\n})\n```\n\n```text\nquery {\n __schema {\n types {\n name\n kind\n possibleTypes {\n name\n description\n }\n }\n }\n}\n```\n\n```text\npossibleTypes.json\n```\n\n```text\nnuxtInitServer\n```\n\n```js\n// Apollo config and endpoint for graph ql\napollo: {\n includeNodeModules: true,\n clientConfigs: {\n default: '@/apollo/client-configs/default.js' // This is where you'll set up the client and import the possible fragment types\n }\n},\n```\n\n```js\nimport { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';\nimport schema from './schema.json';\nconst fragmentMatcher = new IntrospectionFragmentMatcher({\n introspectionQueryResultData: schema\n })\n\nexport default ({req, app}) => {\n const token = process.env.GRAPHQL_TOKEN\n return {\n httpEndpoint: process.env.API_ENDPOINT,\n getAuth: () => `Bearer ${token}`, // remove if you're using the public schema\n cache: new InMemoryCache({ fragmentMatcher }),\n }\n}\n```\n\n```js\nbuild: {\n extend (config, ctx) {\n config.node = {\n fs: 'empty'\n }\n }\n}\n```\n\n```js\nimport Vuex from 'vuex';\nimport fetch from 'node-fetch';\nimport fs from 'fs';\n\n\nconst createStore = () => {\n return new Vuex.Store({\n actions: {\n async nuxtServerInit({commit}, {app}) {\n\n // only update fragements locally\n if (process.env.NODE_ENV == 'local') {\n \n // LOAD FRAGMENT TYPES AND STORE IN FILE\n // APOLLO READS THIS FILE LATER\n fetch(process.env.API_ENDPOINT, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', authorization: 'Bearer ' + process.env.GRAPHQL_TOKEN, },\n body: JSON.stringify({\n variables: {},\n query: `\n {\n __schema {\n types {\n kind\n name\n possibleTypes {\n name\n }\n }\n }\n }\n `,\n }),\n })\n .then(result => result.json())\n .then(result => {\n // here we're filtering out any type information unrelated to unions or interfaces\n const filteredData = result.data.__schema.types.filter(\n type => type.possibleTypes !== null,\n );\n result.data.__schema.types = filteredData;\n fs.writeFile('./apollo/client-configs/schema.json', JSON.stringify(result.data), err => {\n if (err) {\n console.error('Error writing fragmentTypes file', err);\n }\n });\n });\n\n }\n \n },\n }\n });\n};\n\nexport default createStore\n```\n\n```text\napollo/client-configs/default.js\n```\n\n```text\nschema.json\n```\n\n```text\napollo/client-configs/\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nfs\n```\n\n```text\nnpm install --save fs\n```\n\n```text\nstore/index.js\n```\n\n========================================\n\nComments:\n- Thanks Daniel. Your answer led me to this thread which helped me figure out how to implement Apollo's IntrospectionFragmentMatcher with Nuxtjs.\n- Hi @mylesthe.dev thanks for posting this - i am attempting the shift to graph QL with Nuxt but I'm relatively new to both. I've run into this issue for multiple matrix field queries. Any chance you could provide a little more context as to where I place each of the above snippets in Nuxt to solve this globally?\n- @ToddPadwick sent you some examples :)\n- `fs` moved as shown here and on top of that, you don't need to install `fs` because it comes out of the box with Node (and so, with Nuxt). Also, this does not work if you go `SPA` mode only with Nuxt (why tho, but still) because you will `yarn build` rather than `yarn generate` and it will introduce the fact that the Node server is not called. nuxtjs.org/docs/2.x/concepts/nuxt-lifecycle/#server Thanks for the guide tho. :)","metadata":{"transformedAt":"2026-08-18T18:33:07.890Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":460,"estimatedTokens":2836}}750{"id":"stack-71113582","source":"stackoverflow","questionId":71113582,"title":"Displaying markdown content from a string using nuxtjs content","tags":["nuxt.js"],"text":"Title: Displaying markdown content from a string using nuxtjs content\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSuppose, I have a string with markdown contents in it in my database and after fetching that string from the database how can I display it with nuxtjs content module without using md extension?\nCan anyone show me how to do that?\n\n========================================\n\nTop Answer:\nThanks to tony19's answer, I was able to create simple component which renders passed string with Markdown content dynamically. Maybe it will be useful for somebody, too!\n\n*./components/MarkdownStringRenderer.vue*\n\n```\n\nimport markdownParser from \"@nuxt/content/transformers/markdown\"\n\nconst props = defineProps({\n markdownString: {\n type: String,\n required: true,\n }\n});\n\nconst record = ref(\"\");\n\nwatchEffect(async () => {\n await markdownParser.parse(\"custom.md\", props.markdownString).then((md) => record.value = md);\n});\n\n \n\n```\n\nComponent usage example:\n\n```\n\n```\n\nMarkdown will be re-rendered each time `description` changes.\n\n========================================\n\nCode:\n```text\n{\n modules: [\n '@nuxtjs/markdownit'\n ],\n markdownit: {\n runtime: true // Support `$md()`\n }\n}\n```\n\n```text\n<template>\n <div v-html=\"$md.render(model)\"></div>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n model: '# Hello World!'\n }\n }\n}\n</script>\n```\n\n```text\n$md\n```\n\n```text\n<script setup>\nimport markdownParser from \"@nuxt/content/transformers/markdown\"\n\nconst props = defineProps({\n markdownString: {\n type: String,\n required: true,\n }\n});\n\nconst record = ref(\"\");\n\nwatchEffect(async () => {\n await markdownParser.parse(\"custom.md\", props.markdownString).then((md) => record.value = md);\n});\n</script>\n\n<template>\n <ContentRendererMarkdown :value=\"record\" v-if=\"record\" />\n</template>\n```\n\n```text\n<MarkdownStringRenderer :markdownString=\"description\" />\n```\n\n```text\ndescription\n```\n\n```text\n<template>\nContentRendererMarkdown(v-if=\"record\" :value=\"record\")\n</template>\n\n<script setup lang=\"ts\">\n// @ts-expect-error avoid lint error\nimport markdownParser from '@nuxt/content/transformers/markdown'\n\nconst props = defineProps<{\n markdownString: string\n}>()\n\nconst record = ref<string>('')\n\nwatch(\n () => props.markdownString,\n async () => {\n await markdownParser\n .parse('customId', props.markdownString)\n .then((md: string) => (record.value = md))\n },\n)\n</script>\n```\n\n```js\n<MDC value=\"# Here is a markdown title\" />\n```\n\n========================================\n\nComments:\n- Are you using nuxt content module for purely rendering markdown or the whole functionality of nuxt content?\n- I just want to use it for rendering markdown @UdithIshara can you tell me how to do it? Please?\n- doesnt work with nuxt3 : (","metadata":{"transformedAt":"2026-08-18T18:33:07.891Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":145,"estimatedTokens":693}}751{"id":"stack-69000161","source":"stackoverflow","questionId":69000161,"title":"How to use microfrontends with Vue/Nuxt?","tags":["vue.js","vuejs2","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: How to use microfrontends with Vue/Nuxt?\nTags: vue.js, vuejs2, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI wanted to know how to use Microfrontends with Nuxt or at least Vue.\n\nIs there a plug & play simple solution to have it working quickly?\n\nI've heard about Webpack's v5 ModuleFederationPlugin for example, is this a valid thing to start my Nuxt project?\n\n========================================\n\nCode:\n```text\nModuleFederationPlugin\n```\n\n```text\nModuleFederationPlugin\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.891Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":21,"estimatedTokens":126}}752{"id":"stack-59198021","source":"stackoverflow","questionId":59198021,"title":"How to provide/inject into Vue root instance WITH nuxt and @vue/composition-api?","tags":["typescript","nuxt.js","vue-apollo","vuejs3","vue-composition-api"],"text":"Title: How to provide/inject into Vue root instance WITH nuxt and @vue/composition-api?\nTags: typescript, nuxt.js, vue-apollo, vuejs3, vue-composition-api\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use @vue/apollo-composable with my Nuxt-Ts application. This is the example how it should be injected into root instance on a \"normal\" Vue application:\n\n```\nimport { provide } from '@vue/composition-api'\nimport { DefaultApolloClient } from '@vue/apollo-composable'\n\nconst app = new Vue({\n setup () {\n provide(DefaultApolloClient, apolloClient)\n },\n\n render: h => h(App),\n})\n```\n\n**Problem:** I don't know how to get access to the root instance **in Nuxt-TS**.\n\nI tried making a plugin, but it's injected either directly into the root instance (which is not right, because `@vue/apollo-composable` is using `composition-api::provide()` which creates it's own property `_provided`.\n\nAnd if I use nuxt plugin's `inject` a `$` get's concatenated. And if I write a `_provided` object directly in via `ctx.app._provided =` it doesn't stick.\n\n```\nimport { DefaultApolloClient } from \"@vue/apollo-composable\";\nconst myPlugin: Plugin = (context, inject) => {\n const defaultClient = ctx.app.apolloProvider.defaultClient;\n inject(DefaultApolloClient.toString(), defaultClient) // results in $$ and also composition-api::inject is checking inside `_provided[DefaultApolloClient]`\n}\n\nexport default myPlugin\n```\n\nI can't call `provide()` like in the original example, because it's only allowed inside a `VueComponent::setup` function.\n\nI also tried creating a Component and just use it on the page I need it (kind of defeats the purpose of installing in root instance though)\n\n```\nconst InstallGraphQl = createComponent({\n name: \"InstallGraphQl\",\n setup(_props, ctx: any) {\n debugger;\n const apolloClient = ctx.app.apolloProvider.defaultClient;\n ctx.provide(DefaultApolloClient, apolloClient);\n },\n});\nexport default createComponent({\n name: \"DefaultLayout\",\n components: {\n InstallGraphQl\n },\n setup(_props, _ctx: SetupContext) {\n const { result } = useQuery(SharedLayoutQuery);\n return { result };\n },\n});\n```\n\nbut then `setup` of the exported components gets called before `InstallGraphQl::setup`...\n\nEdit: Also for more information about `@vue/apollo-composable` see discussion here: https://github.com/vuejs/vue-apollo/issues/687\n\n========================================\n\nTop Answer:\nI don't use nuxt-ts but i do have this setup in a nuxt application. In my default.vue template i provide like this.\n\n```\n\n import { provide } from '@vue/composition-api';\n import { ApolloClients } from '@vue/apollo-composable'\n\n export default {\n setup(props, context) {\n provide(ApolloClients, {\n default: context.root.$apollo,\n })\n }\n }\n\n```\n\nPackage versions are\n\n```\n\"@vue/apollo-composable\": \"4.0.0-alpha.1\"\n\"@vue/composition-api\": \"version\": \"0.3.4\"\n```\n\nApollo Setup\n\n```\n//apolloClient.js\nimport { ApolloClient } from 'apollo-client';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport link from './link';\n\nexport default function apolloClient(_, inject) {\n const cache = new InMemoryCache();\n\n const client = new ApolloClient({\n // Provide required constructor fields\n cache,\n link,\n // Provide some optional constructor fields\n name: 'apollo-client',\n queryDeduplication: false,\n defaultOptions: {\n watchQuery: {\n fetchPolicy: 'cache-and-network',\n },\n },\n });\n\n inject('apollo', client);\n}\n\n// link.js\nimport { split } from 'apollo-link';\nimport { HttpLink } from 'apollo-link-http';\nimport { WebSocketLink } from 'apollo-link-ws';\nimport { getMainDefinition } from 'apollo-utilities';\nimport fetch from 'unfetch';\nconst httpLink = new HttpLink({\n uri: 'http://localhost:8080/v1/graphql',\n credentials: 'same-origin',\n fetch,\n});\n\nconst wsParams = {\n uri: `ws://localhost:8080/v1/graphql`,\n reconnect: true,\n};\n\nif (process.server) {\n wsParams.webSocketImpl = require('ws');\n}\n\nconst wsLink = new WebSocketLink(wsParams);\n\n// using the ability to split links, you can send data to each link\n// depending on what kind of operation is being sent\nconst link = split(\n // split based on operation type\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' &&\n definition.operation === 'subscription'\n );\n },\n wsLink,\n httpLink,\n);\n\nexport default link;\n```\n\nThen with the above, you include apollo in your nuxtconfig as a plugin\n\n```\nplugins: [\n '~/plugins/vue-composition-api',\n '~/plugins/apolloClient'\n ],\n```\n\n========================================\n\nCode:\n```text\nimport { provide } from '@vue/composition-api'\nimport { DefaultApolloClient } from '@vue/apollo-composable'\n\nconst app = new Vue({\n setup () {\n provide(DefaultApolloClient, apolloClient)\n },\n\n render: h => h(App),\n})\n```\n\n```text\nimport { DefaultApolloClient } from \"@vue/apollo-composable\";\nconst myPlugin: Plugin = (context, inject) => {\n const defaultClient = ctx.app.apolloProvider.defaultClient;\n inject(DefaultApolloClient.toString(), defaultClient) // results in $$ and also composition-api::inject is checking inside `_provided[DefaultApolloClient]`\n}\n\nexport default myPlugin\n```\n\n```text\nconst InstallGraphQl = createComponent({\n name: \"InstallGraphQl\",\n setup(_props, ctx: any) {\n debugger;\n const apolloClient = ctx.app.apolloProvider.defaultClient;\n ctx.provide(DefaultApolloClient, apolloClient);\n },\n});\nexport default createComponent({\n name: \"DefaultLayout\",\n components: {\n InstallGraphQl\n },\n setup(_props, _ctx: SetupContext) {\n const { result } = useQuery(SharedLayoutQuery);\n return { result };\n },\n});\n```\n\n```text\n@vue/apollo-composable\n```\n\n```text\ncomposition-api::provide()\n```\n\n```text\n_provided\n```\n\n```text\ninject\n```\n\n```text\n$\n```\n\n```text\n_provided\n```\n\n```text\nctx.app._provided =\n```\n\n```text\nprovide()\n```\n\n```text\nVueComponent::setup\n```\n\n```text\nsetup\n```\n\n```text\nInstallGraphQl::setup\n```\n\n```text\n@vue/apollo-composable\n```\n\n```js\n/* plugins/provide-apollo-client.js */\n\nimport {provide} from '@vue/composition-api'\nimport {DefaultApolloClient} from '@vue/apollo-composable'\n\nexport default function ({app}) {\n app.setup = () => {\n provide(DefaultApolloClient, ...)\n }\n\n // Or, use local mixin\n app.mixins = (app.mixins || []).concat({\n setup () {...},\n })\n}\n```\n\n```js\n/* nuxt.config.js */\n\nexport default {\n plugins: ['~/plugins/provide-apollo-client'],\n}\n```\n\n```text\nsetup()\n```\n\n```text\n<script>\n import { provide } from '@vue/composition-api';\n import { ApolloClients } from '@vue/apollo-composable'\n\n export default {\n setup(props, context) {\n provide(ApolloClients, {\n default: context.root.$apollo,\n })\n }\n }\n</script>\n```\n\n```text\n\"@vue/apollo-composable\": \"4.0.0-alpha.1\"\n\"@vue/composition-api\": \"version\": \"0.3.4\"\n```\n\n```text\n//apolloClient.js\nimport { ApolloClient } from 'apollo-client';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport link from './link';\n\nexport default function apolloClient(_, inject) {\n const cache = new InMemoryCache();\n\n const client = new ApolloClient({\n // Provide required constructor fields\n cache,\n link,\n // Provide some optional constructor fields\n name: 'apollo-client',\n queryDeduplication: false,\n defaultOptions: {\n watchQuery: {\n fetchPolicy: 'cache-and-network',\n },\n },\n });\n\n inject('apollo', client);\n}\n\n// link.js\nimport { split } from 'apollo-link';\nimport { HttpLink } from 'apollo-link-http';\nimport { WebSocketLink } from 'apollo-link-ws';\nimport { getMainDefinition } from 'apollo-utilities';\nimport fetch from 'unfetch';\nconst httpLink = new HttpLink({\n uri: 'http://localhost:8080/v1/graphql',\n credentials: 'same-origin',\n fetch,\n});\n\nconst wsParams = {\n uri: `ws://localhost:8080/v1/graphql`,\n reconnect: true,\n};\n\nif (process.server) {\n wsParams.webSocketImpl = require('ws');\n}\n\nconst wsLink = new WebSocketLink(wsParams);\n\n// using the ability to split links, you can send data to each link\n// depending on what kind of operation is being sent\nconst link = split(\n // split based on operation type\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' &&\n definition.operation === 'subscription'\n );\n },\n wsLink,\n httpLink,\n);\n\nexport default link;\n```\n\n```text\nplugins: [\n '~/plugins/vue-composition-api',\n '~/plugins/apolloClient'\n ],\n```\n\n```text\nimport { onGlobalSetup } from 'nuxt-composition-api'\n\nexport default () => {\n onGlobalSetup(() => {\n provide('globalKey', true)\n })\n}\n```\n\n```text\nnuxt-composition-api\n```\n\n========================================\n\nComments:\n- Thanks for the answer, that seems to be the only way at this time that works? But how do you configure apollo? Because although I get an default apolloClient, it's still empty instead of populated with my settings from `nuxt.config.ts`. are you using \"@nuxt/vue-apollo\" to create `context.root.$apollo` in the first hand?\n- Awesome will post over, his approach with setup is much better!\n- Although @Austio brought me in the right direction, calling `provide()` inside my `default.vue::setup()` triggered an out of memory error. (I think because it keeps reloading because I'm also query for `loggedInUser` in my `default.vue`) And I also think putting `provide(DefaultApolloClient,..)` inside it's own file and not in `default.vue` is the more correct approach.\n- ah, good to know. Sadly I can't use `nuxt-composition-api`, it always throws an error when I finally build nuxt. to be fair I'm using `nuxt-ts` so it probably isn't made for typescript yet...\n- I stopped using `nuxt-ts` as it's not recommended for production and bloats memory usage, plus I ran into some strange issues..\n- yeah, it has defintily been a hassle. but better than not using typescript... may I asked what else you are using now?\n- I still use `@nuxt/typescript-build` but not the runtime that allows using TS in nuxt.config.\n- ah, gotcha. I will have to look into it. did you have to modify your webpack file to make nuxt work with components in ts? any chance you got a link handy? thx!\n- The Nuxt TypeScript setup works OOTB, simply don't configure the runtime and keep `nuxt.config.js` as JS and components should work fine in TS.\n- Thanks, seems I should have paid more attention to the `optional` while setting it up! I will give it a spin, but I will have to backport my `modules` and `serverMiddleware` to JS before that.","metadata":{"transformedAt":"2026-08-18T18:33:07.891Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":416,"estimatedTokens":2617}}753{"id":"stack-73203265","source":"stackoverflow","questionId":73203265,"title":"Nuxt 3 dynamic page change the Url but it doesn't change the content and fetch data only once","tags":["vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: Nuxt 3 dynamic page change the Url but it doesn't change the content and fetch data only once\nTags: vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI have a `products/index` page and `products/[slug]` in main products page I have a `NuxtLink` to change the page and go to `products/[slug]` and fetch the data for this product.\n\nOn the first click I have a correct data but when I click on back or click on products/index page then try to click on another product, I have the information of the first product I clicked on, and on every product, again I have the information of the first product I clicked on.\n\nUsing `console.log` lead me to find out that my fetch data **DOES NOT CHANGE**, did I miss something here?\n\nUsing `:key` and `:page-key` on `` didn't work.\n\nFirst product I clicked\n\nSecond product and still no changes, data came from first product\n\nThird pic and still no changes\n\n`productComponent.vue`\n\n```\n\n \n \n \n \n \n \n {{ title }}\n\n \n \n قیمت : {{ price }} تومان\n \n \n \n \n \n\nexport default {\n name: 'ProductComponent',\n props: ['title', 'price', 'img', 'alt', 'link'],\n}\n\n```\n\n`products/index.vue` page\n\n```\n\nuseHead({\n title: 'محصولات',\n})\nconst {data, pending, refresh, error} = await useFetch('http://127.0.0.1:8000/api/products')\nconst products=data._value.data.data\n\n \n \n \n \n\n### محصولات\n\n \n \n \n \n \n \n \n \n \n \n \n\n```\n\n`products/[slug]`\n\n```\n\nconst route = useRoute();\nconst {data: productData, pending, refresh, error} = await useFetch(`http://127.0.0.1:8000/api/products/${route.params.slug}`)\nconst product = productData._value.data[0]\nconsole.log(product)\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n نام محصول :\n\n {{ product.name }}\n\n \n \n کشور :\n\n {{ product.country }}\n\n \n \n جنس :\n\n {{ product.material }}\n\n \n \n سن :\n\n {{ product.age }}\n\n \n \n رنگ :\n\n {{ product.color }}\n\n \n \n وزن :\n\n {{ product.weight }}\n\n \n \n طول :\n\n {{ product.length }}\n\n \n \n عرض :\n\n {{ product.width }}\n\n \n \n ارتفاع :\n\n {{ product.height }}\n\n \n \n قیمت :\n\n {{ product.price }}\n\n \n \n \n \n\n \n \n \n توضیحات\n \n \n \n \n \n \n \n برچسب ها : \n {{ tags }} /\n \n \n\nexport default {\n data() {\n return {\n image: null,\n }\n },\n methods: {\n switchImage(index) {\n this.image = index;\n },\n },\n}\n\n```\n\n========================================\n\nTop Answer:\nthis post made my day, really !!\ni was struggling for weeks with request in cache, and by adding dynamic key to my request, it fix everything !\n\nis someone comes over here :\n\n```\nconst { data: story } = await useAsyncData(`articleStory:${slug}` , \n async () => {\n const response = await \n storyblokApi.get(`cdn/stories/articles/${slug}`, {\n version: version,\n resolve_relations: \"post.categories,post.related\",\n });\n return response.data.story || null;\n});\n```\n\ncheers all\n\n========================================\n\nCode:\n```html\n<template>\n <div class=\"mx-auto rounded border mb-7 border-blue-200 pt-1 px-2 mx-1 mb-2\">\n <NuxtLink :to=\"link\">\n <img\n class=\"rounded mx-auto mb-3 border-b border-y-blue-300 pb-3\"\n :src=\"img\"\n :alt=\"alt\"\n />\n <div class=\"mt-2\">\n <div>\n <div class=\"items-center font-bold text-slate-700 leading-snug\">\n <p class=\"pr-3\">{{ title }}</p>\n </div>\n <div class=\"mt-2 text-lg text-slate-600 pr-3 pb-2\">\n قیمت : {{ price }} تومان\n </div>\n </div>\n </div>\n </NuxtLink>\n </div>\n</template>\n\n<script>\nexport default {\n name: 'ProductComponent',\n props: ['title', 'price', 'img', 'alt', 'link'],\n}\n</script>\n```\n\n```html\n<script setup>\nuseHead({\n title: 'محصولات',\n})\nconst {data, pending, refresh, error} = await useFetch('http://127.0.0.1:8000/api/products')\nconst products=data._value.data.data\n</script>\n<template>\n <div>\n <main class=\"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8\">\n <div class=\"relative z-10 flex items-baseline justify-between pt-24 pb-6 border-b mb-7 border-gray-200\">\n <h1 class=\"text-4xl font-extrabold tracking-tight \">محصولات</h1>\n </div>\n <div class=\" border border-blue-300 mx-auto p-4 mb-7\">\n <div class=\"grid sm:grid-cols-2 md:grid-cols-2 gap-2 lg:grid-cols-3 xl:grid-cols-4\">\n <div v-for=\"(product,index) in products\" :key=\"index\">\n <product-component :title=\"product.name\"\n :price=\"product.price\"\n :img=\"'http://127.0.0.1:8000/'+product.image[0].indexArray.large\"\n :alt=\"product.name\"\n :link=\"'/products/'+product.slug\">\n </product-component>\n </div>\n </div>\n </div>\n </main>\n </div>\n</template>\n```\n\n```html\n<script setup>\nconst route = useRoute();\nconst {data: productData, pending, refresh, error} = await useFetch(`http://127.0.0.1:8000/api/products/${route.params.slug}`)\nconst product = productData._value.data[0]\nconsole.log(product)\n</script>\n<template>\n <div class=\"container mx-auto\">\n <section class=\"grid grid-cols-12 gap-3 mb-7 \">\n <!-- little pic-->\n <div class=\"md:col-span-1 mx-auto md:flex md:flex-wrap hidden overflow-auto\" style=\"max-height: 36rem\">\n <div class=\"cursor-pointer bg-amber-100 max-h-9\">\n <div class=\"max-h-fit mb-3 \" v-for=\"(myImage , index) in product.image\" :key=\"index\"\n @click=\"switchImage('http://127.0.0.1:8000/'+myImage.indexArray.large)\">\n <img class=\"object-fill \" style=\"width: 80px;height: 60px\"\n :src=\"'http://127.0.0.1:8000/'+myImage.indexArray.large\"\n :alt=\"myImage.alt\">\n </div>\n </div>\n </div>\n <!-- end of little pic-->\n <!-- pic-->\n <div v-if=\"image\" class=\"md:col-span-6 col-span-12 w-100 w-full max-w-full\">\n <img class=\"\"\n :src=\"image\"\n :alt=\"image.alt\">\n </div>\n <div v-else class=\"md:col-span-6 col-span-12 \">\n <img class=\"object-fill\"\n :src=\"'http://127.0.0.1:8000/'+product.image[0].indexArray.large\"\n alt=\"\">\n </div>\n <!--end of pic-->\n <div class=\"col-span-12 md:hidden\">\n <div class=\"cursor-pointer overflow-x-scroll\">\n <div class=\" mb-3 inline py-1 \" v-for=\"(myImage , index) in product.image\" :key=\"index\" @click=\"switchImage(index)\">\n <img class=\"object-fill inline p-1 overflow-x-scroll\" style=\"width: 80px;height: 60px\"\n :src=\"myImage.url\"\n :alt=\"myImage.alt\">\n </div>\n </div>\n </div>\n <!-- details-->\n <div class=\"col-span-12 md:col-span-4\">\n <div class=\"flex justify-between border-b border-amber-200 p-1 mb-4\">\n <p> نام محصول :</p>\n <p>{{ product.name }}</p>\n </div>\n <div class=\"flex justify-between border-b border-amber-200 p-1 mb-4\">\n <p> کشور :</p>\n <p>{{ product.country }}</p>\n </div>\n <div class=\"flex justify-between border-b border-amber-200 p-1 mb-4\">\n <p> جنس :</p>\n <p>{{ product.material }}</p>\n </div>\n <div class=\"flex justify-between border-b border-amber-200 p-1 mb-4\">\n <p> سن :</p>\n <p>{{ product.age }}</p>\n </div>\n <div class=\"flex justify-between border-b border-amber-200 p-1 mb-4\">\n <p> رنگ :</p>\n <p>{{ product.color }}</p>\n </div>\n <div class=\"flex justify-between border-b border-amber-200 p-1 mb-4\">\n <p> وزن :</p>\n <p>{{ product.weight }}</p>\n </div>\n <div class=\"flex justify-between border-b border-amber-200 p-1 mb-4\">\n <p> طول :</p>\n <p>{{ product.length }}</p>\n </div>\n <div class=\"flex justify-between border-b border-amber-200 p-1 mb-4\">\n <p> عرض :</p>\n <p>{{ product.width }}</p>\n </div>\n <div class=\"flex justify-between border-b border-amber-200 p-1 mb-4\">\n <p> ارتفاع :</p>\n <p>{{ product.height }}</p>\n </div>\n <div class=\"flex justify-between border-b border-amber-200 p-1 mb-4\">\n <p> قیمت :</p>\n <p>{{ product.price }}</p>\n </div>\n </div>\n <!-- end of details-->\n </section>\n\n <div class=\"p-3 mb-7\" style=\"background-color:beige;\">\n <ul class=\"flex flex-row md:space-x-6\">\n <li class=\"block py-2 pr-4 pl-3 text-black\">\n توضیحات\n </li>\n </ul>\n </div>\n <div class=\"mb-5 mx-auto whitespace-normal p-1 border-b border-amber-100-200 \">\n <div v-html=\"product.description\"></div>\n </div>\n <div class=\"mb-7\">\n <span class=\"block mb-4\"> برچسب ها : </span>\n <a v-for=\"(tags , index) in product.tags.split(',')\" :title=\"tags\" :key=\"index\"\n class=\"rounded-md text-sm\" style=\"margin: 3px\" rel=\"tag\"\n href=\"\">{{ tags }} / </a>\n </div>\n </div>\n</template>\n\n\n<script>\nexport default {\n data() {\n return {\n image: null,\n }\n },\n methods: {\n switchImage(index) {\n this.image = index;\n },\n },\n}\n</script>\n```\n\n```text\nproducts/index\n```\n\n```text\nproducts/[slug]\n```\n\n```text\nNuxtLink\n```\n\n```text\nproducts/[slug]\n```\n\n```text\nconsole.log\n```\n\n```text\n:key\n```\n\n```text\n:page-key\n```\n\n```text\n<nuxtPage/>\n```\n\n```text\nproductComponent.vue\n```\n\n```text\nproducts/index.vue\n```\n\n```text\nproducts/[slug]\n```\n\n```html\nconst {data: productData, pending, refresh, error} = await useFetch(`http://127.0.0.1:8000/api/products/${slug}` , { initialCache: false })\n```\n\n```text\ninitialCache : false\n```\n\n```text\nconst { data: story } = await useAsyncData(`articleStory:${slug}` , \n async () => {\n const response = await \n storyblokApi.get(`cdn/stories/articles/${slug}`, {\n version: version,\n resolve_relations: \"post.categories,post.related\",\n });\n return response.data.story || null;\n});\n```\n\n========================================\n\nComments:\n- I'm having the exact same problem. Here is a minimal reproduction: stackblitz.com/edit/…\n- I have formatted your question into something more readable. You have a few errors that can be seen thanks to ESlint (like missing `:key` on your `v-for` loops), consider fixing those at first. Then, checking your Vue devtools and network requests can be a great start.\n- There is another possible way I think. You can run the `refresh()` method when you need to fetch the data again. In some cases, it's help me a lot\n- You can pass a key into useFetch. The advantage over initalCache: false is that data doesn't get fetched more than once. This might help: v3.nuxtjs.org/api/composables/use-fetch#params","metadata":{"transformedAt":"2026-08-18T18:33:07.891Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":493,"estimatedTokens":2642}}754{"id":"stack-74410533","source":"stackoverflow","questionId":74410533,"title":"Nuxt 3 - how to access plugin injections from components?","tags":["vue.js","nuxt.js","nuxt3.js"],"text":"Title: Nuxt 3 - how to access plugin injections from components?\nTags: vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nUsing Nuxt 3 and vue-gtag, what is the right way to access `$gtag` from components?\n\nplugins/gtag.client.js:\n\n```\nimport VueGtag from 'vue-gtag';\n\nexport default defineNuxtPlugin(nuxtApp => {\n const router = useRouter();\n nuxtApp.vueApp.use(\n VueGtag,\n {\n config: {\n id: '...'\n }\n },\n router\n );\n});\n```\n\nIn Nuxt 2, `this.$gtag` was accessible from component file.\n\nIn Nuxt 3, I can't seem to find it:\n\n```\nconst nuxtApp = useNuxtApp();\nnuxtApp.$gtag //undefined\n```\n\nLooking at the source code, it seems to be defined correctly, so I don't think it's a problem with the plugin itself.\n`app.config.globalProperties.$gtag = api;`\n\n========================================\n\nTop Answer:\nFirstly, create a plugin for nuxt3 and save them in `plugins/google-analytics.client.ts`\n\nThen you must use `provide` to add `event`, `pageview`, `screenview`,... like this bellow code.\n\n```\nimport VueGtag, {\n event,\n pageview,\n screenview\n} from \"vue-gtag\";\n\nexport default defineNuxtPlugin((nuxtApp) => {\n const config = useRuntimeConfig()\n\n // @ts-ignore\n nuxtApp.vueApp.use(VueGtag, {\n config: { id: config.public.googleAnalyticId }\n }, nuxtApp.$router);\n\n return {\n provide: {\n gtag: {\n event,\n pageview,\n screenview\n }\n }\n }\n});\n```\n\nNow, you can use `$gtag` as normal in your components.\n\n```\n....\nasync function handleSubmit(valid: any, { email, password }) {\n const { $gtag } = useNuxtApp()\n console.log('$gtag: ', $gtag)\n $gtag.event('login', {\n method: 'Local'\n })\n ....\n....\n```\n\n========================================\n\nCode:\n```text\nimport VueGtag from 'vue-gtag';\n\nexport default defineNuxtPlugin(nuxtApp => {\n const router = useRouter();\n nuxtApp.vueApp.use(\n VueGtag,\n {\n config: {\n id: '...'\n }\n },\n router\n );\n});\n```\n\n```text\nconst nuxtApp = useNuxtApp();\nnuxtApp.$gtag //undefined\n```\n\n```text\n$gtag\n```\n\n```text\nthis.$gtag\n```\n\n```text\napp.config.globalProperties.$gtag = api;\n```\n\n```text\nimport domtoimage from \"dom-to-image-more\";\nexport default defineNuxtPlugin((nuxtApp) => {\n // nuxtApp.vueApp.use(domtoimage)\n return {\n provide: {\n domtoimage\n }\n }\n})\n```\n\n```text\nconst print = () => {\n console.log(\"Print ...\")\n const { $domtoimage } = useNuxtApp()\n $domtoimage.toPng(printMeDiv)\n .then((dataUrl) => {\n console.log(dataUrl)\n })\n }\n}\n```\n\n```text\nimport VueGtag, {\n event,\n pageview,\n screenview\n} from \"vue-gtag\";\n\nexport default defineNuxtPlugin((nuxtApp) => {\n const config = useRuntimeConfig()\n\n // @ts-ignore\n nuxtApp.vueApp.use(VueGtag, {\n config: { id: config.public.googleAnalyticId }\n }, nuxtApp.$router);\n\n return {\n provide: {\n gtag: {\n event,\n pageview,\n screenview\n }\n }\n }\n});\n```\n\n```text\n....\nasync function handleSubmit(valid: any, { email, password }) {\n const { $gtag } = useNuxtApp()\n console.log('$gtag: ', $gtag)\n $gtag.event('login', {\n method: 'Local'\n })\n ....\n....\n```\n\n```text\nplugins/google-analytics.client.ts\n```\n\n```text\nprovide\n```\n\n```text\nevent\n```\n\n```text\npageview\n```\n\n```text\nscreenview\n```\n\n```text\n$gtag\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.891Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":209,"estimatedTokens":824}}755{"id":"stack-60328704","source":"stackoverflow","questionId":60328704,"title":"How to include a link inside nuxt-i18n text","tags":["localization","vue-component","nuxt.js","vue-i18n","nuxt-i18n"],"text":"Title: How to include a link inside nuxt-i18n text\nTags: localization, vue-component, nuxt.js, vue-i18n, nuxt-i18n\nSource: Stack Overflow\n\nQuestion:\nIm trying to use nuxt-I18n module for localization.\nI have installed `\"nuxt-i18n\": \"^6.4.1\"`\n\nAlso in my nuxt.config.js i have the fallowing \n\n```\nmodules: [\n [\n 'nuxt-i18n',\n {\n defaultLocale: 'en',\n lazy: true,\n langDir: 'locales/',\n locales: [\n {\n code: 'mk',\n name: 'Македонски',\n file: 'mk.js',\n },\n {\n code: 'en',\n name: 'English',\n file: 'en.js',\n },\n ],\n },\n ],\n ],\n```\n\nI also created folder **locale** where i have my 2 files where i write my localization. Mostly of the text in my project is simple so I was doing fine with this setup. However i end up on a problem.\nI have a text paragraph with a link inside that goes something like this:\n\n```\nLorem ipsum This is link dolor sit amet. \n\n```\n\nI was trying to solve this with component that comes of i18n but i had a lot of errors with it.\n\nCan anyone give me an example how to solve this ?\n\n========================================\n\nCode:\n```js\nmodules: [\n [\n 'nuxt-i18n',\n {\n defaultLocale: 'en',\n lazy: true,\n langDir: 'locales/',\n locales: [\n {\n code: 'mk',\n name: 'Македонски',\n file: 'mk.js',\n },\n {\n code: 'en',\n name: 'English',\n file: 'en.js',\n },\n ],\n },\n ],\n ],\n```\n\n```html\n<p>Lorem ipsum <a href=\"#\"> This is link </a> dolor sit amet. </p>\n```\n\n```text\n\"nuxt-i18n\": \"^6.4.1\"\n```\n\n```text\n<i18n path=\"text\" tag=\"p\">\n <template v-slot:link>\n <a>{{ $t('link') }}</a>\n </template>\n </i18n\n```\n\n```text\nen: {\n text: 'You can check {link} for more details.',\n link: 'component interpolation',\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.891Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":96,"estimatedTokens":496}}756{"id":"stack-67393513","source":"stackoverflow","questionId":67393513,"title":"How to use $axios Nuxt module inside of setup() from composition API?","tags":["javascript","vuejs2","nuxt.js","vue-composition-api"],"text":"Title: How to use $axios Nuxt module inside of setup() from composition API?\nTags: javascript, vuejs2, nuxt.js, vue-composition-api\nSource: Stack Overflow\n\nQuestion:\nThe docs say to use `this.$axios.$get()` inside of `methods/mounted/etc`, but that throws `TypeError: _this is undefined` when called inside of `setup()`. Is `$axios` compatible with the composition API?\n\nTo clarify, I'm specifically talking about the axios nuxt plugin, not just using axios generically. https://axios.nuxtjs.org/\n\nSo for instance, something like this throws the error above\n\n```\nexport default {\n setup: () => {\n const data = this.$axios.$get(\"/my-url\");\n }\n}\n```\n\n========================================\n\nTop Answer:\nAlright, so with the usual configuration of a Nuxt plugin aka\n`plugins/vue-composition.js`\n\n```\nimport Vue from 'vue'\nimport VueCompositionApi from '@vue/composition-api'\n\nVue.use(VueCompositionApi)\n```\n\n`nuxt.config.js`\n\n```\nplugins: ['~/plugins/vue-composition']\n```\n\nYou can then proceed with a test page and run this kind of code to have a successful axios get\n\n```\n\nimport axios from 'axios'\nimport { onMounted } from '@vue/composition-api'\n\nexport default {\n name: 'App',\n setup() {\n onMounted(async () => {\n const res = await axios.get('https://jsonplaceholder.typicode.com/posts/1')\n console.log(res)\n })\n },\n}\n\n```\n\nI'm not sure about how to import axios globally in this case but since it's composition API, you do not use the options API keys (`mounted` etc...).\n\nThanks to this post for the insight on how to use Vue3: https://stackoverflow.com/a/65015450/8816585\n\n========================================\n\nCode:\n```text\nexport default {\n setup: () => {\n const data = this.$axios.$get(\"/my-url\");\n }\n}\n```\n\n```text\nthis.$axios.$get()\n```\n\n```text\nmethods/mounted/etc\n```\n\n```text\nTypeError: _this is undefined\n```\n\n```text\nsetup()\n```\n\n```text\n$axios\n```\n\n```text\nimport { useContext } from '@nuxtjs/composition-api';\n\nsetup() {\n const { $axios } = useContext();\n}\n```\n\n```js\nimport Vue from 'vue'\nimport VueCompositionApi from '@vue/composition-api'\n\nVue.use(VueCompositionApi)\n```\n\n```js\nplugins: ['~/plugins/vue-composition']\n```\n\n```js\n<script>\nimport axios from 'axios'\nimport { onMounted } from '@vue/composition-api'\n\nexport default {\n name: 'App',\n setup() {\n onMounted(async () => {\n const res = await axios.get('https://jsonplaceholder.typicode.com/posts/1')\n console.log(res)\n })\n },\n}\n</script>\n```\n\n```text\nplugins/vue-composition.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nmounted\n```\n\n========================================\n\nComments:\n- I should have been more clear. I'm referring to the nuxt plugin specifically: axios.nuxtjs.org. I already have composition api working. The issue is that I cannot call this.$axios per the plugin docs axios.nuxtjs.org\n- Ahhh, I'd forgotten about useContext(). I'll give this a try tomorrow.","metadata":{"transformedAt":"2026-08-18T18:33:07.891Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":145,"estimatedTokens":721}}757{"id":"stack-63535913","source":"stackoverflow","questionId":63535913,"title":"how can i install bootstrap on nuxtjs","tags":["bootstrap-4","nuxt.js"],"text":"Title: how can i install bootstrap on nuxtjs\nTags: bootstrap-4, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to use Bootstrap in nuxt.js, how can I do this without using CDN? I want to use bootstrap files in the nuxt.config.js, but I can't, also I want to use jquery files and popper.js\nI tried to include those files on head array on the `nuxt.config.js` but it's doesn't work, and also I tried to include `bootstrap.min.css` on CSS array and fortunately it worked, but js property of bootstrap like Dropdown, Collapses and stuff like that didn't work, I know the reason why those properties don't work, its because Jquery and popper js didn't include, but really how can i include them?\nplease help me\n\n========================================\n\nTop Answer:\nhere is a way I found to install bootstrap in Nuxt Js\nfirstly, you need to install the sass and sass loader packages by using\n\n```\nnpm install --save-dev sass sass-loader@10 fibers\n```\n\nSecondly, you install bootstrap using npm\n\n```\nnpm install bootstrap@next\n```\n\nthirdly, go into your assets folder create a folder named scss, and inside the scss folder create an app.scss or any name you wish\nfourthly, you import bootstrap from your node modules by using the @import that is\n\n```\n@import \"~bootstrap/scss/bootstrap\";\n```\n\nfifthly, you go to the nuxt.config.js and you add your scss file you created by using,\n\n```\n{ src: '~/assets/scss/app.scss', lang: 'scss' },\n```\n\nhere is the link for a project I did from github bootstrap-nuxt\n\n========================================\n\nCode:\n```text\nnuxt.config.js\n```\n\n```text\nbootstrap.min.css\n```\n\n```text\nexport default {\n head: {\n script: [\n {\n src: '/jquery-3.5.1.slim.min.js'\n },\n {\n src: '/popper.min.js'\n },\n {\n src: '/bootstrap.min.js'\n }\n ],\n link: [\n {\n rel: 'stylesheet',\n href: '/bootstrap.min.css'\n }\n ]\n }\n}\n```\n\n```text\nnpm install bootstrap-vue\n```\n\n```text\nmodule.exports = { modules: ['bootstrap-vue/nuxt'] }\n```\n\n```text\nnpm install --save-dev sass sass-loader@10 fibers\n```\n\n```text\nnpm install bootstrap@next\n```\n\n```text\n@import \"~bootstrap/scss/bootstrap\";\n```\n\n```text\n{ src: '~/assets/scss/app.scss', lang: 'scss' },\n```\n\n========================================\n\nComments:\n- please add some code, so its easier to find possible mistakes.\n- thanks for your answer, but I don't want using of bootstrap-vue because its doesn't support of RTL, and it's hard to change config for RTL support\n- thanks for the answer, I knew how to use of CDN, but I don't want use of it for some reasons, I want use manual files, and I include bootstrap.min.css in CSS array on nuxt.config.js its work, but I don't know how can I include js files , which needs for working pure bootstrap like jquery and popper.js, which usually used for DropDown and Copllapse\n- @MohammadAli Just add them in `static` folder and change src as my edit in answer.\n- Here is how to accept answer: stackoverflow.com/help/….","metadata":{"transformedAt":"2026-08-18T18:33:07.891Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":107,"estimatedTokens":753}}758{"id":"stack-67827277","source":"stackoverflow","questionId":67827277,"title":"Unable to build Nuxt due to a problem with PostCSS when using Bulma and Buefy (nuxt-buefy)","tags":["nuxt.js","tailwind-css","bulma","postcss","buefy"],"text":"Title: Unable to build Nuxt due to a problem with PostCSS when using Bulma and Buefy (nuxt-buefy)\nTags: nuxt.js, tailwind-css, bulma, postcss, buefy\nSource: Stack Overflow\n\nQuestion:\nUsing the following config, everything was working fine via `npm run dev`, but when we did `npm run build`, there was an error:\n\nERROR in ./assets/scss/main.scss (./node_modules/@nuxt/postcss8/node_modules/css-loader/dist/cjs.js??ref--7-oneOf-1-1!./node_modules/@nuxt/postcss8/node_modules/postcss-loader/dist/cjs.js??ref--7-oneOf-1-2!./node_modules/sass-loader/dist/cjs.js??ref--7-oneOf-1-3!./assets/scss/main.scss) Module build failed (from ./node_modules/@nuxt/postcss8/node_modules/postcss-loader/dist/cjs.js): ParserError: Syntax Error at line: 1, column 23\n\n**nuxt.config.js**\n\n```\nexport default {\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: 'app-name',\n htmlAttrs: {\n lang: 'en'\n },\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: '' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },\n { rel: 'stylesheet', type: 'text/css', href: 'https://unpkg.com/open-sans-all/css/open-sans.min.css' },\n ]\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\n '@/assets/scss/main.scss',\n ],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [\n { src: '~/plugins/vee-validate.js', ssr: true },\n ],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n // https://go.nuxtjs.dev/tailwindcss\n '@nuxtjs/tailwindcss',\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\n ['nuxt-buefy', { css: false }]\n ],\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {\n transpile: ['vee-validate'],\n }\n}\n```\n\n**assets/scss/main.scss**\n\n```\n// bulma/buefy overrides\n$family-sans-serif: \"Open Sans\", \"Arial\", sans-serif !important;\n\n$input-border-color: white;\n$input-shadow: none;\n$input-radius: 0px;\n\n// Import bulma styles\n@import \"~bulma\";\n\n// Import buefy styles\n@import \"~buefy/src/scss/buefy\";\n```\n\n**package.json**\n\n```\n\"dependencies\": {\n \"core-js\": \"^3.9.1\",\n \"nuxt\": \"^2.15.3\",\n \"nuxt-buefy\": \"^0.4.7\",\n \"vee-validate\": \"^3.4.7\",\n \"vue-clickaway\": \"^2.2.2\"\n },\n \"devDependencies\": {\n \"@nuxtjs/tailwindcss\": \"^4.0.1\",\n \"fibers\": \"^5.0.0\",\n \"postcss\": \"^8.2.8\",\n \"sass\": \"^1.34.0\",\n \"sass-loader\": \"^10.2.0\"\n }\n```\n\nWe traced the build error to `@import \"~buefy/src/scss/buefy\";` in **main.scss**. The project build successfully with that commented out.\n\nFurther analysis lead to this code in `node_modules/buefy/buefy.css`:\n\n```\n.columns.is-variable {\n --columnGap: 0.75rem;\n margin-left: calc(-1 * var(--columnGap));\n margin-right: calc(-1 * var(--columnGap));\n}\n```\n\nCommenting out that code allowed the build to succeed.\n\nAlso changing it from multiplying `-1` to `1` allowed it to succeed.\n\n========================================\n\nCode:\n```text\nexport default {\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: 'app-name',\n htmlAttrs: {\n lang: 'en'\n },\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: '' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },\n { rel: 'stylesheet', type: 'text/css', href: 'https://unpkg.com/open-sans-all/css/open-sans.min.css' },\n ]\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\n '@/assets/scss/main.scss',\n ],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [\n { src: '~/plugins/vee-validate.js', ssr: true },\n ],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n // https://go.nuxtjs.dev/tailwindcss\n '@nuxtjs/tailwindcss',\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\n ['nuxt-buefy', { css: false }]\n ],\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {\n transpile: ['vee-validate'],\n }\n}\n```\n\n```text\n// bulma/buefy overrides\n$family-sans-serif: \"Open Sans\", \"Arial\", sans-serif !important;\n\n$input-border-color: white;\n$input-shadow: none;\n$input-radius: 0px;\n\n// Import bulma styles\n@import \"~bulma\";\n\n// Import buefy styles\n@import \"~buefy/src/scss/buefy\";\n```\n\n```text\n\"dependencies\": {\n \"core-js\": \"^3.9.1\",\n \"nuxt\": \"^2.15.3\",\n \"nuxt-buefy\": \"^0.4.7\",\n \"vee-validate\": \"^3.4.7\",\n \"vue-clickaway\": \"^2.2.2\"\n },\n \"devDependencies\": {\n \"@nuxtjs/tailwindcss\": \"^4.0.1\",\n \"fibers\": \"^5.0.0\",\n \"postcss\": \"^8.2.8\",\n \"sass\": \"^1.34.0\",\n \"sass-loader\": \"^10.2.0\"\n }\n```\n\n```text\n.columns.is-variable {\n --columnGap: 0.75rem;\n margin-left: calc(-1 * var(--columnGap));\n margin-right: calc(-1 * var(--columnGap));\n}\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run build\n```\n\n```text\n@import \"~buefy/src/scss/buefy\";\n```\n\n```text\nnode_modules/buefy/buefy.css\n```\n\n```text\n-1\n```\n\n```text\n1\n```\n\n```text\nbuild: {\n transpile: ['vee-validate'],\n postcss: {\n plugins: {\n \"postcss-custom-properties\": false\n },\n },\n }\n```\n\n```text\n// bulma/buefy overrides\n$family-sans-serif: \"Open Sans\", \"Arial\", sans-serif !important;\n\n$input-border-color: white;\n$input-shadow: none;\n$input-radius: 0px;\n\n$variable-columns: false;\n\n// Import bulma styles\n@import \"~bulma\";\n\n// Import buefy styles\n@import \"~buefy/src/scss/buefy\";\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nmain.scss\n```\n\n========================================\n\nComments:\n- I spent an hour trying to figure this out. This should be marked as the correct answer!\n- I spent nearly 2 hours, this guided me in the right direction but I also needed to disable it in preset-env: ``` build: { postcss: { plugins: { \"postcss-custom-properties\": false, 'postcss-preset-env': { features: { 'custom-properties': false } } } } }```","metadata":{"transformedAt":"2026-08-18T18:33:07.891Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":271,"estimatedTokens":1552}}759{"id":"stack-58632158","source":"stackoverflow","questionId":58632158,"title":"How can I remove first loading circle div (id=\"nuxt-loading\") in Nuxt.js?","tags":["nuxt.js"],"text":"Title: How can I remove first loading circle div (id=\"nuxt-loading\") in Nuxt.js?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI copied some files from here: https://codesandbox.io/s/github/nuxt/nuxt.js/tree/dev/examples/custom-loading?from-embed\n\n- pages/about.vue\n\n- pages/index.vue\n\n- components/loading.vue\n\nAnd setted nuxt.config.js. See below.\n\n**project/components/loading.vue**\n\n```\n\n \n asdasdasd...\n\n \n\n export default {\n data: () => ({\n loading: false\n }),\n methods: {\n start () {\n this.loading = true\n },\n finish () {\n this.loading = false\n }\n }\n }\n\n```\n\n**project/nuxt.config.js**\n\n```\n{\n // ...\n loading: '~/components/loading',\n // ...\n}\n```\n\nNext step, I setted setTimeout ms from 1000 to 60000 for test. I got another loading page on first load, not **components/loading.vue**. The second and the other loading was good, but not the first.\n\nI saw after F12 and I found it in project.\n**project/.nuxt/loading.html**\n\n```\n\n#nuxt-loading {\n visibility: hidden;\n opacity: 0;\n position: absolute;\n left: 0;\n right: 0;\n top: 0;\n bottom: 0;\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n animation: nuxtLoadingIn 10s ease;\n -webkit-animation: nuxtLoadingIn 10s ease;\n animation-fill-mode: forwards;\n overflow: hidden;\n}\n\n@keyframes nuxtLoadingIn {\n 0% {\n visibility: hidden;\n opacity: 0;\n }\n 20% {\n visibility: visible;\n opacity: 0;\n }\n 100% {\n visibility: visible;\n opacity: 1;\n }\n}\n\n@-webkit-keyframes nuxtLoadingIn {\n 0% {\n visibility: hidden;\n opacity: 0;\n }\n 20% {\n visibility: visible;\n opacity: 0;\n }\n 100% {\n visibility: visible;\n opacity: 1;\n }\n}\n\n#nuxt-loading>div,\n#nuxt-loading>div:after {\n border-radius: 50%;\n width: 5rem;\n height: 5rem;\n}\n\n#nuxt-loading>div {\n font-size: 10px;\n position: relative;\n text-indent: -9999em;\n border: .5rem solid #F5F5F5;\n border-left: .5rem solid #D3D3D3;\n -webkit-transform: translateZ(0);\n -ms-transform: translateZ(0);\n transform: translateZ(0);\n -webkit-animation: nuxtLoading 1.1s infinite linear;\n animation: nuxtLoading 1.1s infinite linear;\n}\n\n#nuxt-loading.error>div {\n border-left: .5rem solid #ff4500;\n animation-duration: 5s;\n}\n\n@-webkit-keyframes nuxtLoading {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n@keyframes nuxtLoading {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\nwindow.addEventListener('error', function () {\n var e = document.getElementById('nuxt-loading');\n if (e) {\n e.className += ' error';\n }\n});\n\nLoading...\n\n```\n\nSo my question. How can I disable it?\n\n========================================\n\nCode:\n```html\n<template>\n <div v-if=\"loading\" id=\"loader\">\n <p>asdasdasd...</p>\n </div>\n</template>\n\n<script>\n export default {\n data: () => ({\n loading: false\n }),\n methods: {\n start () {\n this.loading = true\n },\n finish () {\n this.loading = false\n }\n }\n }\n</script>\n```\n\n```js\n{\n // ...\n loading: '~/components/loading',\n // ...\n}\n```\n\n```html\n<style>\n#nuxt-loading {\n visibility: hidden;\n opacity: 0;\n position: absolute;\n left: 0;\n right: 0;\n top: 0;\n bottom: 0;\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n animation: nuxtLoadingIn 10s ease;\n -webkit-animation: nuxtLoadingIn 10s ease;\n animation-fill-mode: forwards;\n overflow: hidden;\n}\n\n@keyframes nuxtLoadingIn {\n 0% {\n visibility: hidden;\n opacity: 0;\n }\n 20% {\n visibility: visible;\n opacity: 0;\n }\n 100% {\n visibility: visible;\n opacity: 1;\n }\n}\n\n@-webkit-keyframes nuxtLoadingIn {\n 0% {\n visibility: hidden;\n opacity: 0;\n }\n 20% {\n visibility: visible;\n opacity: 0;\n }\n 100% {\n visibility: visible;\n opacity: 1;\n }\n}\n\n#nuxt-loading>div,\n#nuxt-loading>div:after {\n border-radius: 50%;\n width: 5rem;\n height: 5rem;\n}\n\n#nuxt-loading>div {\n font-size: 10px;\n position: relative;\n text-indent: -9999em;\n border: .5rem solid #F5F5F5;\n border-left: .5rem solid #D3D3D3;\n -webkit-transform: translateZ(0);\n -ms-transform: translateZ(0);\n transform: translateZ(0);\n -webkit-animation: nuxtLoading 1.1s infinite linear;\n animation: nuxtLoading 1.1s infinite linear;\n}\n\n#nuxt-loading.error>div {\n border-left: .5rem solid #ff4500;\n animation-duration: 5s;\n}\n\n@-webkit-keyframes nuxtLoading {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n@keyframes nuxtLoading {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n</style>\n\n<script>\nwindow.addEventListener('error', function () {\n var e = document.getElementById('nuxt-loading');\n if (e) {\n e.className += ' error';\n }\n});\n</script>\n\n<div id=\"nuxt-loading\" aria-live=\"polite\" role=\"status\"><div>Loading...</div></div>\n\n<!-- https://projects.lukehaas.me/css-loaders -->\n```\n\n```js\n// nuxt.config.js\nloadingIndicator: {\n name: 'circle',\n color: '#3B8070',\n background: 'white'\n}\n```\n\n```js\n// nuxt.config.js\nloadingIndicator: '~/loading.html'\n```\n\n```text\nloadingIndicator\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nloadingIndicator\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.891Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":337,"estimatedTokens":1365}}760{"id":"stack-52209553","source":"stackoverflow","questionId":52209553,"title":"How can I get started with integrating AWS Amplify to a Nuxt.js project?","tags":["nuxt.js","aws-amplify"],"text":"Title: How can I get started with integrating AWS Amplify to a Nuxt.js project?\nTags: nuxt.js, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nIm recently started working with vue and nuxt. I want to add an AWS backend to my project. I've seen that Amplify is useful but haven't been able to find any resources on how to implement it in nuxt. Any advice?\n\n========================================\n\nTop Answer:\nThis is my setup:\n\n1/ `plugins/amplify.client.js` -> this name makes it execute on client side\n\n```\nimport Vue from 'vue'\nimport Amplify, * as AmplifyModules from 'aws-amplify'\nimport { AmplifyPlugin } from 'aws-amplify-vue'\nimport awsmobile from '~/aws-exports'\nAmplify.configure(awsmobile)\n\nVue.use(AmplifyPlugin, AmplifyModules)\n\n// Make Amplify available in store and Vue instances\nexport default (_, inject) => {\n inject('Amplify', AmplifyModules)\n}\n```\n\n2/ `nuxt.config.js`\n\n```\nplugins: ['@/plugins/amplify.client.js'],\n```\n\nIt let me use commands such as `this.$Amplify.Hub` or `store.$Amplify` so I have access to the main functions anywhere.\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\nimport Amplify, * as AmplifyModules from 'aws-amplify'\nimport { AmplifyPlugin, components } from 'aws-amplify-vue'\nimport aws_exports from '@/aws-exports'\nAmplify.configure(aws_exports)\n\nVue.use(AmplifyPlugin, AmplifyModules)\n\n//register components individually for further use\n// Do not import in .vue files\nVue.component('sign-in', components.SignIn)\n```\n\n```text\nplugins: [\n {\n src: '~plugins/amplify.js',\n ssr: false\n }\n]\n```\n\n```js\nimport Vue from 'vue'\nimport Amplify, * as AmplifyModules from 'aws-amplify'\nimport { AmplifyPlugin } from 'aws-amplify-vue'\nimport awsmobile from '~/aws-exports'\nAmplify.configure(awsmobile)\n\nVue.use(AmplifyPlugin, AmplifyModules)\n\n// Make Amplify available in store and Vue instances\nexport default (_, inject) => {\n inject('Amplify', AmplifyModules)\n}\n```\n\n```js\nplugins: ['@/plugins/amplify.client.js'],\n```\n\n```text\nplugins/amplify.client.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nthis.$Amplify.Hub\n```\n\n```text\nstore.$Amplify\n```\n\n========================================\n\nComments:\n- Can you show much how much have you implemented ? What's the difficulty?\n- @gnomeria I was asking because I wasn't sure if I should use it. I was deciding if I should use that or the serverless framework. Since then I've decided to use sls since I think it better fits my needs.\n- I wrote a tutorial about it for SSR Nuxt.js kodius.com/blog/nuxt-ssr-on-amplify. Hehe in first version I missed documenting this 2 steps you showed :)\n- `Vue.prototype.$Amplify = AmplifyModules;` works for me if you just want to use Amplify in this.$Amplify","metadata":{"transformedAt":"2026-08-18T18:33:07.891Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":105,"estimatedTokens":682}}761{"id":"stack-60997912","source":"stackoverflow","questionId":60997912,"title":"Nuxt $vuetify.theme.dark reset when i change page","tags":["vue.js","vuetify.js","nuxt.js"],"text":"Title: Nuxt $vuetify.theme.dark reset when i change page\nTags: vue.js, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using **Nuxt.js v2.12.2 with Vuetify**.\nI installed Vuetify during the initial configuration of the new project.\n\nI want to build a static website with some functionality like **change the theme from dark to light**.\n\nSo I added a switch in my default layout to change this property: $vuetify.theme.dark\n\nHere's my code for the switch: \n\n```\n\n```\n\nI even tried in this way but is the same:\n\n```\n\n```\n\nWhen I click on the switch the property change correcly.\nBut if I change page or I reload, it goes back to his previous value.\n\nHow do I change this property so that it stays that way for the session?\nDo I need to save it somewhere?\n\nHere's the code inside nuxt.config.js:\n\n```\nvuetify: {\ncustomVariables: ['~/assets/variables.scss'],\ntheme: {\n themes: {\n dark: {\n primary: colors.blue.darken2,\n accent: colors.grey.darken3,\n secondary: colors.amber.darken3,\n info: colors.teal.lighten1,\n warning: colors.amber.base,\n error: colors.deepOrange.accent4,\n success: colors.green.accent3\n },\n light: {\n primary: '#3f51b5',\n secondary: '#b0bec5',\n accent: '#8c9eff',\n error: '#b71c1c',\n },\n }\n}\n```\n\nThanks for the help.\n\n========================================\n\nTop Answer:\nFirst of all in Vuetify config file you need to add this property:\n\n```\ndark: true/false\n```\n\nthe configuration should now look like this:\n\r\n\r\n\n```\ntheme: {\r\n dark: true,\r\n themes: {\r\n dark: {\r\n primary: colors.blue.darken2,\r\n accent: colors.grey.darken3,\r\n secondary: colors.amber.darken3,\r\n background: '#34358e'\r\n },\r\n light: {\r\n primary: '#3f51b5',\r\n secondary: '#b0bec5',\r\n accent: '#8c9eff',\r\n error: '#b71c1c',\r\n }\r\n }\r\n}\n```\n\n\r\n\r\n\r\n\nThen in your Layout in the v-app component you have to bind a method \n\nit look like this:\n\n\r\n\r\n\n```\n\r\n \r\n \r\n \r\n\n```\n\n\r\n\r\n\r\n\nand in your script tag add goDark in data and setTheme as a computed property.\n\n\r\n\r\n\n```\n\r\nexport default {\r\n data: () => ({\r\n goDark: false,\r\n }),\r\n computed: {\r\n setTheme() {\r\n if (this.goDark === true) {\r\n return (this.$vuetify.theme.dark = true);\r\n } else {\r\n return (this.$vuetify.theme.dark = false);\r\n }\r\n }\r\n }\r\n};\r\n\n```\n\n\r\n\r\n\r\n\nIt should work now.\n\n========================================\n\nCode:\n```text\n<v-switch v-model=\"$vuetify.theme.dark\" />\n```\n\n```text\n<v-switch @click=\"$vuetify.theme.dark = !$vuetify.theme.dark\" />\n```\n\n```text\nvuetify: {\ncustomVariables: ['~/assets/variables.scss'],\ntheme: {\n themes: {\n dark: {\n primary: colors.blue.darken2,\n accent: colors.grey.darken3,\n secondary: colors.amber.darken3,\n info: colors.teal.lighten1,\n warning: colors.amber.base,\n error: colors.deepOrange.accent4,\n success: colors.green.accent3\n },\n light: {\n primary: '#3f51b5',\n secondary: '#b0bec5',\n accent: '#8c9eff',\n error: '#b71c1c',\n },\n }\n}\n```\n\n```text\ngoDark\n```\n\n```text\ngoDark\n```\n\n```text\nonMounted\n```\n\n```text\nlocalStorage.getItem('[your key for dark property]')\n```\n\n```text\ndark: true/false\n```\n\n```js\ntheme: {\n dark: true,\n themes: {\n dark: {\n primary: colors.blue.darken2,\n accent: colors.grey.darken3,\n secondary: colors.amber.darken3,\n background: '#34358e'\n },\n light: {\n primary: '#3f51b5',\n secondary: '#b0bec5',\n accent: '#8c9eff',\n error: '#b71c1c',\n }\n }\n}\n```\n\n```html\n<v-app :dark=\"setTheme\">\n <v-container>\n <v-switch v-model=\"goDark\"></v-switch>\n </v-container>\n</v-app>\n```\n\n```js\n<script>\nexport default {\n data: () => ({\n goDark: false,\n }),\n computed: {\n setTheme() {\n if (this.goDark === true) {\n return (this.$vuetify.theme.dark = true);\n } else {\n return (this.$vuetify.theme.dark = false);\n }\n }\n }\n};\n</script>\n```\n\n```text\n<template>\n <div>\n <v-btn\n class=\"px-1\"\n min-width=\"0px\"\n icon\n :color=\"$vuetify.theme.dark ? 'yellow' : 'indigo'\"\n @click=\"switchTheme()\"\n >\n <v-icon>mdi-theme-light-dark</v-icon>\n </v-btn>\n </div>\n</template>\n```\n\n```text\n<script>\nexport default {\n mounted() {\n this.$vuetify.theme.dark = this.$store.state.darkMode\n },\n methods: {\n switchTheme() {\n this.$store.commit('SWITCH_DARK')\n this.$vuetify.theme.dark = this.$store.state.darkMode\n },\n }\n}\n</script>\n```\n\n```text\nexport const state = () => ({\n darkMode: false,\n})\n\nexport const mutations = {\n SWITCH_DARK(state) {\n state.darkMode = !state.darkMode\n },\n}\n```\n\n```text\nnpm install --save vuex-persist\n```\n\n```text\nlayouts/default.vue\n```\n\n```text\nstore/index.js\n```\n\n```text\nmounted() {\n setTimeout(() => {\n this.$vuetify.theme.dark = localStorage.getItem('dark') === 'true'\n }, 200)\n}\n```\n\n```text\ncomputed: {\n mode: {\n set(theme) {\n this.$vuetify.theme.dark = theme === 'dark'\n localStorage.setItem('dark', theme === 'dark')\n },\n get() {\n return this.$vuetify.theme.dark ? 'dark' : 'light'\n }\n }\n }\n```\n\n========================================\n\nComments:\n- Unfortunately, even in this way, the theme becomes light when I change or reload the page\n- Can you create a demo link from the problem? @L.Gangemi","metadata":{"transformedAt":"2026-08-18T18:33:07.891Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":329,"estimatedTokens":1296}}762{"id":"stack-72329540","source":"stackoverflow","questionId":72329540,"title":"Nuxt 3 Routing : \"Simple\" dynamic route return 404 error","tags":["vue.js","nuxt.js","vuejs3","vue-router","vue-router4"],"text":"Title: Nuxt 3 Routing : \"Simple\" dynamic route return 404 error\nTags: vue.js, nuxt.js, vuejs3, vue-router, vue-router4\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a simple dynamic link with nuxt3 (\"3.0.0-rc.3\") and I cannot reach dynamic slug url. I followed this page but it doesn't seem to work for me :\nhttps://nuxtjs.org/examples/routing/dynamic-pages\n\nHere is my simple page structure :\n\n```\npages/\n index.vue\n category/\n _id.vue\n```\n\nWhen I try to reach my `localhost:3000/category/test` I have the 404 error page with the message \"Page not found: /category/test\".\n\nHere is the link in my \"index.vue\" file :\n\n```\nTest\n```\n\nHere is the content of my \"_id.vue\" file :\n\n```\n\n \n \n\n### Project: {{ $route }}\n\n \n\nexport default {}\n\n```\n\n========================================\n\nCode:\n```text\npages/\n index.vue\n category/\n _id.vue\n```\n\n```text\n<NuxtLink to=\"/category/test\">Test</NuxtLink>\n```\n\n```text\n<template>\n <div>\n <h1>Project: {{ $route }}</h1>\n </div>\n</template>\n\n<script>\nexport default {}\n</script>\n\n<style>\n</style>\n```\n\n```text\nlocalhost:3000/category/test\n```\n\n```text\npages/\n index.vue\n category/\n [id].vue\n```\n\n```text\n[id]\n```\n\n```text\n_id\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.892Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":87,"estimatedTokens":299}}763{"id":"stack-62371594","source":"stackoverflow","questionId":62371594,"title":"[Vue warn]: Error in beforeCreate hook: \"ReferenceError: document is not defined\"","tags":["javascript","vue.js","nuxt.js","document"],"text":"Title: [Vue warn]: Error in beforeCreate hook: \"ReferenceError: document is not defined\"\nTags: javascript, vue.js, nuxt.js, document\nSource: Stack Overflow\n\nQuestion:\nThis might be a long shot, but I cannot figure out what is going wrong. Hopefully somebody can give me some directions.\n\nI am using the vue quick edit plugin : https://github.com/A1rPun/vue-quick-edit in my Nuxt project.\n\nSometimes I will get the error popped up: \n\n [Vue warn]: Error in beforeCreate hook: \"ReferenceError: document is\n not defined\"\n\nThis seems to happen only the first time I load in the page (unconfirmed!), and afterwards it never happens again (using ctrl+F5, loading in incognito, trying in another browser, ...), it just never shows again and the library works perfectly. \n\nHowever, it got me hesitating on using the library, since i'm unsure where the error is coming from and if it might impact my end users.\n\nThis is the component i created for using the inline editable field:\n\n```\n\n \n\nimport QuickEdit from 'vue-quick-edit'\n\nexport default {\n components: { QuickEdit },\n props: {\n label: {\n type: String,\n required: true,\n },\n },\n methods: {\n updateValue (event) {\n // do something\n },\n },\n}\n\n```\n\n========================================\n\nTop Answer:\nThis is because *Nuxt* render page in server side for first time, so `document` is really not defined in server.\n\nYou could define your plugins in `nuxt.config.js` to and tell nuxt to use it only in client:\n\nIn `nuxt.config.js`:\n\n```\n...\nplugins: [\n { src: \"~/plugins/quickEdit.js\", ssr: false }\n]\n...\n```\n\nand in `~/plugins/quickEdit.js`:\n\n```\nimport Vue from \"vue\";\nimport QuickEdit from 'vue-quick-edit'\n\nVue.use(QuickEdit);\n```\n\nand then just use it in your component.\n\n========================================\n\nCode:\n```text\n<template>\n <quick-edit\n :aria-label=\"label\"\n @input=\"updateValue\"\n />\n</template>\n\n<script>\nimport QuickEdit from 'vue-quick-edit'\n\nexport default {\n components: { QuickEdit },\n props: {\n label: {\n type: String,\n required: true,\n },\n },\n methods: {\n updateValue (event) {\n // do something\n },\n },\n}\n</script>\n\n<style lang=\"scss\" scoped>\n\n</style>\n```\n\n```text\n<template>\n <client-only>\n <quick-edit\n :aria-label=\"label\"\n @input=\"updateValue\"\n />\n </client-only>\n</template>\n```\n\n```text\nclient-only\n```\n\n```text\n...\nplugins: [\n { src: \"~/plugins/quickEdit.js\", ssr: false }\n]\n...\n```\n\n```text\nimport Vue from \"vue\";\nimport QuickEdit from 'vue-quick-edit'\n\nVue.use(QuickEdit);\n```\n\n```text\ndocument\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n~/plugins/quickEdit.js\n```\n\n========================================\n\nComments:\n- This did it for me for the `vue-infinite-loading` plugin. Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:07.892Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":156,"estimatedTokens":690}}764{"id":"stack-54770812","source":"stackoverflow","questionId":54770812,"title":"How to change random text with interval 5 seconds in Vue (Nuxt js)","tags":["javascript","vue.js","nuxt.js"],"text":"Title: How to change random text with interval 5 seconds in Vue (Nuxt js)\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm a beginner in Vue and I have some problem to change random text with interval 5 second when the page is loading.\n\n\r\n\r\n\n```\n\r\n \r\n \r\n Welcome {{ whois }}\r\n \r\n\t\r\n\r\n\r\n\r\nexport default {\r\n data() {\r\n return {\r\n whois: ['Student', 'Developer', 'Programmer']\r\n }\r\n },\r\n // methods: {\r\n // randomWhois(){\r\n \r\n // }\r\n // },\r\n // beforeMount() {\r\n // this.randomWhois();\r\n // }\r\n}\r\n\n```\n\n\r\n\r\n\r\n\nI hope when the interval 5 seconds, my text is always changed.\n\nExample: (always change in 5 seconds)\n\n**Welcome Student**\n\n**Welcome Developer**\n\n**Welcome Programmer**\n\nThank you very much!\n\n========================================\n\nCode:\n```js\n<template>\n <section class=\"container\">\n <h1 class=\"title\">\n Welcome {{ whois }}\n </h1>\n\t</section>\n<template>\n\n<script>\nexport default {\n data() {\n return {\n whois: ['Student', 'Developer', 'Programmer']\n }\n },\n // methods: {\n // randomWhois(){\n \n // }\n // },\n // beforeMount() {\n // this.randomWhois();\n // }\n}\n</script>\n```\n\n```text\n<template>\n <section class=\"container\">\n <h1 class=\"title\">\n Welcome {{ whois[0] }}\n </h1>\n </section>\n<template>\n\n<script>\nexport default {\n data() {\n return {\n whois: ['Student', 'Developer', 'Programmer']\n }\n },\n mounted(){\n window.setInterval(()=>{\n this.pollPerson();\n }, 5000);\n\n },\n methods: {\n pollPerson(){\n const first = this.whois.shift();\n this.whois = this.whois.concat(first);\n }\n }\n}\n</script>\n```\n\n```text\nmounted\n```\n\n```text\nwhois\n```\n\n```text\nWelcome\n```\n\n```text\n{{ whois[0] }}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.892Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":132,"estimatedTokens":433}}765{"id":"stack-52481997","source":"stackoverflow","questionId":52481997,"title":"Vuetify: checkbox shows status is checked when it is unchecked, and vice versa","tags":["javascript","vue.js","vuetify.js","nuxt.js"],"text":"Title: Vuetify: checkbox shows status is checked when it is unchecked, and vice versa\nTags: javascript, vue.js, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nLet me simplify the issue:\n\nI have a checkbox in my Vue.js template (using Vuetify components):\n\n```\n\n```\n\nThe `checkit()` method code is:\n\n```\ncheckit: function() {\n let elt = document.getElementById('john')\n if(elt.checked) {\n console.log('checked')\n } else {\n console.log('unchecked')\n }\n}\n```\n\nBut I am getting the opposite result: when it is checked it says it is unchecked and vice versa.\n\nWhat causes this and how to fix it?\n\nCodepen demo\n\n========================================\n\nCode:\n```text\n<v-checkbox \n v-model=\"selected\" \n label=\"John\"\n value=\"John\"\n id =\"john\" \n @click.native=\"checkit\">\n</v-checkbox>\n```\n\n```text\ncheckit: function() {\n let elt = document.getElementById('john')\n if(elt.checked) {\n console.log('checked')\n } else {\n console.log('unchecked')\n }\n}\n```\n\n```text\ncheckit()\n```\n\n```text\ncheckit: function () {\n this.$nextTick(() => {\n let elt = document.getElementById('john')\n if(elt.checked) {\n console.log('checked')\n } else {\n console.log('unchecked')\n }\n })\n\n //this.selected.push('Vuejs')\n //this.selected.push('Paris')\n}\n```\n\n```text\nchange\n```\n\n```text\ndocument.getElementById('john')\n```\n\n```text\nselected\n```\n\n```text\n$nextTick\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.892Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":91,"estimatedTokens":355}}766{"id":"stack-67985280","source":"stackoverflow","questionId":67985280,"title":"How to set custom path for dotenv in nuxt","tags":["javascript","vue.js","environment-variables","nuxt.js","dotenv"],"text":"Title: How to set custom path for dotenv in nuxt\nTags: javascript, vue.js, environment-variables, nuxt.js, dotenv\nSource: Stack Overflow\n\nQuestion:\nI have the following `nuxt.config.js`, where in the `srcDir` is pointing to \"main-app\" and I have placed the .env outside of it. So in the `nuxt.config.js`, how can set the custom path in line 1\n\n```\nrequire('dotenv').config({ path: '../.env' })\n```\n\nsuch that my process.env works\nhttps://i.sstatic.net/kXwmr.png\n\nAlso the buildModules in nuxt.config.js is as follows\n\n```\nbuildModules: [\"@nuxtjs/fontawesome\", \"@nuxtjs/dotenv\"],\n```\n\n========================================\n\nTop Answer:\n**If you are using version > 2.13 then you won't need to install dotenv anymore because it's already built in**\nhttps://nuxtjs.org/docs/directory-structure/nuxt-config/#runtimeconfig\n\n.env support\nSimilar to vue-cli (*), .env file will be always loaded via dotenv and is accessible via process.env and options._env. process.env is updated so one can use it right inside nuxt.config for runtime config. Values are interpolated and expanded with an improved version of dotenv-expand. .env file is also watched to reload during nuxt dev. Path can be set via cli --dotenv or disabled by --dotenv false.\n\n**I created the .env.xxx files and created the corresponding scripts**\n\nhttps://i.sstatic.net/ekozb.jpg\n\nhttps://i.sstatic.net/DwKDQ.png\n\n========================================\n\nCode:\n```text\nrequire('dotenv').config({ path: '../.env' })\n```\n\n```text\nbuildModules: [\"@nuxtjs/fontawesome\", \"@nuxtjs/dotenv\"],\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nsrcDir\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nbuildModules: [\"@nuxtjs/fontawesome\", ['@nuxtjs/dotenv', { path: './' }]],\n```\n\n```js\nconst { resolve } = require('path')\nrequire('dotenv').config({ path: resolve(__dirname,\"../.env\") })\n```\n\n```js\nconst { resolve } = require('path')\nconst current = resolve(__dirname)\nconst upper = resolve(__dirname, '..')\nconsole.log('current', current)\nconsole.log('upper', upper)\n\nconst testFolder = '../'\n\nfs.readdir(testFolder, (_err, files) => {\n files.forEach((file) => {\n console.log(file)\n })\n})\n\nexport default {\n publicRuntimeConfig: {\n // rest of the nuxt.config.js file below\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nexport default\n```\n\n========================================\n\nComments:\n- You should not post code as images. Rather, copy pasta it as text here.\n- I used require('dotenv').config({path: resolve(__dirname,\"../.env\")})\n- You should console.log the directory above to see if you do find the `.env` in it, and of course double-check that this is fine so far (that you're not one level above/deeper).\n- Actually putting console.log in nuxt.config.js is not showing up\n- any other way to check?\n- It should work. Google a way to find out how to print the content of the `__dirname` directory. Maybe this is a windows only issue?\n- mine is also linux only..let me check the edited answer\n- I am trying to see the console.log in the browser...is that wrong?\n- Should I seperately run the nuxt.config.js file then?\n- This is backend code that you can only run on a `Node.js` environment. So, you need to write it on the \"server\". Edited my question again. But it's pretty much in the `nuxt.config.js` file, before the actual configuration. Or you can also make it in any `.js` file and call `node myFile.js` on it.\n- finally I was able to figure out Actually I was not setting the live path of the env file in the build modules The right path is defined as buildModules: [\"@nuxtjs/fontawesome\", ['@nuxtjs/dotenv', { path: './' }]],\n- Thank you for this, I lost few days and gave up, but found this and tried again, now working flawless\n- npm run build && npm run start is the production command isnt it? where will you put --dotenv .env.production in this script?","metadata":{"transformedAt":"2026-08-18T18:33:07.892Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":111,"estimatedTokens":954}}767{"id":"stack-77292506","source":"stackoverflow","questionId":77292506,"title":"How to make Nuxt 3 correctly build SSG pages + dynamic API routes?","tags":["nuxt.js","nuxt3.js"],"text":"Title: How to make Nuxt 3 correctly build SSG pages + dynamic API routes?\nTags: nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a site which uses only a combination of statically generated pages and JSON API routes, with no runtime SSR of templates. I would like Nuxt to build it accordingly:\n\n- Routes under `/api` should be handled by a runtime server\n\n- Every other route should be prerendered at build time\n\nHowever, I can't figure out how to configure Nuxt to do this particular combination:\n\n- Running `nuxt build` generates the api routes correctly, but doesn't prerender the pages\n\n- Running `nuxt generate` prerenders the pages, but doesn't output a server for the api routes\n\nI'm on the nitro `cloudflare` preset. I've tried various combinations of `routeRules`, but I can't figure out how to get the behavior I want. Any ideas?\n\n========================================\n\nTop Answer:\nThe simplest way is put your `` in the template in `` and use lazyfetch for getting data.\n\nfor generate,first make your _slug page and set in your generate. for example if you have 3 pages on blog route in nuxt 2 you should do this. I think in nuxt 3 is similar.\n\nin nuxt.config\n\n```\ngenerate:{\n dir: 'your directory of generate',\n routes:()=>{\n return[\n '/blog/blog1_page',\n '/blog/blog2_page',\n '...'\n ]\n}\n```\n\n========================================\n\nCode:\n```text\n/api\n```\n\n```text\nnuxt build\n```\n\n```text\nnuxt generate\n```\n\n```text\ncloudflare\n```\n\n```text\nrouteRules\n```\n\n```text\nnitro: {\n prerender: {\n crawlLinks: true,\n routes: ['/'],\n ignore: [\"/api\"]\n }\n},\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nnuxt build\n```\n\n```text\nworker.js\n```\n\n```text\n/api\n```\n\n```text\ngenerate:{\n dir: 'your directory of generate',\n routes:()=>{\n return[\n '/blog/blog1_page',\n '/blog/blog2_page',\n '...'\n ]\n}\n```\n\n```text\n<div>\n```\n\n```text\n<clientOnly>\n```\n\n========================================\n\nComments:\n- That sounds more like an SPA-- I want to statically generate multiple pages\n- This only works on default links that are displayed on the page. I have a checkbox on the page and if I click it, several new links will appear -- these initially hidden links won't be crawled by nitro... Any ideas?\n- @X.Arthur You could create a page, that includes all links of your site and set the crawler to start from that page. Alternatively using `v-show` instead of `v-if` could help get the crawler to see these links.","metadata":{"transformedAt":"2026-08-18T18:33:07.892Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":115,"estimatedTokens":610}}768{"id":"stack-73466605","source":"stackoverflow","questionId":73466605,"title":"How do I load an external stylesheet in Nuxt 3?","tags":["vue.js","nuxt.js","mapbox-gl-js","nuxt3.js"],"text":"Title: How do I load an external stylesheet in Nuxt 3?\nTags: vue.js, nuxt.js, mapbox-gl-js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to load the mapboxgl stylesheet in my Nuxt 3.0.0-rc.8 app. Typically with a Vue projec I manually add it to the head of the index.html page.\n\nHowever, that is not how you do in Nuxt 3 apparently. I've tried adding it to the head and css options in the nuxt.config.ts file, but neither got me there. I did notice that when I added it to the css array, it was added to my header but 'https://' was replaced with '_nuxt'.\n\nI know I am missing something simple. Here is my config file:\n\n```\nexport default defineNuxtConfig({\n css: [\n '~/assets/css/main.css',\n ],\n build: {\n postcss: {\n postcssOptions: require('./postcss.config.js'),\n },\n },\n buildModules: ['@pinia/nuxt'],\n runtimeConfig: {\n treesAPIKey: '',\n public: {\n baseURL: '',\n mapToken: '',\n },\n },\n head: { link: [{ rel: 'stylesheet', href: 'https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css' }] },\n});\n```\n\n========================================\n\nCode:\n```js\nexport default defineNuxtConfig({\n css: [\n '~/assets/css/main.css',\n ],\n build: {\n postcss: {\n postcssOptions: require('./postcss.config.js'),\n },\n },\n buildModules: ['@pinia/nuxt'],\n runtimeConfig: {\n treesAPIKey: '',\n public: {\n baseURL: '',\n mapToken: '',\n },\n },\n head: { link: [{ rel: 'stylesheet', href: 'https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css' }] },\n});\n```\n\n```js\nimport { defineNuxtConfig } from 'nuxt'\n\nexport default defineNuxtConfig({\n app: {\n head: {\n link: [{ rel: 'stylesheet', href: 'https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css' }]\n }\n }\n})\n```\n\n```text\napp.head\n```\n\n```text\nhead\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.892Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":77,"estimatedTokens":440}}769{"id":"stack-51710423","source":"stackoverflow","questionId":51710423,"title":"Can't include scss file in the css nuxt.config.js configuration","tags":["nuxt.js"],"text":"Title: Can't include scss file in the css nuxt.config.js configuration\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to include a scss file in the css nuxt.config.js option however when I run \n\n```\nnpm run dev\n```\n\nI get the following error : \n\n```\nThis dependency was not found:\n\n* ..\\assets\\css\\main.scss in ./.nuxt/App.js\n\nTo install it, you can run: npm install --save ..\\assets\\css\\main.scss\n```\n\nHere is my package.json :\n\n```\n\"dependencies\": {\n \"bootstrap-vue\": \"^2.0.0-rc.11\",\n \"nuxt\": \"^1.0.0\"\n },\n \"devDependencies\": {\n \"babel-eslint\": \"^8.2.1\",\n \"eslint\": \"^4.15.0\",\n \"eslint-friendly-formatter\": \"^3.0.0\",\n \"eslint-loader\": \"^1.7.1\",\n \"eslint-plugin-vue\": \"^4.0.0\",\n \"node-sass\": \"^4.9.2\",\n \"sass-loader\": \"^7.1.0\"\n }\n```\n\nAnd the css configuration :\n\n```\ncss: [\n \"@/assets/css/main.scss\",\n ],\n```\n\nThe main.scss file is located under assets/css/main.scss :\n\n```\n@import \"node_modules/bootstrap/scss/bootstrap\";\n\n* {\n font-family: \"Quicksand\";\n margin: 0;\n padding: 0;\n}\n\n.full-width {\n width: 100%;\n}\n```\n\n========================================\n\nCode:\n```text\nnpm run dev\n```\n\n```text\nThis dependency was not found:\n\n* ..\\assets\\css\\main.scss in ./.nuxt/App.js\n\nTo install it, you can run: npm install --save ..\\assets\\css\\main.scss\n```\n\n```text\n\"dependencies\": {\n \"bootstrap-vue\": \"^2.0.0-rc.11\",\n \"nuxt\": \"^1.0.0\"\n },\n \"devDependencies\": {\n \"babel-eslint\": \"^8.2.1\",\n \"eslint\": \"^4.15.0\",\n \"eslint-friendly-formatter\": \"^3.0.0\",\n \"eslint-loader\": \"^1.7.1\",\n \"eslint-plugin-vue\": \"^4.0.0\",\n \"node-sass\": \"^4.9.2\",\n \"sass-loader\": \"^7.1.0\"\n }\n```\n\n```text\ncss: [\n \"@/assets/css/main.scss\",\n ],\n```\n\n```text\n@import \"node_modules/bootstrap/scss/bootstrap\";\n\n* {\n font-family: \"Quicksand\";\n margin: 0;\n padding: 0;\n}\n\n.full-width {\n width: 100%;\n}\n```\n\n```text\nnpm install --save-dev sass sass-loader fibers\n```\n\n```text\ncss: [\n '@/assets/scss/main.scss'\n]\n```\n\n```text\nsass-loader\n```\n\n```text\nsass\n```\n\n```text\nfibers\n```\n\n========================================\n\nComments:\n- Can you post your whole config file? It may be you are missing a curly brace or something.\n- This solution didnt work for me, i still get the error","metadata":{"transformedAt":"2026-08-18T18:33:07.892Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":141,"estimatedTokens":549}}770{"id":"stack-78121968","source":"stackoverflow","questionId":78121968,"title":"How to add inline script tags to Nuxt 3?","tags":["nuxt.js","nuxt3.js"],"text":"Title: How to add inline script tags to Nuxt 3?\nTags: nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to integrate Piwik and Intercom into my Nuxt 3 application. Previously, I was able to use the special `app.html` file in the project root, but that feature is not available anymore. I can use the `useHead()` utility or the Nuxt configuration, but I don't have a URL for the `src` attribute, just an inline script.\n\n========================================\n\nCode:\n```text\napp.html\n```\n\n```text\nuseHead()\n```\n\n```text\nsrc\n```\n\n```js\nuseHead({\n script: [\n {\n textContent: `/* Inline code goes here ... */`\n tagPosition: \"bodyClose\",\n },\n ],\n});\n```\n\n```text\ntextContent\n```\n\n```text\nuseHead()\n```\n\n```text\napp.head.script\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\ntagPosition\n```\n\n```text\n'head' | 'bodyClose' | 'bodyOpen'\n```\n\n```text\ninnerHTML\n```\n\n```text\ntextContent\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.892Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":64,"estimatedTokens":227}}771{"id":"stack-59082751","source":"stackoverflow","questionId":59082751,"title":"How to remove window._nuxt_ in nuxt project, it is too large for me","tags":["vue.js","nuxt.js","vue-ssr"],"text":"Title: How to remove window._nuxt_ in nuxt project, it is too large for me\nTags: vue.js, nuxt.js, vue-ssr\nSource: Stack Overflow\n\nQuestion:\nWhen I use `nuxt` to develop my project, I find some problems. \n\n```\nwindow.__NUXT__=(function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,_,$,aa, ..... code was too larger\n```\n\ncan I remove it or use js file to replace it?\n\n========================================\n\nCode:\n```text\nwindow.__NUXT__=(function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,_,$,aa, ..... code was too larger\n```\n\n```text\nnuxt\n```\n\n```text\n// nuxt.config.js\n{\n...,\nhooks: {\n 'vue-renderer:ssr:context'(context) {\n const routePath = JSON.stringify(context.nuxt.routePath);\n context.nuxt = {serverRendered: true, routePath};\n }\n }\n}\n```\n\n```text\nhook\n```\n\n```text\nvue-renderer:ssr:context\n```\n\n```text\ncontext.nuxt = null\n```\n\n```text\nwindow._NUXT_\n```\n\n```text\nserverRender\n```\n\n```text\nroutePath\n```\n\n```text\nwindow.nuxt\n```\n\n========================================\n\nComments:\n- You're a live saver :)","metadata":{"transformedAt":"2026-08-18T18:33:07.893Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":69,"estimatedTokens":289}}772{"id":"stack-73804228","source":"stackoverflow","questionId":73804228,"title":"How to include an .htaccess file wit Nuxt?","tags":["vue.js",".htaccess","nuxt.js"],"text":"Title: How to include an .htaccess file wit Nuxt?\nTags: vue.js, .htaccess, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a Nuxt.js app with an `.htaccess` file.\n\nThe problem is that when I execute `nuxt generate` in the terminal, my `.htaccess` file disappears. What can I do to include my `.htaccess` file when I execute `nuxt generate`?\n\n========================================\n\nCode:\n```text\n.htaccess\n```\n\n```text\nnuxt generate\n```\n\n```text\n.htaccess\n```\n\n```text\n.htaccess\n```\n\n```text\nnuxt generate\n```\n\n```text\n.htaccess\n```\n\n```text\n/static\n```\n\n========================================\n\nComments:\n- You could probably put it into the `/static` directory: nuxtjs.org/docs/directory-structure/static#static-directory\n- I also have this approach: stackoverflow.com/a/71844473/8816585 Even tho, I'm not sure it's needed if you want something static.\n- Thank you it's working. I thought that if was putting my .htaccess file into the static directory, it would stay here.\n- I have posted my answer!\n- could also move or make the file dynamically with a custom build module nuxtjs.org/docs/directory-structure/modules\n- The docs are for Nuxt 2. Does it work the same in Nuxt 3? According to Nuxt 3 docs, I should use the `public` directory for that, but a `.htaccess` file put into `public` will not show up in the generated pages (using ssg `nuxi generate`). nuxt.com/docs/guide/directory-structure/public\n- @fred this is indeed the directory for Nuxt3. Not sure what's wrong on your side but it should work properly and is the way to go. One thing to note is that the build process should not affect its content meaning that what you put in the public directory will be served as is and hence not touched by your build tool (I assume it's Vite).\n- `nuxi generate` will properly copy any dot file from `public/` to `.output/public/` BUT the `.htaccess` file. So I assume this is a mechanic that was built in on purpose (maybe for security reasons?). I can't find a way to turn it off.\n- So I went this way: I created a non-standard `static/` directory and just run a `cp ...` command after `nuxi generate`. Saves me the trouble with the nuxt compiler.","metadata":{"transformedAt":"2026-08-18T18:33:07.893Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":52,"estimatedTokens":545}}773{"id":"stack-72883103","source":"stackoverflow","questionId":72883103,"title":"Nuxt Vitest Mock useRoute in another module","tags":["jestjs","nuxt.js","vuejs3","vue-router","vitest"],"text":"Title: Nuxt Vitest Mock useRoute in another module\nTags: jestjs, nuxt.js, vuejs3, vue-router, vitest\nSource: Stack Overflow\n\nQuestion:\nI am trying to write a test for the following Nuxt 3 composable (useLinkToSlug).\n\n```\nimport { computed } from 'vue';\n\nexport default function () {\n const route = useRoute();\n return computed(() => route?.params?.slug ? `/${route.params.slug}` : undefined);\n}\n```\n\nTo keep the code as lean as possible, I tried to mock the vue-router module and set the return of `useRoute()` manually.\n\nMy test looks like this:\n\n```\nimport { vi, it, expect, describe } from 'vitest';\n\nimport useLinkToSlug from '~~/composables/useLinkToSlug';\n\ndescribe('useLinkToSlug', () => {\n it('should return link to slug', () => {\n vi.mock('vue-router', () => ({\n useRoute: () => ({ params: { slug: 'abc' } })\n }));\n\n const link = useLinkToSlug();\n\n expect(link.value).toEqual('/abc');\n });\n\n it('should return null', () => {\n vi.mock('vue-router', () => ({\n useRoute: () => ({ params: { slug: undefined } })\n }));\n\n const link = useLinkToSlug();\n\n expect(link.value).toBeNull();\n });\n});\n```\n\nThe first one succeeds, but the later one fails, with:\n\nAssertionError: expected '/abc' to be null\n\nI don't get why and what to do, to make this work.\n\nUsing: Nuxt3 with Vitest\n\n========================================\n\nCode:\n```js\nimport { computed } from 'vue';\n\nexport default function () {\n const route = useRoute();\n return computed(() => route?.params?.slug ? `/${route.params.slug}` : undefined);\n}\n```\n\n```js\nimport { vi, it, expect, describe } from 'vitest';\n\nimport useLinkToSlug from '~~/composables/useLinkToSlug';\n\ndescribe('useLinkToSlug', () => {\n it('should return link to slug', () => {\n vi.mock('vue-router', () => ({\n useRoute: () => ({ params: { slug: 'abc' } })\n }));\n\n const link = useLinkToSlug();\n\n expect(link.value).toEqual('/abc');\n });\n\n it('should return null', () => {\n vi.mock('vue-router', () => ({\n useRoute: () => ({ params: { slug: undefined } })\n }));\n\n const link = useLinkToSlug();\n\n expect(link.value).toBeNull();\n });\n});\n```\n\n```text\nuseRoute()\n```\n\n```js\nimport { computed } from 'vue';\nimport { useRoute } from 'vue-router'; // added this import statement\n\nexport default function () {\n const route = useRoute();\n return computed(() => route?.params?.slug ? `/${route.params.slug}` : undefined);\n}\n```\n\n```js\nimport { vi, it, expect, describe } from 'vitest';\n\nimport useLinkToSlug from '~~/composables/useLinkToSlug';\n\nvi.mock('vue-router'); // mock the import\n\ndescribe('useLinkToSlug', () => {\n it('should return link to slug', () => {\n const VueRouter = await import('vue-router');\n\n VueRouter.useRoute.mockReturnValueOnce({\n params: { slug: 'abc' }\n });\n\n const link = useLinkToSlug();\n\n expect(link.value).toEqual('/abc');\n });\n\n it('should return null', () => {\n const VueRouter = await import('vue-router');\n\n VueRouter.useRoute.mockReturnValueOnce({\n params: { slug: undefined }\n });\n\n const link = useLinkToSlug();\n\n expect(link.value).toBeNull();\n });\n});\n```\n\n```text\nuseRoute\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.893Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":147,"estimatedTokens":811}}774{"id":"stack-72917167","source":"stackoverflow","questionId":72917167,"title":"Simple Nuxt 3 Page Transition not working","tags":["vue.js","nuxt.js","vue-router","nuxt3.js"],"text":"Title: Simple Nuxt 3 Page Transition not working\nTags: vue.js, nuxt.js, vue-router, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm discovering Nuxt 3 and and simply want to make an animation between pages. The idea is to use javascript hooks to make page transitions using js library such as gsap or animeJs.\n\nSo in my `app.vue` file, I simply put `` into `` element like this :\n\n```\n\n \n \n \n\n```\n\nMy vue pages ('./pages/index.vue' and './pages/project/myproject.vue') look like this :\n\n```\n\n \n \n\n### My Project\n\n \n\nfunction onEnter(el, done) {\n done()\n}\nfunction onLeave(el, done) {\n done()\n}\n\n```\n\nI have followed both Nuxt 3 and Vue 3 documentations :\n\nhttps://v3.nuxtjs.org/guide/directory-structure/pages#layouttransition-and-pagetransition\n\nhttps://vuejs.org/guide/built-ins/transition.html#javascript-hooks\n\nI also read this thread on github, but I can't find answer :\nhttps://github.com/nuxt/framework/discussions/851\n\nWhen i was using **Nuxt 2** I only need to put transition object into my page like this and it's working fine :\n\n```\n\nexport default {\n // ... (datas, methods)\n transition: {\n mode: \"in-out\",\n css: false,\n enter(el, done) {\n console.log(\"enter\");\n done()\n },\n leave(el, done) {\n console.log(\"leave\");\n done()\n }\n }\n}\n\n \n \n\n### Hello World\n\n \n\n```\n\nDo you have any idea how to achieve it ?\n\n========================================\n\nTop Answer:\nJust the official documentation for Nuxt 3. You need to add the following code to your `nuxt.config.ts` file:\n\n```\nexport default defineNuxtConfig({\n app: {\n pageTransition: { name: 'page', mode: 'out-in' }\n },\n})\n```\n\nAnd then apply the classes inside your `app.vue` file, like this:\n\n```\n\n \n\n.page-enter-active,\n.page-leave-active {\n transition: all 0.4s;\n}\n\n.page-enter-from,\n.page-leave-to {\n opacity: 0;\n filter: blur(1rem);\n}\n\n```\n\nNuxt 3 uses the Vue's `` component under the hood, so you don't need to add it in the template.\n\nBe careful with **the css prefix**.\n\n========================================\n\nCode:\n```text\n<NuxtLayout>\n <Transition>\n <NuxtPage/>\n </Transition>\n</NuxtLayout>\n```\n\n```text\n<template>\n <div>\n <h1>My Project</h1>\n </div>\n</template>\n\n<script setup>\nfunction onEnter(el, done) {\n done()\n}\nfunction onLeave(el, done) {\n done()\n}\n</script>\n```\n\n```text\n<script>\nexport default {\n // ... (datas, methods)\n transition: {\n mode: \"in-out\",\n css: false,\n enter(el, done) {\n console.log(\"enter\");\n done()\n },\n leave(el, done) {\n console.log(\"leave\");\n done()\n }\n }\n}\n</script>\n<template>\n <div>\n <h1 class=\"text-center text-5xl\">Hello World</h1>\n </div>\n</template>\n```\n\n```text\napp.vue\n```\n\n```text\n<NuxtPage/>\n```\n\n```text\n<Transition>\n```\n\n```text\n<Transition>\n```\n\n```text\nassets/sass/app.scss\n```\n\n```text\npage-\n```\n\n```text\nlayout-\n```\n\n```js\nexport default defineNuxtConfig({\n app: {\n pageTransition: { name: 'page', mode: 'out-in' }\n },\n})\n```\n\n```js\n<template>\n <NuxtPage />\n</template>\n\n<style>\n.page-enter-active,\n.page-leave-active {\n transition: all 0.4s;\n}\n\n.page-enter-from,\n.page-leave-to {\n opacity: 0;\n filter: blur(1rem);\n}\n</style>\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\napp.vue\n```\n\n```text\n<Transition>\n```\n\n```text\n<style>\n```\n\n```text\nscoped\n```\n\n```text\nexport default defineNuxtConfig({\n app: {\n pageTransition: { name: 'page', mode: 'out-in' }\n },\n})\n```\n\n```text\n<template>\n <NuxtPage />\n</template>\n\n<style>\n.page-enter-active,\n.page-leave-active {\n transition: all 0.4s;\n}\n.page-enter-from,\n.page-leave-to {\n opacity: 0;\n filter: blur(1rem);\n}\n</style>\n```\n\n```text\ntransition\n```\n\n```text\nstyle\n```\n\n```html\n<!--components/im/index.vue-->\n<template>\n <ClientOnly>\n <Transition name=\"fade\">\n <div>test</div>\n </Transition>\n </ClientOnly>\n</template>\n<script setup>\n\n</script>\n\n<style scoped lang=\"scss\">\n.fade-enter-active,\n.fade-leave-active {\n transition: opacity 0.5s ease;\n}\n\n.fade-enter-from,\n.fade-leave-to {\n opacity: 0;\n}\n</style>\n```\n\n========================================\n\nComments:\n- I don't understand why this is marked as the answer. It does not answer the question about transitions with js hooks?\n- This does not answer how to create transitions using hooks.\n- it doesn not work for me\n- scoped was the hint. Thanks!\n- Please add supporting details, links or an explanation to improve your answer. Please refer to stackoverflow.com/help/how-to-answer for more details.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:07.893Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":310,"estimatedTokens":1199}}775{"id":"stack-70534566","source":"stackoverflow","questionId":70534566,"title":"Run a dev server in CI pipleine","tags":["vue.js","continuous-integration","nuxt.js","devops","github-actions"],"text":"Title: Run a dev server in CI pipleine\nTags: vue.js, continuous-integration, nuxt.js, devops, github-actions\nSource: Stack Overflow\n\nQuestion:\nI have a CI pipeline setup using Github Action/Workflows, where i would want to run Cypress Automated tests, However I am having some logical problems of how to run my dev server. let me show you my pipeline\n\n```\nname: Nuxt CI Pipeline\n\non:\n push:\n branches: [ CI-pipeline ]\n # pull_request:\n # branches: [ master ]\n\njobs:\n build:\n\n runs-on: ubuntu-latest\n\n strategy:\n matrix:\n node-version: [ 14.x ]\n # See supported Node.js release schedule at https://nodejs.org/en/about/releases/\n\n steps:\n - uses: actions/checkout@v2\n - name: Use Node.js ${{ matrix.node-version }}\n uses: actions/setup-node@v2\n with:\n node-version: ${{ matrix.node-version }}\n cache: 'npm'\n - name: Make envfile\n uses: SpicyPizza/create-envfile@v1\n with:\n envkey_ENV: staging\n file_name: .env\n - run: npm ci\n - run: npm run dev\n - run: | \n cd e2e\n ls -l\n npm ci\n npx cypress run\n```\n\nNow I want to spin up the devserver and run the tests on that port usually 3000 , however the problem is when the command `npm run dev` is executed, the pipeline keeps on waiting there and doesnt move forward , which makes sense as devserver doesn't return a response as other commands will , so its kinda stuck there. My knowledge of devops is bare minimum , can someone point out what am i missing?\n\n========================================\n\nCode:\n```text\nname: Nuxt CI Pipeline\n\non:\n push:\n branches: [ CI-pipeline ]\n # pull_request:\n # branches: [ master ]\n\njobs:\n build:\n\n runs-on: ubuntu-latest\n\n strategy:\n matrix:\n node-version: [ 14.x ]\n # See supported Node.js release schedule at https://nodejs.org/en/about/releases/\n\n steps:\n - uses: actions/checkout@v2\n - name: Use Node.js ${{ matrix.node-version }}\n uses: actions/setup-node@v2\n with:\n node-version: ${{ matrix.node-version }}\n cache: 'npm'\n - name: Make envfile\n uses: SpicyPizza/create-envfile@v1\n with:\n envkey_ENV: staging\n file_name: .env\n - run: npm ci\n - run: npm run dev\n - run: | \n cd e2e\n ls -l\n npm ci\n npx cypress run\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm install --save-dev start-server-and-test\n```\n\n```text\n\"scripts\": {\n \"start:ci\": \"<<start your dev server>>\",\n \"cy:run\": \"cypress run --browser chrome --headless\",\n \"cy:ci\": \"start-server-and-test start:ci http://localhost:3000 cy:run\"\n },\n```\n\n```text\npackage.json\n```\n\n```text\nnpm run cy:ci\n```\n\n========================================\n\nComments:\n- I wish I can give you 100 Upvotes and a beer, I've been banging my head around for days on this, thankyou so much for this, keep up the good work\n- I have a problem where the cypress tester could not access the dev server running on localhost:3000. Any idea why this happens?\n- Only with this information it is difficult to make a guess. I would recommend to open a new question for your issue including some implementation details. Feel free to link it here as a comment, then I can take a look.","metadata":{"transformedAt":"2026-08-18T18:33:07.893Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":122,"estimatedTokens":782}}776{"id":"stack-68528407","source":"stackoverflow","questionId":68528407,"title":"Change Nuxt Route Without Re-rendering","tags":["vue.js","nuxt.js","vue-router"],"text":"Title: Change Nuxt Route Without Re-rendering\nTags: vue.js, nuxt.js, vue-router\nSource: Stack Overflow\n\nQuestion:\nI have a Nuxt page and i want to change route path without re-rendering or refreshing page with a method on a button.\n\nif i do `this.$router.push()` or `replace()`, page will refresh and if i do `window.history.pushState()` or `replaceState()` that works fine but after that if i add a query with `this.$router.push({ query: a = b })` on my page, page will refresh because changing route with `window.history` will not change `$route` and when i use `this.$router.push`, Vue Router thinks its a different page.\n\nI've done a lot of search on internet and did not find anything, so please don't label this question as duplicate.\n\n========================================\n\nTop Answer:\nFinally i solved this problem with using parent page and nuxt childs, i changed tabs to nav and rendered base components on parent page and other things on child pages and now it works fine. Tnx to @kissu and @Braks.\n\n========================================\n\nCode:\n```text\nthis.$router.push()\n```\n\n```text\nreplace()\n```\n\n```text\nwindow.history.pushState()\n```\n\n```text\nreplaceState()\n```\n\n```text\nthis.$router.push({ query: a = b })\n```\n\n```text\nwindow.history\n```\n\n```text\n$route\n```\n\n```text\nthis.$router.push\n```\n\n========================================\n\nComments:\n- What are you actually trying to achieve with all of this?\n- i have some tabs in my page and im tring to sync active tab name in route\n- `router.push` doesn't refresh the page. Who told you it does?\n- If you're having tabs, try to use the dynamic component: vuejs.org/v2/guide/components-dynamic-async.html\n- You don't even need to mess up with the router/path to achieve some tabs. Pass it regular props defining which tab to display.\n- Also, could you please provide us some code? Would be helpful to see what you're tying to do. Even a minimal reproducible example could be nice!\n- i know do not need to change path to active tab. but i want to keep tabs and route synce so if someone come in my page can go on any tab directly. look this page to undrestand what im trying to do beatstars.com/raspo/feed\n- go to beatstars.com/raspo/feed and try changing tabs and you see page URL is changing too but no refreshing or re-rendering happend\n- i have a page like this but if i change tab with $router.push() or $router.replace() tab content will be shown on click then page will be refreshed\n- router.push does not trigger a page *reload* if that's what you're talking about. If you mean that you're *router-view* changes then yeah of course it does. You're pushing a different route so of course the view will change. If you *only* want to have the Tab change then the Tab should be a child of some Route (in the website you linked that'd be the root / ). The website you linked basically does the same. you click a tab, it pushes a route and the tab gets rendered in its container accordingly. Maybe this will help you too.\n- As mentioned above by @braks, when you navigate thanks to the Vue router (the one also used in Nuxt), you will remove some pages and mount some other instead. You can prevent this kind of behavior and have something more hacky but your use-case is totally classic. Hence you can use the default behavior of the nested pages. There is no \"browser\" refresh as in a F5 keypress. But there is a new rendering, otherwise you won't be able to get the fresh new components.\n- Also of note, when using nested pages (ie ``), it's best to set a `key` for it, however be careful of what you set the key as. I was using `router.replace` within the nested page content, and I would still get browser refresh! This is because I was using `route.fullPath` for the NuxtPage key, which meant the key would change on small changes to query params. Instead, I change it to use `route.name` to be more simple, and everything worked.","metadata":{"transformedAt":"2026-08-18T18:33:07.893Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":66,"estimatedTokens":977}}777{"id":"stack-66842616","source":"stackoverflow","questionId":66842616,"title":"Vue / Nuxt.js - APIs being called twice in created hook","tags":["vue.js","nuxt.js"],"text":"Title: Vue / Nuxt.js - APIs being called twice in created hook\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am currently developing in Nuxt.js and like most beginners, I wanted to know the best lifecycle hook to place API calls. Many resources I have found, much like the one below, state that the `created()` hook is the best place for fetching data from an API prior to having everything be loaded.\n\nDifference between the created and mounted events in Vue.js\n\nMy question came in when I noticed on the networking tab in developer options that my API within the `created()` hook was being called twice. After looking into this further, it states that this hook runs on server side and client side. I notice that `mounted()` only runs on client side so I am learning towards utilizing that hook. I did however notice that I can use some `if` logic (if process.server) in the `created()` hook to only have this run on the client / server and not both. Is this a common solution?\n\nTo clarify my question further, if `created()` runs on both server and client side, why put my API calls in this hook?\n\n========================================\n\nCode:\n```text\ncreated()\n```\n\n```text\ncreated()\n```\n\n```text\nmounted()\n```\n\n```text\nif\n```\n\n```text\ncreated()\n```\n\n```text\ncreated()\n```\n\n```js\nexport default {\n data() {\n return {\n todos: []\n }\n },\n async fetch() {\n const { data } = await axios.get(\n `https://jsonplaceholder.typicode.com/todos`\n )\n // `todos` has to be declared in data()\n this.todos = data\n }\n}\n```\n\n```js\nexport default {\n async asyncData(context) {\n const data = await context.$axios.$get(\n `https://jsonplaceholder.typicode.com/todos`\n )\n // `todos` does not have to be declared in data()\n return { todos: data.Item }\n // `todos` is merged with local data\n }\n}\n```\n\n```text\ncreated\n```\n\n```text\nif(process.server)\n```\n\n```text\nfetch\n```\n\n```text\nfetchOnServer: false\n```\n\n```text\nthis\n```\n\n```text\n$fetchState.pending\n```\n\n```text\n$fetchState.error\n```\n\n```text\nfetch\n```\n\n```text\n$fetch()\n```\n\n```text\nasyncData\n```\n\n```text\nthis\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.893Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":113,"estimatedTokens":529}}778{"id":"stack-70766367","source":"stackoverflow","questionId":70766367,"title":"Pass data from child to parent with a computed property in vuejs","tags":["vue.js","filter","nuxt.js"],"text":"Title: Pass data from child to parent with a computed property in vuejs\nTags: vue.js, filter, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to make a search component that receives an object and then filters it by user input. Then pass it again to parent to show what i filtered. (Nuxt)\n\n```\n// Parent component\n\n...\n\nbookmarks = [ { \"title\": \"Facebook\", \"url\": \"https://facebook.com\" }, { \"title\": \"Google\", \"url\": \"https://google.com/\" } ]\n```\n\n```\n// Child search component\n\n \n\n export default {\n props: ['bookmarks'],\n data() {\n return {\n searchQuery: null,\n }\n },\n computed: {\n filteringBookmarks:{\n get: function() {\n if(this.searchQuery){\n return this.bookmarks.filter(data => data.title.toLowerCase().includes(this.searchQuery.toLowerCase()))\n } else{\n return this.bookmarks;\n }\n }\n }\n },\n watch: {\n filteringBookmarks(newValue) {\n console.log(`yes, computed property changed: ${newValue}`); // \n```\n\nI've tried another ways but always ends in the same spot, whole website freezing. Its seems like never stop refreshing \"bookmarks\". Maybe is a circular problem?\n\n========================================\n\nTop Answer:\nYou are emitting a computed value to the parent component, and the parent updates the bookmarks and pass it as a prop to the child component which makes the computed property to be updated and since you have a watcher on the computed property, it will again emits it's new value causing an **infinite loop**.\n\nA **solution** can be to emit search query itself and then filter the results on the parent element.\n\n========================================\n\nCode:\n```js\n// Parent component\n<AppSearch :bookmarks=\"bookmarks\" />\n\n...\n\nbookmarks = [ { \"title\": \"Facebook\", \"url\": \"https://facebook.com\" }, { \"title\": \"Google\", \"url\": \"https://google.com/\" } ]\n```\n\n```js\n// Child search component\n<template>\n <input type=\"text\" v-model=\"searchQuery\"> </input>\n</template>\n\n<script>\n export default {\n props: ['bookmarks'],\n data() {\n return {\n searchQuery: null,\n }\n },\n computed: {\n filteringBookmarks:{\n get: function() {\n if(this.searchQuery){\n return this.bookmarks.filter(data => data.title.toLowerCase().includes(this.searchQuery.toLowerCase()))\n } else{\n return this.bookmarks;\n }\n }\n }\n },\n watch: {\n filteringBookmarks(newValue) {\n console.log(`yes, computed property changed: ${newValue}`); // <--- INFINITES MESSAGES\n this.$emit('update:bookmarks', filteringBookmarks)\n }\n },\n }\n</script>\n```\n\n```html\n<script>\n export default {\n props: ['bookmarks'],\n data() {\n return {\n searchQuery: null,\n }\n },\n watch: {\n searchQuery(newValue) {\n let filteringBookmarks=[]\n if(newValue){\n filteringBookmarks=this.bookmarks.filter(data => data.title.toLowerCase().includes(this.searchQuery.toLowerCase()))\n }else{\n filteringBookmarks=this.bookmarks;\n }\n\n this.$emit('update:bookmarks', filteringBookmarks)\n }\n },\n }\n</script>\n```\n\n```text\nsearchQuery\n```\n\n========================================\n\nComments:\n- This solved my problem partially, as i had to add an event listener (because that emit doesn't work for me) and i had to create a duplicate of 'bookmarks', because when i was changing it, it was changed in the child too, and we dont want that. So i just pass 'bookmarks' to child, and in the parent i use 'filteredBookmarks' which is the changing one and has the initial value of 'bookmarks'. I hope that those who come here understand this.\n- Thanks a lot!!!","metadata":{"transformedAt":"2026-08-18T18:33:07.893Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":133,"estimatedTokens":946}}779{"id":"stack-67093079","source":"stackoverflow","questionId":67093079,"title":"Nuxt.config.js is not in cwd","tags":["vue.js","nuxt.js"],"text":"Title: Nuxt.config.js is not in cwd\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to use 'npm run generate' in Nuxt project, but i have error:\n\n```\nPath C:/Users/Марина/OneDrive/Desktop/weHost/zabota-dialog/nuxt.config.js is not in cwd C:\\Users\\Марина\\OneDrive\\Desktop\\weHost\\zabota-dialog\n```\n\nNuxt.config.js now in Project root directory. File contents:\n\n```\nexport default {\n // Target: https://go.nuxtjs.dev/config-target\n target: \"static\",\n\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: \"dialog-zabota\",\n htmlAttrs: {\n lang: \"en\"\n },\n meta: [\n { charset: \"utf-8\" },\n { name: \"viewport\", content: \"width=device-width, initial-scale=1\" },\n { hid: \"description\", name: \"description\", content: \"\" }\n ],\n link: [{ rel: \"icon\", type: \"image/x-icon\", href: \"/favicon.ico\" }]\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\"./assets/less/main.less\"],\n styleResources: {\n less: [\"./assets/less/static/variables.less\", \"./assets/less/static/font-face.less\"]\n },\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\"@nuxtjs/style-resources\"],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [],\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {}\n};\n```\n\nWhat i do wrong? Why it's not run?\n\n========================================\n\nTop Answer:\nI can recommend don't use cyrillic later in path\n.Its help for me\n\n========================================\n\nCode:\n```text\nPath C:/Users/Марина/OneDrive/Desktop/weHost/zabota-dialog/nuxt.config.js is not in cwd C:\\Users\\Марина\\OneDrive\\Desktop\\weHost\\zabota-dialog\n```\n\n```js\nexport default {\n // Target: https://go.nuxtjs.dev/config-target\n target: \"static\",\n\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: \"dialog-zabota\",\n htmlAttrs: {\n lang: \"en\"\n },\n meta: [\n { charset: \"utf-8\" },\n { name: \"viewport\", content: \"width=device-width, initial-scale=1\" },\n { hid: \"description\", name: \"description\", content: \"\" }\n ],\n link: [{ rel: \"icon\", type: \"image/x-icon\", href: \"/favicon.ico\" }]\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\"./assets/less/main.less\"],\n styleResources: {\n less: [\"./assets/less/static/variables.less\", \"./assets/less/static/font-face.less\"]\n },\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\"@nuxtjs/style-resources\"],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [],\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {}\n};\n```\n\n```text\nC:\\Users\\Марина\\OneDrive\\Desktop\\weHost\\zabota-dialog\n```\n\n```text\nC:/Users/Марина/OneDrive/Desktop/weHost/zabota-dialog/nuxt.config.js\n```\n\n```text\n\\\n```\n\n```text\n/\n```\n\n```text\nnpm backslash windows\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.893Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":129,"estimatedTokens":801}}780{"id":"stack-72127393","source":"stackoverflow","questionId":72127393,"title":"cant access json object stored in local storage [object Object] in vue.js","tags":["javascript","vue.js","nuxt.js"],"text":"Title: cant access json object stored in local storage [object Object] in vue.js\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have `fieldObj` which I need frequently. It comes from database.\nI want to store it in localStorage.\n\nbelow is the code I wrote which fetch `fieldObj` from database if localStorage don't have it.\n\nWhen I try to access the json data stored in localStorage it just shows\n\n[object Object]\n\ncode is treating `fieldObj` of localStorage as string.\n\nI need to access key values pairs stored in `fieldObj`.\n\n```\n\nexport default {\n data() {\n return {\n fields: JSON,\n }\n },\n created() {\n if (!localStorage.getItem('field-obj')) {\n axios\n .get('/api/u/record/', {\n withCredentials: true,\n })\n .then((response) => {\n response.data.forEach((el) => {\n if (el.COLUMN_TYPE == 'int') el.COLUMN_TYPE = 'number'\n })\n const fieldObj = response.data[0].fieldObj[0]\n this.fields = fieldObj\n })\n .then(() => {\n localStorage.setItem('field-obj', this.fields)\n })\n } else {\n console.log(new Object(localStorage.getItem('field-obj')))\n // console.log(localStorage.getItem('field-obj')[0].username)\n }\n },\n}\n\n```\n\n========================================\n\nCode:\n```html\n<script>\nexport default {\n data() {\n return {\n fields: JSON,\n }\n },\n created() {\n if (!localStorage.getItem('field-obj')) {\n axios\n .get('/api/u/record/', {\n withCredentials: true,\n })\n .then((response) => {\n response.data.forEach((el) => {\n if (el.COLUMN_TYPE == 'int') el.COLUMN_TYPE = 'number'\n })\n const fieldObj = response.data[0].fieldObj[0]\n this.fields = fieldObj\n })\n .then(() => {\n localStorage.setItem('field-obj', this.fields)\n })\n } else {\n console.log(new Object(localStorage.getItem('field-obj')))\n // console.log(localStorage.getItem('field-obj')[0].username)\n }\n },\n}\n</script>\n```\n\n```text\nfieldObj\n```\n\n```text\nfieldObj\n```\n\n```text\nfieldObj\n```\n\n```text\nfieldObj\n```\n\n```js\nlocalStorage.setItem('field-obj',JSON.stringify(this.fields))\n```\n\n```js\nthis.fields = JSON.parse(localStorage.getItem('field-obj'))\n```\n\n========================================\n\nComments:\n- Try to wrap the thing that you want to display into a `JSON.parse(JSON.stringify(yourObject))` to inspect the variable. There is probably an object down there and not a string or alike.\n- do you mean `JSON.parse(JSON.stringify(localStorage.getItem('field-obj'))‌​)` ?\n- when it fetch `fieldObj` from database it gives `{case index: 'varchar(14)', next visit: 'date', patient name: 'varchar(30)', prescription: 'varchar(255)'}`\n- Yes for the first question. So if you store an object in your localStorage, you will get an object back. Hence something like `localStorage.getItem('field-obj').prescription` may be needed.\n- Got it ! changed the way I was storing item in local storage from `localStorage.setItem('field-obj',this.fields)` to `localStorage.setItem('field-obj',JSON.stringify(this.fields)‌​)` and accessed it by `this.fields = JSON.parse(localStorage.getItem('field-obj'))` and it worked completely fine.\n- basically I was storing fieldObj inside another object , hence fieldObj was inaccessible; `JSON.parse(JSON.parse(JSON.stringify(localStorage.getItem('f‌​ield-obj'))))` worked completely fine too...\n- Yep, this is usually the issue with this kind of error.\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:07.893Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":122,"estimatedTokens":869}}781{"id":"stack-66251277","source":"stackoverflow","questionId":66251277,"title":"Nuxt Leaflet, change tile layer requests incorrect tiles","tags":["leaflet","nuxt.js","vue2leaflet"],"text":"Title: Nuxt Leaflet, change tile layer requests incorrect tiles\nTags: leaflet, nuxt.js, vue2leaflet\nSource: Stack Overflow\n\nQuestion:\nI am using Nuxt Leaflet, and I have not figured out how to change the tile layer. I have tried multiple different approaches, and they all result with not requesting the proper tiles for the changed layer.\n\nHere is an example:\n\n```\n\n \n\n```\n\nIf I change the `mapTileUrl` value to a different url, it requests the following tile urls:\nhttps://wc-maps.s3.amazonaws.com/map-tiles-no-ocean/-1/0/0.png\n\nIf I do a conditional tile layer like this, I get the same result:\n\n```\n\n \n \n\n \n \nI have also tried using `L` object to add the new tile layer, and still get the same result. Anyone know why it is not requesting the proper tile urls?\n\n========================================\n\nCode:\n```html\n<l-map\n id=\"maps-lmap\"\n ref=\"lmap\"\n style=\"width:100%; height:100%\"\n :zoom=\"mapZoom\"\n :center=\"mapCenter\"\n :options=\"mapOptions\"\n :min-zoom=\"minZoom\"\n :max-zoom=\"maxZoom\"\n @update:center=\"mapCenterUpdate\"\n @update:zoom=\"mapZoomUpdate\"\n @update:bounds=\"mapBoundsUpdate\"\n>\n <l-tile-layer\n :url=\"mapTileUrl\"\n :attribution=\"mapAttribution\"\n :tile-size=\"512\"\n :options=\"{'zoomOffset':-1}\"\n />\n</l-map>\n```\n\n```html\n<template v-if=\"mapType === typeA\">\n <l-tile-layer\n :url=\"tileUrlA\"\n ...\n >\n </l-tile-layer>\n</template>\n<template v-else>\n <l-tile-layer\n :url=\"tileUrlB\"\n ...\n >\n </l-tile-layer>\n</template\n```\n\n```text\nmapTileUrl\n```\n\n```text\nL\n```\n\n```text\nmapTileUrl\n```\n\n```text\ntileSize\n```\n\n```text\nzoomOffset\n```\n\n========================================\n\nComments:\n- This seems to be the unfortunate case. I wish I could work with the mixed size map layers, but this doesn't seem possible.","metadata":{"transformedAt":"2026-08-18T18:33:07.893Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":96,"estimatedTokens":439}}782{"id":"stack-64077307","source":"stackoverflow","questionId":64077307,"title":"Vuetify Nuxt.js : how to add url link in image tag","tags":["vue.js","vuejs2","vue-component","nuxt.js","vuetify.js"],"text":"Title: Vuetify Nuxt.js : how to add url link in image tag\nTags: vue.js, vuejs2, vue-component, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\ni am new in Nuxt.js and Vuetifiy i want to add url link in image tag. if i press image it should open other page link\n\n**my page layout**\n\nhttps://i.sstatic.net/CR0MC.png\n**i have specified urls each image have different url like i want to add this url to image**\n\n```\nto=\"/AppMain/Support/Support\" \nand\n to=\"/UserDash/Profile\" \nalso\n to=\"/AppMain/Entertainment\"\n how to add this urls in image\n```\n\nmy code\n\n```\n\n \n \n \n \n \n \n \n {{ images.caption }}\n \n \n \n \n \n \n \n \n \n export default {\n name: \"playground\",\n data: () => ({\n slides: [\n {\n images: [\n { src: \"https://akam.cdn.jdmagicbox.com/images/icontent/newwap/newprotmore/hkm_allcategories.svg\", caption: \"All Categories\"},\n { src: \"https://akam.cdn.jdmagicbox.com/images/icontent/newwap/newprotmore/hkm_b2b.svg\", caption: \"B2B\" },\n { src: \"https://akam.cdn.jdmagicbox.com/images/icontent/newwap/newprotmore/hkm_shopping.svg\", caption: \"Shopping\" }\n \n ]\n },\n```\n\n========================================\n\nCode:\n```text\nto=\"/AppMain/Support/Support\" \nand\n to=\"/UserDash/Profile\" \nalso\n to=\"/AppMain/Entertainment\"\n how to add this urls in image\n```\n\n```html\n<template>\n <v-layout style=\"width: auto;\" class=\"ma-auto\">\n <v-carousel cycle light height=\"309\" hide-delimiter-background show-arrows-on-hover>\n <v-carousel-item v-for=\"(slide, i) in slides\" :key=\"i\">\n <v-row>\n <v-col cols=\"3\" v-for=\"(images, j) in slide.images\" :key=\"j\">\n <div class=\"d-flex flex-column justify-center align-center\">\n <v-img :src=\"images.src\" width=\"30\"/>\n <span class=\"mx-auto text-center caption\">{{ images.caption }}</span>\n </div>\n </v-col>\n </v-row>\n </v-carousel-item>\n </v-carousel>\n </v-layout>\n </template>\n \n <script>\n export default {\n name: \"playground\",\n data: () => ({\n slides: [\n {\n images: [\n { src: \"https://akam.cdn.jdmagicbox.com/images/icontent/newwap/newprotmore/hkm_allcategories.svg\", caption: \"All Categories\"},\n { src: \"https://akam.cdn.jdmagicbox.com/images/icontent/newwap/newprotmore/hkm_b2b.svg\", caption: \"B2B\" },\n { src: \"https://akam.cdn.jdmagicbox.com/images/icontent/newwap/newprotmore/hkm_shopping.svg\", caption: \"Shopping\" }\n \n ]\n },\n```\n\n```html\n<nuxt-link to=\"#\">\n <v-img :src=\"images.src\" width=\"30\"/>\n</nuxt-link>\n```\n\n```html\n<nuxt-link :to=\"images.url\">\n```\n\n```text\n<nuxt-link />\n```\n\n```text\nslide.images\n```\n\n========================================\n\nComments:\n- is there possible to you answer my another question regarding nuxt.js image uploading please reply\n- @user12380208 what's the question url?\n- thank you for replying my question url stackoverflow.com/questions/64182413/… in this question i am not added image file input for better under stand of my question. thank you\n- this is not working with nuxtjs3 and vuetify3 : where logo is in public folder\n- @cyril what is the error?\n- no error, just nothing appears :/","metadata":{"transformedAt":"2026-08-18T18:33:07.893Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":128,"estimatedTokens":808}}783{"id":"stack-63366607","source":"stackoverflow","questionId":63366607,"title":"AWS Amplify - CognitoIdentityCredentials is not authorized to perform: sts:AssumeRole on resource","tags":["amazon-web-services","nuxt.js","amazon-cognito","amazon-iam","aws-sts"],"text":"Title: AWS Amplify - CognitoIdentityCredentials is not authorized to perform: sts:AssumeRole on resource\nTags: amazon-web-services, nuxt.js, amazon-cognito, amazon-iam, aws-sts\nSource: Stack Overflow\n\nQuestion:\nI have an Amplify App using Nuxt. When a user logs in via cognito the app tries to use STS to transfer to another role to get a QuickSight Dashboard Embed Url following this AWS blog post.\n\nSo I have a role with this policy:\n\n```\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Action\": \"quicksight:GetDashboardEmbedUrl\",\n \"Resource\": \"arn:aws:quicksight:us-west-2:xxxxxxxx:dashboard/xxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxxx\",\n \"Effect\": \"Allow\"\n }\n ]\n}\n```\n\nand I added this policy to my app-authenticated-role\n\n```\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": {\n \"Effect\": \"Allow\",\n \"Action\": \"sts:AssumeRole\",\n \"Resource\": \"arn:aws:iam::xxxxxxxxx:role/embed_role_name\"\n }\n}\n```\n\nWhen they log in via cognito I attempt to assume the embed_role with STS\n\nwith:\n\n```\nlet params = {\n RoleArn: QS_EMBED_ROLE,\n RoleSessionName: \"embedding-qs\",\n};\n\nlet sts = new AWS.STS();\n\nsts.assumeRole(params, function (err, data) {\n if (err) console.log(err, err.stack);\n // an error occurred\n else {\n console.log(data);\n }\n});\n```\n\nI get this error:\n\nAccessDenied: User: arn:aws:sts::xxxxxxxxxx:assumed-role/app-authenticated-role/CognitoIdentityCredentials is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::xxxxxxxxxxxxx:role/embed_role\n\nIt seems pretty straight-forward in the docs so I'm not sure if I'm just not understanding something.\n\nAlso, in the course of trying a million things I think I edited the Trust Relationships for both the app-authenticated-role and embed-role and am not sure if it matters one way or the other.\n\nThe app-authenticated-role trust policy is:\n\n```\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Federated\": \"cognito-identity.amazonaws.com\"\n },\n \"Action\": \"sts:AssumeRoleWithWebIdentity\",\n \"Condition\": {\n \"StringEquals\": {\n \"cognito-identity.amazonaws.com:aud\": \"us-east-2:xxxxxxxx-xxxxxx-xxxxxx-xxxx-xxxxxxxx\"\n },\n \"ForAnyValue:StringLike\": {\n \"cognito-identity.amazonaws.com:amr\": \"authenticated\"\n }\n }\n }\n ]\n}\n```\n\nand the embed_role trust policy is:\n\n```\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Federated\": \"cognito-identity.amazonaws.com\"\n },\n \"Action\": \"sts:AssumeRoleWithWebIdentity\",\n \"Condition\": {\n \"StringEquals\": {\n \"cognito-identity.amazonaws.com:aud\": \"us-east-2:xxxxxxxx-xxxxxx-xxxxxx-xxxx-xxxxxxxx\"\n }\n }\n }\n ]\n}\n```\n\n========================================\n\nTop Answer:\nIf you are using a Cognito Identity Pool to map an authenticated user to an IAM role, then rather than call `sts:AssumeRole` directly, you would normally use `AWS.CognitoIdentityCredentials()` to get IAM credentials for your web identity.\n\nThis makes 2 calls behind the scenes. Firstly, it uses the given Login (a JWT token from an Identity Provider such as Cognito User Pools, Facebook, Google, etc) to create a new identity, or retrieve an existing one. Secondly, it will call `sts:AssumeRoleWithWebIdentity` on your behalf and return IAM credentials.\n\nThis is all described in the Cognito Identity Pool docs.\n\nSo your authenticated role trust policy would be:\n\n```\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Federated\": \"cognito-identity.amazonaws.com\"\n },\n \"Action\": \"sts:AssumeRoleWithWebIdentity\",\n \"Condition\": {\n \"StringEquals\": {\n \"cognito-identity.amazonaws.com:aud\": \"us-east-2:xxxxxxxx-xxxxxx-xxxxxx-xxxx-xxxxxxxx\"\n },\n \"ForAnyValue:StringLike\": {\n \"cognito-identity.amazonaws.com:amr\": \"authenticated\"\n }\n }\n }\n ]\n}\n```\n\nwhich states that Cognito Identity can call STS to get credentials on behalf of a web identity.\n\nThe permissions policy associated with that role would be:\n\n```\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Action\": \"quicksight:GetDashboardEmbedUrl\",\n \"Resource\": \"arn:aws:quicksight:us-west-2:xxxxxxxx:dashboard/xxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxxx\",\n \"Effect\": \"Allow\"\n }\n ]\n}\n```\n\nplus whatever other permissions your web user should have.\n\n========================================\n\nCode:\n```text\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Action\": \"quicksight:GetDashboardEmbedUrl\",\n \"Resource\": \"arn:aws:quicksight:us-west-2:xxxxxxxx:dashboard/xxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxxx\",\n \"Effect\": \"Allow\"\n }\n ]\n}\n```\n\n```text\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": {\n \"Effect\": \"Allow\",\n \"Action\": \"sts:AssumeRole\",\n \"Resource\": \"arn:aws:iam::xxxxxxxxx:role/embed_role_name\"\n }\n}\n```\n\n```text\nlet params = {\n RoleArn: QS_EMBED_ROLE,\n RoleSessionName: \"embedding-qs\",\n};\n\nlet sts = new AWS.STS();\n\nsts.assumeRole(params, function (err, data) {\n if (err) console.log(err, err.stack);\n // an error occurred\n else {\n console.log(data);\n }\n});\n```\n\n```text\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Federated\": \"cognito-identity.amazonaws.com\"\n },\n \"Action\": \"sts:AssumeRoleWithWebIdentity\",\n \"Condition\": {\n \"StringEquals\": {\n \"cognito-identity.amazonaws.com:aud\": \"us-east-2:xxxxxxxx-xxxxxx-xxxxxx-xxxx-xxxxxxxx\"\n },\n \"ForAnyValue:StringLike\": {\n \"cognito-identity.amazonaws.com:amr\": \"authenticated\"\n }\n }\n }\n ]\n}\n```\n\n```text\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Federated\": \"cognito-identity.amazonaws.com\"\n },\n \"Action\": \"sts:AssumeRoleWithWebIdentity\",\n \"Condition\": {\n \"StringEquals\": {\n \"cognito-identity.amazonaws.com:aud\": \"us-east-2:xxxxxxxx-xxxxxx-xxxxxx-xxxx-xxxxxxxx\"\n }\n }\n }\n ]\n}\n```\n\n```text\n\"Action\": \"sts:AssumeRole\"\n```\n\n```text\n\"Action\": \"sts:AssumeRoleWithWebIdentity\"\n```\n\n```text\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Federated\": \"cognito-identity.amazonaws.com\"\n },\n \"Action\": \"sts:AssumeRoleWithWebIdentity\",\n \"Condition\": {\n \"StringEquals\": {\n \"cognito-identity.amazonaws.com:aud\": \"us-east-2:xxxxxxxx-xxxxxx-xxxxxx-xxxx-xxxxxxxx\"\n },\n \"ForAnyValue:StringLike\": {\n \"cognito-identity.amazonaws.com:amr\": \"authenticated\"\n }\n }\n }\n ]\n}\n```\n\n```text\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Action\": \"quicksight:GetDashboardEmbedUrl\",\n \"Resource\": \"arn:aws:quicksight:us-west-2:xxxxxxxx:dashboard/xxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxxx\",\n \"Effect\": \"Allow\"\n }\n ]\n}\n```\n\n```text\nsts:AssumeRole\n```\n\n```text\nAWS.CognitoIdentityCredentials()\n```\n\n```text\nsts:AssumeRoleWithWebIdentity\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":306,"estimatedTokens":1717}}784{"id":"stack-66723441","source":"stackoverflow","questionId":66723441,"title":"NuxtJS and multilevel human-readable filters","tags":["javascript","seo","nuxt.js"],"text":"Title: NuxtJS and multilevel human-readable filters\nTags: javascript, seo, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nGood day to all!\n\nI'm facing a big problem that I can't find an approach to.\n\nIn short - I would like to be able to generate multi-level routes of previously unknown length to create filters.\n\nMore details\nThere is a website site.com\n\nIt has sections: **site.com/news**, **site.com/articles** and so on. For simplicity, I will denote them as **site.com/section**\n\nEach section has categories: **site.com/news/people**, **site.com/articles/how**. For simplicity, I will denote them as **site.com/section/category**\n\nThe number of sections and categories can be more than one piece\n\nWhen a user goes to a section, they see the entire list of posts in that section.\n\nWhen the user goes to the category of the section, he sees only the news inside the category.\n\nThere are several such sections, so I set **@nuxt/routejs** to disable routing based on the pages directory.\nThe route.js looks like this\n\n```\nVue.use(Router)\n\nexport function createRouter() {\n return new Router({\n mode: 'history',\n routes: [\n // Home page of the site\n {\n path: '/',\n component: BasePage,\n },\n // Page with a section\n {\n name: 'section',\n path: '/:section',\n component: PostBase,\n },\n // Also a page with a section, but with pagination taken into account\n {\n name: 'section-page',\n path: '/:section/page/:page',\n component: PostBase,\n },\n // Category page inside the section\n {\n name: 'category',\n path: '/:section/:category',\n component: PostBase,\n },\n // Category page inside the section, but with pagination taken into account\n {\n name: 'category-page',\n path: '/:section/:category/page/:page',\n component: PostBase,\n },\n ]\n })\n}\n```\n\nAnd then I don't know how to solve the problem properly.\nI want to give the user the ability to use a \"smart filter\" that is as close to SEO recommendations as possible.\nFor example, it can use a single filter and get this:\n\nsite.com/news/sorting-date\n\nAnd can get it:\n\nsite.con/news/sorting-date/author-elisa/page/4\n\nOr is it:\n\nsite.com/news/people/sorting-views/city-new-york/page/2\n\nI could give more examples, but I think it is clear from the three that with an unknown number of filters (which I set through the admin panel), there may be an unknown number of slashes.\n\nWhat should I do? How to solve this problem correctly?\n\nI also apologize for a very bad English. I really hope for your help or even tips :)\n\n========================================\n\nCode:\n```text\nVue.use(Router)\n\nexport function createRouter() {\n return new Router({\n mode: 'history',\n routes: [\n // Home page of the site\n {\n path: '/',\n component: BasePage,\n },\n // Page with a section\n {\n name: 'section',\n path: '/:section',\n component: PostBase,\n },\n // Also a page with a section, but with pagination taken into account\n {\n name: 'section-page',\n path: '/:section/page/:page',\n component: PostBase,\n },\n // Category page inside the section\n {\n name: 'category',\n path: '/:section/:category',\n component: PostBase,\n },\n // Category page inside the section, but with pagination taken into account\n {\n name: 'category-page',\n path: '/:section/:category/page/:page',\n component: PostBase,\n },\n ]\n })\n}\n```\n\n```text\n{\n name: 'category',\n path: '/:section/:category/:filters*', // or :filters+ if you want at least one\n component: PostBase,\n},\n```\n\n```text\nthis.$route.params.filters\n```\n\n```text\n\"sorting-views/city-new-york/page/2\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":147,"estimatedTokens":909}}785{"id":"stack-63806420","source":"stackoverflow","questionId":63806420,"title":"VueComponent.mounted : TypeError: Cannot read property 'get' of undefined in mounted hook","tags":["unit-testing","vue.js","jestjs","nuxt.js","vue-test-utils"],"text":"Title: VueComponent.mounted : TypeError: Cannot read property 'get' of undefined in mounted hook\nTags: unit-testing, vue.js, jestjs, nuxt.js, vue-test-utils\nSource: Stack Overflow\n\nQuestion:\nI am using jest for unit testing in nuxt js\nI have mounted hook like this\n\n\r\n\r\n\n```\nasync mounted(){\n \n try{\n var response = await this.$axios.get(\"api_url here\");\n this.result = response.data;\n } catch(e){\n console.log(\"Exception: \",e)\n }\n}\n```\n\n\r\n\r\n\r\n\nwhen i do unit test for it my code is . utnit.spec.js\n\n\r\n\r\n\n```\njest.mock(\"axios\", () => ({\n get: () => Promise.resolve({ data: [{ val: 1 }] })\n}));\n\nimport { mount } from '@vue/test-utils';\nimport file from '../filefile';\nimport axios from \"axios\";\n\ndescribe('file', () => {\n test('check comp. working correctly', () => {\n var wrapper = mount(file);\n afterEach(() => {\n wrapper.destroy()\n })\n }) \n})\n```\n\n\r\n\r\n\r\n\nI am getting this warn there and there is no data in the results\n\n\r\n\r\n\n```\nException: TypeError: Cannot read property 'get' of undefined\n at VueComponent.mounted\n```\n\n\r\n\r\n\r\n\nhow do I know what is the problem here, is this I can not access axios in the unit file Is there any specific way to test Axios in mounted hook\n\n========================================\n\nCode:\n```js\nasync mounted(){\n \n try{\n var response = await this.$axios.get(\"api_url here\");\n this.result = response.data;\n } catch(e){\n console.log(\"Exception: \",e)\n }\n}\n```\n\n```js\njest.mock(\"axios\", () => ({\n get: () => Promise.resolve({ data: [{ val: 1 }] })\n}));\n\n\nimport { mount } from '@vue/test-utils';\nimport file from '../filefile';\nimport axios from \"axios\";\n\n\ndescribe('file', () => {\n test('check comp. working correctly', () => {\n var wrapper = mount(file);\n afterEach(() => {\n wrapper.destroy()\n })\n }) \n})\n```\n\n```js\nException: TypeError: Cannot read property 'get' of undefined\n at VueComponent.mounted\n```\n\n```text\nvar wrapper = mount(file, { mocks: { $axios: axios } });\n```\n\n```text\njest.mock(\"axios\", () => Object.assign(\n jest.fn(),\n { get: jest.fn() }\n));\n```\n\n```text\nthis.$axios.get\n```\n\n```text\naxios.get\n```\n\n```text\nlocalVue\n```\n\n```text\naxios()\n```\n\n```text\naxios.get\n```\n\n```text\nPromise.resolve({ data: ... })\n```\n\n========================================\n\nComments:\n- You have to mock axios\n- I have mock axios like this jest.mock(\"axios\", () => ({ get: () => Promise.resolve({ data: [{ val: 1 }] }) })); but the same issue\n- thanks a lot now when i do console.log(wrapper.vm.res) i got ... [ { val: [Getter/Setter] } ] so would you suggest me where i can read about all jest fn or brief about it\n- or like i can set value of promise after reslove what will i get\n- wrapper.vm.res is not provided in the question and isn't related to Axios problem. Console output means that res is an array of objects. See jestjs.io/docs/en/mock-function-api and possibly other mock-related chapters. You need to do `axios.get.mockResolvedValueOnce({ data: ... })` in-place before its expected call.\n- my Bad! so wrapper.vm.result is . [ { val: [Getter/Setter] } ] , what is mean by that . and also i have done what changes you suggest and after jest.mock(\"axios\", () => Object.assign( jest.fn(), { get: jest.fn() } )); i code axios.get.mockResolvedValueOnce({ data: {val :1 }) but even after that i;m not getting the [ { val: [Getter/Setter] } ] , so did not get how to resolve it , and thank very much for answering would you help me out please\n- res is an array that was provided by the mock, this means that it was mocked correctly, and component parts that rely on it should work ok. res is transformed by Vue to make it reactive, this is the reason why it looks like that in console output. See vuejs.org/v2/guide/reactivity.html for how this works.\n- so i change my code a bit like await axios.get.mockResolvedValueOnce({ data: ... })in it/test block and after it i did console.log(wrapper.vm.res) and got undefined value and also getting in axios request in page cannot read data of undefined how it can be possible\n- axios.get.mockResolvedValueOnce goes before it's called, i.e. before mount. No `await` is needed there. If you need to wait for it to apply, you need to expose the promise to await, should be instead `let mockRes = Promise.resolve({ data ... }); axios.get.mockValueOnce(mockRes); var wrapper=mount(...); await mockRes`. At this point res should be applied to the component.\n- Let us continue this discussion in chat.\n- no problem ..is there any other way where i can show you code , and take feedback from you what should be done exactly ,\n- You can add a new snippet that shows your current attempt to the question (in addition to existing ones) or show a link to Codesandbox or Stackblitz.","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":162,"estimatedTokens":1175}}786{"id":"stack-62843716","source":"stackoverflow","questionId":62843716,"title":"Check nuxt-child is empty or not","tags":["vue.js","nuxt.js"],"text":"Title: Check nuxt-child is empty or not\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIs there any way to check `nuxt-child` or native `router-view` has childs or not? for instance I wanted to show a div if `nuxt-child` was empty/or didn't not set.\n\n```\n\n Choose something to start...\n\n```\n\nAny ideas?\n\n========================================\n\nCode:\n```text\n<div v-if=\" nuxt-child == null \">\n Choose something to start...\n</div>\n\n<nuxt-child />\n```\n\n```text\nnuxt-child\n```\n\n```text\nrouter-view\n```\n\n```text\nnuxt-child\n```\n\n```text\n<div v-if=\"this.$route.matched.length\">\n Choose something to start...\n</div>\n```\n\n========================================\n\nComments:\n- Maybe if you can use the $emit function to pass to parent component some data. for instance, on created function, make any tests, and if the test are null return false. This way can be? Maybe I can provide some code to you.","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":48,"estimatedTokens":227}}787{"id":"stack-65367821","source":"stackoverflow","questionId":65367821,"title":"ECONNREFUSED when dispatch action in nuxtServerInit","tags":["javascript","vue.js","nuxt.js"],"text":"Title: ECONNREFUSED when dispatch action in nuxtServerInit\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am converting my Nuxt application to SSR - because I want to use `nuxtServerInit` and `asyncData`. These are the steps I have taken to convert it.\n\n- Remove `ssr: false` from `nuxt.config.js`\n\n- Dispatch actions to initialize store's state in `nuxtServerInit` inside `store/index.js`\n\nNow my `nuxt.config.js` looks like this\n\n```\nrequire(\"dotenv\").config({ path: `.env.${process.env.NODE_ENV}` });\n\nexport default {\n router: {\n base: \"/app/\",\n },\n target: \"static\",\n head: {\n // Some head, meta, link config\n },\n css: [\"@/assets/scss/main.scss\"],\n styleResources: {\n scss: [\"@/assets/scss/*.scss\", \"@/assets/scss/main.scss\"],\n },\n plugins: [\"@/plugins/apiFactory.js\"],\n components: true,\n buildModules: [\n \"@nuxtjs/eslint-module\",\n [\"@nuxtjs/dotenv\", { filename: `.env.${process.env.NODE_ENV}` }],\n ],\n modules: [\n \"bootstrap-vue/nuxt\",\n \"@nuxtjs/style-resources\",\n [\"nuxt-sass-resources-loader\", \"@/assets/scss/main.scss\"],\n ],\n build: {\n splitChunks: {\n layouts: true,\n },\n },\n};\n```\n\nAnd the `store/index.js` looks like this.\n\n```\nimport axios from \"axios\";\n\nexport const state = () => ({\n data: [],\n});\n\nexport const mutations = {\n setData(state, data) {\n state.data = data;\n },\n};\n\nexport const actions = {\n async nuxtServerInit({ dispatch }) {\n // Before converting to SSR this action was dispatched in page/component that need this data\n await dispatch(\"fetchData\");\n },\n async fetchData({ commit }) {\n const { data } = await axios.get(\"http://localhost:3030/my/api/path\");\n commit(\"setData\", data);\n },\n};\n\nexport const getters = { /* some getters */ };\n```\n\nBut after I restarted the development server - I was greeted with `connect ECONNREFUSED 127.0.0.1:3030`\n\nhttps://i.sstatic.net/CTHhT.png\n\nThese are the steps I've taken after that\n\n- Check if the API on `localhost:3030` is running and accessible - It's running and accessible via direct URL and Postman\n\n- Comment out the `// await dispatch(\"fetchData\");` in `nuxtServerInit` - restarted the dev server - site is accessible again but without initial data.\n\nSo, I suspected that the action dispatched in `nuxtServerInit` cause the problem - If it is how do I fix this problem or where should I look into next? Please let me know, Thanks!\n\nAdditional Information\n\n- The API on `localhost:3030` is Lumen version 7.2.2\n\n- The application will be deployed on shared hosting\n\n========================================\n\nTop Answer:\nIf you have your own server add your api domain in hosts file (in linux /etc/hosts)\n\n```\n127.0.0.1 api.domain.com\n```\n\nI was struggling for 2 days to understand why it wasn`t working and then it hit me pm2 server side has access only locally.\n\n========================================\n\nCode:\n```js\nrequire(\"dotenv\").config({ path: `.env.${process.env.NODE_ENV}` });\n\nexport default {\n router: {\n base: \"/app/\",\n },\n target: \"static\",\n head: {\n // Some head, meta, link config\n },\n css: [\"@/assets/scss/main.scss\"],\n styleResources: {\n scss: [\"@/assets/scss/*.scss\", \"@/assets/scss/main.scss\"],\n },\n plugins: [\"@/plugins/apiFactory.js\"],\n components: true,\n buildModules: [\n \"@nuxtjs/eslint-module\",\n [\"@nuxtjs/dotenv\", { filename: `.env.${process.env.NODE_ENV}` }],\n ],\n modules: [\n \"bootstrap-vue/nuxt\",\n \"@nuxtjs/style-resources\",\n [\"nuxt-sass-resources-loader\", \"@/assets/scss/main.scss\"],\n ],\n build: {\n splitChunks: {\n layouts: true,\n },\n },\n};\n```\n\n```text\nimport axios from \"axios\";\n\nexport const state = () => ({\n data: [],\n});\n\nexport const mutations = {\n setData(state, data) {\n state.data = data;\n },\n};\n\nexport const actions = {\n async nuxtServerInit({ dispatch }) {\n // Before converting to SSR this action was dispatched in page/component that need this data\n await dispatch(\"fetchData\");\n },\n async fetchData({ commit }) {\n const { data } = await axios.get(\"http://localhost:3030/my/api/path\");\n commit(\"setData\", data);\n },\n};\n\nexport const getters = { /* some getters */ };\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nasyncData\n```\n\n```text\nssr: false\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nstore/index.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nstore/index.js\n```\n\n```text\nconnect ECONNREFUSED 127.0.0.1:3030\n```\n\n```text\nlocalhost:3030\n```\n\n```text\n// await dispatch(\"fetchData\");\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nlocalhost:3030\n```\n\n```text\nconst axiosPlugin: Plugin = ({ $axios, isDev }) => {\n if (isDev && process.server) $axios.setBaseURL('http://172.22.0.1:3000/api')\n}\n```\n\n```text\n127.0.0.1 api.domain.com\n```\n\n```text\naxios: {\n baseURL: 'http://localhost:5000',\n },\n```\n\n```text\nyarn run dev --port 5000\n```\n\n========================================\n\nComments:\n- Have you found a solution for this in the meantime? I am experiencing the same problem. Everywhere in the nuxt components the axios API call goes through, only in the index.js store inside nuxtServerInit I get an Error: connect ECONNREFUSED 127.0.0.1 ... Cheers Tim","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":249,"estimatedTokens":1280}}788{"id":"stack-65198995","source":"stackoverflow","questionId":65198995,"title":"removing event listeners in Nuxt/Vue","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: removing event listeners in Nuxt/Vue\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm on Nuxtjs 2.13 and i wanna know \"how should I remove event listeners (is there a need??)\".\n\nI'm not talkinkg about js `addEventListener` and `removeEventListener` . I'm more curious about `this.$emit()` , `$nuxt.$emit()` and `$nuxt.$on()` . is there a way to remove `$nuxt.$on()` or listener on component `` in `beforeDestroy()` and is it necessary?\n\nas my Nuxt project using so much RAM on my server, i kindda think there are some optimization needed.\n\n========================================\n\nCode:\n```text\naddEventListener\n```\n\n```text\nremoveEventListener\n```\n\n```text\nthis.$emit()\n```\n\n```text\n$nuxt.$emit()\n```\n\n```text\n$nuxt.$on()\n```\n\n```text\n$nuxt.$on()\n```\n\n```text\n<mycomp @myevent=\"do()\" />\n```\n\n```text\nbeforeDestroy()\n```\n\n```text\nvm.$off\n```\n\n```text\n$nuxt.$on\n```\n\n```text\n$nuxt.$off\n```\n\n========================================\n\nComments:\n- I think Nuxt automatically remove all events that declared by \"v-on\" directive when the components un-mounted","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":62,"estimatedTokens":270}}789{"id":"stack-60733465","source":"stackoverflow","questionId":60733465,"title":"How to use vue plugin in nuxt","tags":["vue.js","nuxt.js"],"text":"Title: How to use vue plugin in nuxt\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nThere's a plugin called vue-chat-scroll and I would like to use it in nuxt. Am a beginner so I cant really understand how but I wonder if its possible to use this vue plugin in nuxt as plugin. how would one do that?\n\n========================================\n\nTop Answer:\nCreate a file inside plugins folder, for example, vue-chat-scroll.js with the following content:\n\n```\nimport Vue from 'vue'\nimport VueChatScroll from 'vue-chat-scroll'\nVue.use(VueChatScroll)\n```\n\nIn nuxt.config.js import the plugin as \n\n```\nplugins: [...your existing plugins,'~/plugins/vue-chat-scroll.js']\n```\n\nand then the plugin tutorial for its API\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue';\nimport VueChatScroll from 'vue-chat-scroll';\n\n Vue.component('VueChatScroll', VueChatScroll);\n```\n\n```text\nplugins: [\n {\n src: '~/plugins/vue-chat-scroll.js',\n ssr: true\n }\n]\n```\n\n```text\nimport Vue from 'vue'\nimport VueChatScroll from 'vue-chat-scroll'\nVue.use(VueChatScroll)\n```\n\n```text\nplugins: [...your existing plugins,'~/plugins/vue-chat-scroll.js']\n```\n\n========================================\n\nComments:\n- Please add some code with expected behavior\n- 'Vue.use' doesn't work for plugins in nuxt. You should use Vue.component('VueChatScroll', VueChatScroll);\n- github.com/theomessin/vue-chat-scroll The library is not a component it is a directive. Also if this is a component it is not good idea to register the component globally. I don't know why the answer marked as accepted .\n- yep. i tried both and your one throws error \"Failed to resolve directive: chat-scroll\" as we can clearly see the library is not a component . it is a vue custom directive .\n- btw, ssr: true is legacy code it will depreciated in upcoming release. you should use mode : 'client' or mode : 'server' default value is mode : 'server'\n- Throws error \"Failed to resolve directive: chat-scroll\".\n- Note that updating `nuxt.config.js` is no longer required in Nuxt@3","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":65,"estimatedTokens":515}}790{"id":"stack-66505570","source":"stackoverflow","questionId":66505570,"title":"nuxt auth-module \"User Data response does not contain field XXX\"","tags":["javascript","nuxt.js","nuxt-auth"],"text":"Title: nuxt auth-module \"User Data response does not contain field XXX\"\nTags: javascript, nuxt.js, nuxt-auth\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use nuxt-auth module, my settings for this module is\n\n```\nauth: {\n cookie: false,\n plugins: ['~/plugins/api.js'],\n redirect: {\n logout: '/login',\n login: '/',\n home: false\n },\n strategies: {\n local: {\n scheme: 'refresh',\n token: {\n property: 'token',\n maxAge: 3600\n },\n refreshToken: {\n property: 'refresh_token',\n data: 'refresh_token',\n maxAge: 60 * 60 * 24 * 30\n },\n user: {\n property: 'userDetail'\n },\n endpoints: {\n login: { url: 'http://localhost:8085/api/login_check', method: 'post', propertyName: 'token' },\n refresh: { url: 'http://localhost:8085/api/token/refresh', method: 'post', propertyName: 'refresh_token' },\n logout: false,\n user: { url: 'http://localhost:8085/api/user/fetchactive', method: 'get' }\n },\n tokenRequired: true\n }\n }\n }\n```\n\nMy \"fetchactive\" API returns a JSON containing a property \"userDetail\" which is a string containing the email address, (I also tried to make userDetail an object but with no luck).\n\ne.g.\n\n```\n{\"userDetail\":{\"email\":\"my@email.test\"}}\n```\n\nNuxt auth keeps telling me that \"User Data response does not contain field userDetail\".\n\nI also tried to set \"property\" to false, but Nuxt auth in that cases looks for a field named \"false\"...\nI just can't get it to work.\n\nAnyone can help?\n\n========================================\n\nTop Answer:\nusing this configuration in the nuxt.config.js file worked for me\n\n\r\n\r\n\n```\nauth: {\n strategies: {\n local: {\n user: {\n property: ''\n },\n //other configs\n }\n }\n //other configs\n }\n```\n\n========================================\n\nCode:\n```text\nauth: {\n cookie: false,\n plugins: ['~/plugins/api.js'],\n redirect: {\n logout: '/login',\n login: '/',\n home: false\n },\n strategies: {\n local: {\n scheme: 'refresh',\n token: {\n property: 'token',\n maxAge: 3600\n },\n refreshToken: {\n property: 'refresh_token',\n data: 'refresh_token',\n maxAge: 60 * 60 * 24 * 30\n },\n user: {\n property: 'userDetail'\n },\n endpoints: {\n login: { url: 'http://localhost:8085/api/login_check', method: 'post', propertyName: 'token' },\n refresh: { url: 'http://localhost:8085/api/token/refresh', method: 'post', propertyName: 'refresh_token' },\n logout: false,\n user: { url: 'http://localhost:8085/api/user/fetchactive', method: 'get' }\n },\n tokenRequired: true\n }\n }\n }\n```\n\n```text\n{\"userDetail\":{\"email\":\"my@email.test\"}}\n```\n\n```text\nendpoints: {\n user: { url: 'http://localhost:8085/api/user/fetchactive', method: 'get', propertyName: '' }\n }\n }\n```\n\n```html\nauth: {\n strategies: {\n local: {\n user: {\n property: ''\n },\n //other configs\n }\n }\n //other configs\n }\n```\n\n========================================\n\nComments:\n- I tried your solution but it still does not work. It keeps looking for other property names. I guess it's a bug. I'll go for a manual fetch for user detail and put user: false in the nuxt config... thanks\n- Don't do it manually if You use nuxt.auth. Ok hm.... so this is the response from You API: `{\"userDetail\":{\"email\":\"my@email.test\"}}` ? You can't have 'user' object in ''strategies.local' and in ''strategies.local.endpoints' . Have it in just one place?? Just leave the user object in 'strategies.local.endpoints' and there set propertyName:''\n- I already tried this but no luck... Were you able to test this and did you get it working?\n- Yes, I had same situation in my Nuxt project, and handled it in that way. Also have spent long time to find a solution, but tried many things and found this solution to use empty string in \"propertyName\"\n- @sangio90 have You handled it? try to set { property: false or '' } see helpful link stackoverflow.com/a/55986884/10900851 or github.com/nuxt-community/auth-module/issues/…\n- Sadly I tried them all, I tried propertyName: false, propertyName: '', property: false, property: '' but still it looks for that \"user\" field in my response. It does the XHR call properly and it retrieves the user info correctly, but it ignores it and looks for a \"user\" field. I also tried to change the API to provide a user field in my data, still not working.\n- I finally got it working by debugging the cod. the issue was this: My backend sends a response which seems not to have \"data\" field, so response.data.anything will always crash because response.data is undefined. What is strange is that both my login and user API do not expose DATA field, I had to manually add it to the user api, in the login API response.data was valid even without setting it manually.\n- @sangio90 ahh! great to hear it :) I'm glad that You didn't gave up, good luck with the rest of the project. :)","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":155,"estimatedTokens":1235}}791{"id":"stack-63188983","source":"stackoverflow","questionId":63188983,"title":"Nuxt.js - ssr, Error Cannot set headers after they are sent to the client","tags":["nuxt.js"],"text":"Title: Nuxt.js - ssr, Error Cannot set headers after they are sent to the client\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am having this problem in nuxt.js-ssr environment.\n\n```\nERROR Cannot set headers after they are sent to the client \n at ServerResponse.setHeader (_http_outgoing.js:535:11)\n at p (node_modules/cookie-universal/dist/cookie-universal-common.js:1:1399)\n at Object.set (node_modules/cookie-universal/dist/cookie-universal-common.js:1:1836)\n at pages/index.js:145:21\n at processTicksAndRejections (internal/process/task_queues.js:97:5)\n```\n\nThe reason?\nOccurs when nuxt fetch(SSR) calls API and writes cookie information in response\n\n```\nprotected async fetch() {\n axios.get('https://api.onstove.com/test/test')\n .then((value: AxiosResponse) => {\n console.log('data ::', value.data);\n })\n .then(() => {\n console.log('cookie before ===> ', this.$cookies.get('T1'));\n this.$cookies.set('T1', 'test122sdfdsfsfds34342');\n console.log('cookie after ===> ', this.$cookies.get('T1'));\n });\n```\n\n}\n\nLet me know if anyone solved it.\n\n========================================\n\nCode:\n```text\nERROR Cannot set headers after they are sent to the client \n at ServerResponse.setHeader (_http_outgoing.js:535:11)\n at p (node_modules/cookie-universal/dist/cookie-universal-common.js:1:1399)\n at Object.set (node_modules/cookie-universal/dist/cookie-universal-common.js:1:1836)\n at pages/index.js:145:21\n at processTicksAndRejections (internal/process/task_queues.js:97:5)\n```\n\n```text\nprotected async fetch() {\n axios.get('https://api.onstove.com/test/test')\n .then((value: AxiosResponse<Test>) => {\n console.log('data ::', value.data);\n })\n .then(() => {\n console.log('cookie before ===> ', this.$cookies.get('T1'));\n this.$cookies.set('T1', 'test122sdfdsfsfds34342');\n console.log('cookie after ===> ', this.$cookies.get('T1'));\n });\n```\n\n```text\nprotected async fetch() {\n return axios.get('https://api.onstove.com/test/test')\n .then((value: AxiosResponse<Test>) => {\n console.log('data ::', value.data);\n })\n .then(() => {\n console.log('cookie before ===> ', this.$cookies.get('T1'));\n this.$cookies.set('T1', 'test122sdfdsfsfds34342');\n console.log('cookie after ===> ', this.$cookies.get('T1'));\n });\n```\n\n========================================\n\nComments:\n- may I know how you import use that $cookies?\n- I believe OP was using npmjs.com/package/vue-cookies\n- thank you very much. I just resolved my problem by your hint.","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":80,"estimatedTokens":633}}792{"id":"stack-60085863","source":"stackoverflow","questionId":60085863,"title":"Testing a NUXT.js and Vue.js app with Jest. Getting '[vuex] module namespace not found in mapState()' and '[vuex] unknown action type'","tags":["javascript","vue.js","jestjs","vuex","nuxt.js"],"text":"Title: Testing a NUXT.js and Vue.js app with Jest. Getting '[vuex] module namespace not found in mapState()' and '[vuex] unknown action type'\nTags: javascript, vue.js, jestjs, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn spite of my understanding that NUXT does namespacing automatically. Because of this, I am unable to test or reference the store in any of my testing modules. Can anyone give me a tip? Maybe where I can edit the namespacing property in a Nuxt app?\n\nHere is the code below for the component, store, and the test.\n\nButtonComponent.vue:\n\n```\n\n \n \n \n\nimport { mapState, mapActions } from 'vuex'\n\nexport default {\n data: {\n return {\n value: 25\n }\n }\n methods: {\n buttonClick(event) {\n this.$store.dispatch('buttonComponent/setNewValue', valuePassedIn)\n },\n },\n}\n\n```\n\nbuttonComponent.spec.js:\n\n```\nimport Component from '../../Component'\nimport { mount, createLocalVue } from '@vue/test-utils'\nimport expect from 'expect'\nimport Vue from 'vue'\nimport Vuex from 'vuex'\nimport Vuetify from 'vuetify'\n\nconst localVue = createLocalVue()\nlocalVue.use(Vuex)\nVue.use(Vuetify)\n\ndescribe('Component', () => {\n let store\n let vuetify\n let actions\n beforeEach(() => {\n actions = {\n actionClick: jest.fn()\n }\n store = new Vuex.Store({\n actions,\n })\n vuetify = new Vuetify()\n })\n\n it('method sends value to store when button is clicked', async () => {\n const wrapper = mount(Component, {\n store,\n localVue,\n vuetify,\n })\n wrapper.find('.v-btn').trigger('click')\n expect(actions.actionClick).toHaveBeenCalledWith('buttonComponent/setNewValue', 25)\n })\n})\n```\n\nbuttonComponent.js:\n\n```\nexport const state = () => ({\n value: 0,\n})\n\nexport const mutations = {\n SET_TO_NEW_VALUE(state, value) {\n state.value = value\n },\n}\n\nexport const actions = {\n setNewValue({ commit }, value) {\n commit('SET_TO_NEW_VALUE', value)\n },\n}\n```\n\n========================================\n\nCode:\n```text\n<template>\n <v-container>\n <v-btn @buttonClick v-model=\"value\"></v-btn>\n </v-container>\n</template>\n\n<script>\nimport { mapState, mapActions } from 'vuex'\n\nexport default {\n data: {\n return {\n value: 25\n }\n }\n methods: {\n buttonClick(event) {\n this.$store.dispatch('buttonComponent/setNewValue', valuePassedIn)\n },\n },\n}\n</script>\n\n<style scoped></style>\n```\n\n```text\nimport Component from '../../Component'\nimport { mount, createLocalVue } from '@vue/test-utils'\nimport expect from 'expect'\nimport Vue from 'vue'\nimport Vuex from 'vuex'\nimport Vuetify from 'vuetify'\n\nconst localVue = createLocalVue()\nlocalVue.use(Vuex)\nVue.use(Vuetify)\n\ndescribe('Component', () => {\n let store\n let vuetify\n let actions\n beforeEach(() => {\n actions = {\n actionClick: jest.fn()\n }\n store = new Vuex.Store({\n actions,\n })\n vuetify = new Vuetify()\n })\n\n\n\n it('method sends value to store when button is clicked', async () => {\n const wrapper = mount(Component, {\n store,\n localVue,\n vuetify,\n })\n wrapper.find('.v-btn').trigger('click')\n expect(actions.actionClick).toHaveBeenCalledWith('buttonComponent/setNewValue', 25)\n })\n})\n```\n\n```text\nexport const state = () => ({\n value: 0,\n})\n\nexport const mutations = {\n SET_TO_NEW_VALUE(state, value) {\n state.value = value\n },\n}\n\nexport const actions = {\n setNewValue({ commit }, value) {\n commit('SET_TO_NEW_VALUE', value)\n },\n}\n```\n\n========================================\n\nComments:\n- It takes about 5 seconds to run 1 test on my machine using the nuxt builder. A better option is to mock the nuxt store.\n- @ioan mocking behavior within your own codebase is a terrible idea. There should have been a better way to do this.","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":187,"estimatedTokens":914}}793{"id":"stack-60489682","source":"stackoverflow","questionId":60489682,"title":"How can I use a leaflet marker as nuxt-link?","tags":["javascript","vue.js","leaflet","vue-router","nuxt.js"],"text":"Title: How can I use a leaflet marker as nuxt-link?\nTags: javascript, vue.js, leaflet, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI started to use nuxt and vue-leaflet for an interactive map and i am very new to it.\n\nThe Map contains multiple Markers for different Locations.\nWhen the user clicks on a marker the respective page should open.\nCurrently a popup opens which contains the link. \n\n```\n\n \n {{\n location.characterName\n }}\n \n \n```\n\nbut i don't want to use a popup and than the link, I want the link to open when the user clicks on the marker.\nSadly this code doesn't work:\n\n```\n\n \n \n \n```\n\nThanks for any helps and have a good day :)\nChris\n\n========================================\n\nCode:\n```html\n<l-marker\n v-for=\"(location, index) in allLocations\"\n :key=\"index\"\n :lat-lng=\"location.latlng\"\n >\n <l-popup>\n <nuxt-link :to=\"getLink(location)\">{{\n location.characterName\n }}</nuxt-link>\n </l-popup>\n </l-marker>\n```\n\n```html\n<nuxt-link\n v-for=\"(location, index) in allLocations\"\n :key=\"index\"\n :to=\"getLink(location)\"\n v-slot=\"{ href, navigate }\"\n >\n <l-marker :lat-lng=\"location.latlng\" :href=\"href\" @click=\"navigate\">\n </l-marker>\n </nuxt-link>\n```\n\n========================================\n\nComments:\n- thanks that worked :) actually you just have to use router.push(\"page2\")","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":67,"estimatedTokens":356}}794{"id":"stack-59409517","source":"stackoverflow","questionId":59409517,"title":"Nuxt how to debug: The client-side rendered virtual DOM tree is not matching server-rendered content","tags":["server-side-rendering","nuxt.js"],"text":"Title: Nuxt how to debug: The client-side rendered virtual DOM tree is not matching server-rendered content\nTags: server-side-rendering, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSo in my Nuxt *universal-mode* app, I sometimes have an error which rises:\n\n```\nvue.runtime.esm.js:620 [Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside , or missing . Bailing hydration and performing full client-side render.\n```\n\nWhich usually comes along a second one (actually the second one sometimes rises without the first, not the other way round):\n\n```\nTypeError: Cannot read property 'toLowerCase' of undefined\n at emptyNodeAt (vue.runtime.esm.js:5851)\n at VueComponent.patch [as __patch__] (vue.runtime.esm.js:6492)\n at VueComponent.Vue._update (vue.runtime.esm.js:3933)\n at VueComponent.updateComponent (vue.runtime.esm.js:4048)\n at Watcher.get (vue.runtime.esm.js:4467)\n at new Watcher (vue.runtime.esm.js:4456)\n at mountComponent (vue.runtime.esm.js:4061)\n at VueComponent.Vue.$mount (vue.runtime.esm.js:8399)\n at init (vue.runtime.esm.js:3115)\n at hydrate (vue.runtime.esm.js:6362)\n```\n\nAnd then nothing works, since when I click to another page in my app, I get:\n\n```\nclient.js:134 TypeError: Cannot read property '_transitionClasses' of undefined\n at Array.updateClass (vue.runtime.esm.js:6799)\n at patchVnode (vue.runtime.esm.js:6298)\n at updateChildren (vue.runtime.esm.js:6177)\n at patchVnode (vue.runtime.esm.js:6303)\n at updateChildren (vue.runtime.esm.js:6177)\n at patchVnode (vue.runtime.esm.js:6303)\n at updateChildren (vue.runtime.esm.js:6177)\n at patchVnode (vue.runtime.esm.js:6303)\n at updateChildren (vue.runtime.esm.js:6177)\n at patchVnode (vue.runtime.esm.js:6303)\n```\n\nI mostly understand the *why* this happens, though when it comes, I have no idea where to start from, since the error message doesn't give a single hint on what **actually are** the differences between the server-side version and the client one.\n\nSo when this issue rises, the only thing I can do is to rollback to previous git commits until the issues fixes itself ... which unfortunately doesn't work very well, as sometimes the bug appears on code versions where it was not there previously.\n\nUsually the solution is to delete as many things as possible (`.nuxt`, `node_install`) and to set up everything from scratch and hopefully it works again.\n\nFinally my remarks/questions are:\n\n- When the `client-side version doesn't match the server-side` bug appears, why can't we have more detailed informations on **what differences**?\n\n- Any idea why this bug happens as a whole in such non-deterministic manner?\n\n- Why is this breaking everything, while at first this is simply a warning?\n\nAs for me this is a very big issue for a production app, as being so undeterministically fixable.\n\n========================================\n\nCode:\n```text\nvue.runtime.esm.js:620 [Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.\n```\n\n```text\nTypeError: Cannot read property 'toLowerCase' of undefined\n at emptyNodeAt (vue.runtime.esm.js:5851)\n at VueComponent.patch [as __patch__] (vue.runtime.esm.js:6492)\n at VueComponent.Vue._update (vue.runtime.esm.js:3933)\n at VueComponent.updateComponent (vue.runtime.esm.js:4048)\n at Watcher.get (vue.runtime.esm.js:4467)\n at new Watcher (vue.runtime.esm.js:4456)\n at mountComponent (vue.runtime.esm.js:4061)\n at VueComponent.Vue.$mount (vue.runtime.esm.js:8399)\n at init (vue.runtime.esm.js:3115)\n at hydrate (vue.runtime.esm.js:6362)\n```\n\n```text\nclient.js:134 TypeError: Cannot read property '_transitionClasses' of undefined\n at Array.updateClass (vue.runtime.esm.js:6799)\n at patchVnode (vue.runtime.esm.js:6298)\n at updateChildren (vue.runtime.esm.js:6177)\n at patchVnode (vue.runtime.esm.js:6303)\n at updateChildren (vue.runtime.esm.js:6177)\n at patchVnode (vue.runtime.esm.js:6303)\n at updateChildren (vue.runtime.esm.js:6177)\n at patchVnode (vue.runtime.esm.js:6303)\n at updateChildren (vue.runtime.esm.js:6177)\n at patchVnode (vue.runtime.esm.js:6303)\n```\n\n```text\n.nuxt\n```\n\n```text\nnode_install\n```\n\n```text\nclient-side version doesn't match the server-side\n```\n\n```text\nTypeError: Cannot read property 'toLowerCase' of undefined\n```\n\n```text\nThe client-side rendered virtual DOM tree is not matching server-rendered content\n```\n\n```text\nTypeError: Cannot read property 'toLowerCase' of undefined\n```\n\n```text\ndate-fns\n```\n\n========================================\n\nComments:\n- I've found that this can happen due to any invalid HTML syntax or structure on the page, not necessarily just in the component that's not matching. For example, placing a inside of a caused an extra #text element on server-side and was forcing hydration bail in a hard-to-trace manner.\n- Thanks for posting your solution. Commenting out worked for me (I had an a tag inside a nuxt-link tag).","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":127,"estimatedTokens":1304}}795{"id":"stack-65815006","source":"stackoverflow","questionId":65815006,"title":"Said cons to using Next.js don't seem like they would be any different from other SSR frameworks","tags":["reactjs","nuxt.js","next.js","nestjs","server-side-rendering"],"text":"Title: Said cons to using Next.js don't seem like they would be any different from other SSR frameworks\nTags: reactjs, nuxt.js, next.js, nestjs, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nI've yet to take a deep dive into SSR until now, but I'm about jump in, and first doing some preliminary research to try to get me and the agency going in the most-likely best direction. This is one of the determining factors in choosing Angular, React, or Vue as the company's choice in F/E frameworks which will become our go-to. As it has come to seem like React and Next are likely the best way forward for us at this time. I'm focusing on a few said cons of using Next, as they are things that I want to make sure are not deal breakers.\n\nIn one particular article comparing Next, Nuxt, and Nest, I am seeing a bullet point where it says that \"Next.js is not backend\". Elsewhere it's mentioned that Next should be supplemented with a Node.js server for a backend. My question to this is, is that suggesting that Nuxt and Nest *are* backend? So there wouldn't ever be any reason to supplement Nuxt and Nest with Node or another server? That doesn't seem to me like it would *usually* or *always* be the case. Like somehow Nuxt and Nest are so amazing that they handle most or all of the server needs you would ever have? It doesn't seem like that's necessarily their purpose... Or is it?\n\nIn the same article there are similarly three other bullet points as cons for Next that I have a hard time seeing how the other two frameworks would be any different. The other points are:\n\n• If you’re creating a simple app, it can be overkill\n\n• All data needs to be loadable from both the client and server\n\n• Migrating a server-side app to Next.js is not a quick process, and depending on your project it may be too much work\n\n- More so than the other SSRs?\n\n- It seems like every SSR and frontend would need to load from the client and server. Isn't that the point?\n\n- It seems like migrating any backend to F/E and SSR would not be a quick process.\n\nI could be wrong, but it seems like these considerations were breezed over in the writing of the page. There would be good reason for noting these cons against the other frameworks just to not give the impression that Next is necessarily a miracle against the other two where development and migration were always going to be a breeze.\n\nObviously as a SO question, we would like to avoid opinion weighing in here, which this question seems like it might attract. I am looking for *specific* information about ways to make me believe Nuxt and Nest are advantageous over Next in these few regards.\n\nI realize that people who could speak to every one of these SSR frameworks are probably scarce, but if you can speak to one or the other, that would still be very helpful.\n\nAdditionally, the article was written in April of 2019, and things may well have changed.\n\n========================================\n\nCode:\n```text\nprocess.browser\n```\n\n========================================\n\nComments:\n- VERY helpful. Ty both.\n- Don't forget to accept the answer if this helped.","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":43,"estimatedTokens":779}}796{"id":"stack-60933290","source":"stackoverflow","questionId":60933290,"title":"Nuxt Auth doesn't work with Google strategie","tags":["authentication","google-oauth","nuxt.js"],"text":"Title: Nuxt Auth doesn't work with Google strategie\nTags: authentication, google-oauth, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement a Google authentication in front of a Nuxt website. I using the community Auth module with the buid-in google strategie. Actually, the authentication is working perfectly in localhost but it's not working when the website is online. Sometime, Google responds with a 401 error (for invalid credentials).\n\nHere is what look like my `nuxt.config.js` file:\n\n```\nexport default {\n mode: 'spa',\n\n modules: [\n \"@nuxtjs/axios\",\n \"@nuxtjs/auth\",\n \"@nuxtjs/vuetify\",\n ],\n\n auth: {\n strategies:{\n google: {\n client_id:\n \"XXXXXXXX-xxxxxxxxxxxxxxx.apps.googleusercontent.com\"\n }\n },\n redirect: {\n login: '/login',\n logout: '/login',\n home: '/',\n callback: '/callback'\n }\n }\n}\n```\n\nAnd here my `login.vue` page :\n\n```\n\n Login with Google\n\n export default {\n middleware: ['auth'],\n methods: {\n consoleLog(text) {\n if (this.log !== null) {\n this.log += text + \"\\n\";\n } else {\n this.log = text + \"\\n\";\n }\n },\n async loginClicked() {\n try {\n let res = await this.$auth.loginWith('google');\n console.log(\"login result: \" + res);\n } catch (err) {\n this.consoleLog(\"login error: \" + err);\n }\n }\n }\n }\n\n```\n\n========================================\n\nTop Answer:\n```\ngoogle: {\nclientId: '............................................apps.googleusercontent.com',\nscope: ['profile', 'email'],\ncodeChallengeMethod: '',\nresponseType: 'token id_token',\n}\n```\n\nThis worked for me :)\n\n========================================\n\nCode:\n```js\nexport default {\n mode: 'spa',\n\n modules: [\n \"@nuxtjs/axios\",\n \"@nuxtjs/auth\",\n \"@nuxtjs/vuetify\",\n ],\n\n auth: {\n strategies:{\n google: {\n client_id:\n \"XXXXXXXX-xxxxxxxxxxxxxxx.apps.googleusercontent.com\"\n }\n },\n redirect: {\n login: '/login',\n logout: '/login',\n home: '/',\n callback: '/callback'\n }\n }\n}\n```\n\n```js\n<template>\n <v-btn @click=\"loginClicked()\">Login with Google</v-btn>\n</template>\n\n<script>\n export default {\n middleware: ['auth'],\n methods: {\n consoleLog(text) {\n if (this.log !== null) {\n this.log += text + \"\\n\";\n } else {\n this.log = text + \"\\n\";\n }\n },\n async loginClicked() {\n try {\n let res = await this.$auth.loginWith('google');\n console.log(\"login result: \" + res);\n } catch (err) {\n this.consoleLog(\"login error: \" + err);\n }\n }\n }\n }\n</script>\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nlogin.vue\n```\n\n```text\ngoogle: {\nclientId: '............................................apps.googleusercontent.com',\nscope: ['profile', 'email'],\ncodeChallengeMethod: '',\nresponseType: 'token id_token',\n}\n```\n\n========================================\n\nComments:\n- Could you please article or source of code from where I can make google auth work? Struggling for days, and still no result. Thank you in advance\n- There is an already accepted answer from over a year ago. Can you please add more clarification to your answer about why it is helpful or how you came to it?","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":160,"estimatedTokens":801}}797{"id":"stack-61638549","source":"stackoverflow","questionId":61638549,"title":"(Vue-router) Route with name 'abc' does not exist when redirect another page with parameter in NuxtJS","tags":["vue.js","vuejs2","nuxt.js","vue-router"],"text":"Title: (Vue-router) Route with name 'abc' does not exist when redirect another page with parameter in NuxtJS\nTags: vue.js, vuejs2, nuxt.js, vue-router\nSource: Stack Overflow\n\nQuestion:\nI'm building project with NuxtJs(SSR type). I want to pass param when redirect another page. Based on Nuxtjs documentation, this is my structure folder\n\n```\npages/\n--| product/\n-----| productlist.vue\n-----| productadd.vue\n-----| productedit/\n----------| _id.vue\n```\n\nIn `productlist.vue`, i want to redirect to `productedit/{id}` when click edit button, i used Nuxt-link to do it\n\n```\n\n mdi-pencil\n\n```\n\nHowever i always get page **404 Not Found** and console log `[vue-router] Route with name 'productedit-id' does not exist`\n\nI don't understand why? I don't know what i missed. Please help me and i'm so grateful\n\n========================================\n\nCode:\n```text\npages/\n--| product/\n-----| productlist.vue\n-----| productadd.vue\n-----| productedit/\n----------| _id.vue\n```\n\n```text\n<v-btn class=\"mr-2\" small color=\"primary\" nuxt :to=\"{ name: 'productedit-id', params: { id: item.id } }\">\n <v-icon>mdi-pencil</v-icon>\n</v-btn>\n```\n\n```text\nproductlist.vue\n```\n\n```text\nproductedit/{id}\n```\n\n```text\n[vue-router] Route with name 'productedit-id' does not exist\n```\n\n```text\n:to=\"{ name: 'product-productedit-id', params: { id: item.id } }\"\n```\n\n```text\n:to=\"`/product/productedit/`+item.id\"\n```\n\n========================================\n\nComments:\n- Can you (or check) the `name` values in your `/.nuxt/router.js` file? Do you use a module like nuxt-i18n that override the router values?\n- hi Mohsen, thank you but both solutions not work for me :(\n- i tried base your solutions but still always 404 :(\n- in your build folder, open `router.js` and check that route with your name exist\n- i have one more small question, in `_id.vue` i want to get param from url, this is my code but it not work `data() { return { productId: this.$route.params.id, product: {} }; },`\n- Did you try to set `productId` in mounted? what will show if put `{{$route.params}}` in template of `_id.vue` ?\n- i puted `productId` in `mounted` and it work good for me, thank you for your enthusiastic assistance","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":76,"estimatedTokens":547}}798{"id":"stack-51224224","source":"stackoverflow","questionId":51224224,"title":"Passing Data in asyncData Nuxt.js","tags":["nuxt.js"],"text":"Title: Passing Data in asyncData Nuxt.js\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm new to nuxt.js and I want to ask if there is any way to pass data in asyncData.\nHere is the code.\n\n```\n\n import axios from 'axios'\n export default {\n data(){\n return {\n sample: 'asdf',\n baseUrl: 'https://jsonplaceholder.typicode.com/posts/1'\n }\n },\n async asyncData ({ params }) {\n let { data } = await axios.get(this.baseUrl)\n return { title: data}\n }\n}\n\n```\n\nI know you don't have access to `this` but is there a way to pass data. Thanks.\n\n========================================\n\nCode:\n```text\n<script type=\"text/javascript\">\n import axios from 'axios'\n export default {\n data(){\n return {\n sample: 'asdf',\n baseUrl: 'https://jsonplaceholder.typicode.com/posts/1'\n }\n },\n async asyncData ({ params }) {\n let { data } = await axios.get(this.baseUrl)\n return { title: data}\n }\n}\n</script>\n```\n\n```text\nthis\n```\n\n```text\n// nuxt.config.js\n env: {\n baseUrl: process.env.BASE_URL || 'http://localhost:3000'\n }\n```\n\n```text\nasync asyncData ({ params }) {\n let { data } = await axios.get(process.env.baseUrl)\n return { title: data}\n}\n```\n\n```text\nimport axios from 'axios'\n\nexport default axios.create({\n baseURL: process.env.baseUrl\n})\n```\n\n========================================\n\nComments:\n- pass data from where?\n- in the asyncData, look at `this.baseUrl` in `axios.get(this.baseUrl)` it's invalid. How can I pass it? Thanks.\n- you cant pass it from data. You can only use objects from context. Like params, or store. You can put anything in store and access it from asyncDAta\n- I see, I know now... so my global data need to pass in the store and it's accessible in the `context.store` or es6 `{ store }`. Thanks..\n- well. for global data you use process.env\n- Can you give me example about how to use process.env.. I used `global.js` and used `Vue.prototype.$g =` but the problem is you can't access `this` in asyncData.\n- You can also access env directly `asyncData({ env })`","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":85,"estimatedTokens":510}}799{"id":"stack-56915064","source":"stackoverflow","questionId":56915064,"title":"Nuxt auth getToken witnin async is undefined","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Nuxt auth getToken witnin async is undefined\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to fetch some data from user and I need to pass bearer token within call.\n\n```\nasync asyncData () {\n let response = await axios.get('dataURL', {}, { headers: {\"Authorization\" : `Bearer ${this.$auth.getToken('local')}`} })\n },\n```\n\nBut this doesn't work, it always says that $auth is undefined, while within template I can easily output any $auth property...\n\nHow can I get bearer token within async?\n\n========================================\n\nTop Answer:\nMaybe you can try to pass the context (this) , after your call?\n\nE.g:\n\nawait axios.get('dataURL', {}, { headers: {\"Authorization\" : `Bearer ${this.$auth.getToken('local')}`} }),this;\n\n========================================\n\nCode:\n```text\nasync asyncData () {\n let response = await axios.get('dataURL', {}, { headers: {\"Authorization\" : `Bearer ${this.$auth.getToken('local')}`} })\n },\n```\n\n```text\nasync asyncData (context) {\n let response = await axios.get('dataURL', {}, { headers: {\"Authorization\" : `Bearer ${context.app.$auth.getToken('local')}`} })\n },\n```\n\n```text\nasync asyncData (context) {\n let { response } = await axios.get('dataURL', {}, { headers: {\"Authorization\" : `Bearer ${context.app.$auth.getToken('local')}`} })\n return { token: response }\n },\n```\n\n```text\nawait axios.get('dataURL', {}, { headers: {\"Authorization\" : `Bearer ${this.$auth.getToken('local')}`} }),this;\n```\n\n```text\nasync asyncData (app) {\n let response = await axios.get('dataURL', {}, { headers: {\"Authorization\" : `Bearer ${app.$auth.getToken('local')}`} });\n},\n```\n\n========================================\n\nComments:\n- Make sure `this` is what you think it is.\n- @Titus Okay this is not usable within async. How can I get a cookie that is set from nuxt/auth module?\n- You can use `this` in an `async` function. You can set the function's context (what `this` refers to inside the function) using `bind` or `call` or `apply`. Here is an example: `someObject.asyncData.call(objectWith$authProp)`","metadata":{"transformedAt":"2026-08-18T18:33:07.894Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":64,"estimatedTokens":523}}800{"id":"stack-53302905","source":"stackoverflow","questionId":53302905,"title":"Access Nuxt plugins in .js files","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Access Nuxt plugins in .js files\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nLet's say that I have a script file, `foo.js`:\n\n```\nfunction doStuff() {\n // how to access store and other plugins here?\n}\n\nexport default { doStuff }\n```\n\nWithout passing the calling component as an argument, how can I access things like `app` or installed plugins like `store`, `i18n` in a script file like the one above?\n\n========================================\n\nCode:\n```text\nfunction doStuff() {\n // how to access store and other plugins here?\n}\n\nexport default { doStuff }\n```\n\n```text\nfoo.js\n```\n\n```text\napp\n```\n\n```text\nstore\n```\n\n```text\ni18n\n```\n\n```text\nconst customHelpers = {\n methods: {\n doStuff () {\n // this will be referenced to component it is executed in\n }\n }\n}\n```\n\n```text\n// component.vue\nimport customHelpers from '~/mixins/customHelpers'\nexport default {\n mixins: [customHelpers],\n mounted () {\n this.doStuff()\n }\n}\n```\n\n```text\nimport Vue from 'vue'\n\nVue.prototype.$doStuff = () => { /* stuff happens here */ }\n```\n\n```text\nexport default {\n ..., // other nuxt options\n plugins: ['~/plugins/customHelpers.js']\n}\n```\n\n```text\nexport default {\n mounted () {\n this.$doStuff()\n }\n}\n```\n\n```text\nexport default ({ app }, inject) => {\n inject('doStuff', () => { /* stuff happens here */ })\n}\n```\n\n```text\nexport default {\n ..., // other nuxt options\n plugins: ['~/plugins/customHelpers.js']\n}\n```\n\n```text\nexport default {\n asyncData ({ app }) {\n app.$doStuff()\n }\n}\n```\n\n```text\nthis\n```\n\n```text\nthis.customMethod\n```\n\n```text\ncustomHelpers.js\n```\n\n```text\ncomponent.vue\n```\n\n```text\nplugins/customHelpers.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nthis\n```\n\n```text\nplugins/customHelpers.js\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- Please, elaborate why default plugin format doesn't work for you? `export default ({ app, store }) => { /* plugin code */ }`\n- @aBiscuit Because the script file is not a plugin\n- Where does `doStuff` is expected to be called from? Components, store or other places? This may help to determine better approach of implementation.\n- @aBiscuit Sorry for not being clear about that. Mainly from components. I would like to avoid `doStuff(this)`, `doStuff.call(this)` etc.\n- Thanks for your examples. Let's say that I don't want to define a plugin or mixin, and simply want to access the store or similar inside `customHelpers.js`. Is that possible?\n- Taking a step back.. Generally, what you want to do is to have a function with dynamically bound context. There has to be an access point for context. It can be done right in place of invocation (e.g. doStuff.bind(this), or assigning function directly to component's method, so Vue does binding for you), or it can be done through ways provided by environment you develop in - Nuxt.js in this case, which are listed above. I don't think there would be better options in terms of keeping logic maintainable and predictable.","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":24,"totalLines":160,"estimatedTokens":767}}801{"id":"stack-77496214","source":"stackoverflow","questionId":77496214,"title":"Where can arbitrary code be placed in Nuxt 3?","tags":["javascript","nuxt.js","nuxt3.js"],"text":"Title: Where can arbitrary code be placed in Nuxt 3?\nTags: javascript, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm facing confusion due to the different purposes of numerous folders in Nuxt 3. I want to store a simple food list array in a JavaScript file and export it, but I'm uncertain about the appropriate location to place this file.\n\nThis is my food.js file:\n\n```\nexport const food = ['apple', 'banana', 'some random fruit']\n```\n\nTypically, if I'm not using Nuxt 3, I would place the `food.js` file next to the component that will utilize it, like this:\n\n- `components/myFolder1/FoodView.vue`\n\n- `components/myFolder1/food.js`\n\nHowever, in Nuxt 3, this approach is no longer feasible as my `food.js` file will be automatically registered as a component due to Nuxt 3's mechanisms.\n\nPlacing `food.js` in the `composables/` folder doesn't make sense since it's just a static file.\n\nAlthough putting `food.js` in the `utils/` folder seems reasonable, the `utils/` folder doesn't scan nested folders for auto-registration. For instance:\n\nIf my `utils/` folder looks like this:\n\n- `utils/formatDate.js`\n\n- `utils/foodApp/food.js`\n\nNuxt 3 will only auto-import `formatDate.js` and ignore `food.js`. I would have to manually import `food.js`, which deviates from Nuxt 3 conventions and potentially complicates the project's comprehension. Additionally, the `utils/` folder isn't an ideal place to store this type of arbitrary code.\n\nHence, I'm seeking advice on the best location to store such arbitrary code in Nuxt 3.\n\n========================================\n\nCode:\n```js\nexport const food = ['apple', 'banana', 'some random fruit']\n```\n\n```text\nfood.js\n```\n\n```text\ncomponents/myFolder1/FoodView.vue\n```\n\n```text\ncomponents/myFolder1/food.js\n```\n\n```text\nfood.js\n```\n\n```text\nfood.js\n```\n\n```text\ncomposables/\n```\n\n```text\nfood.js\n```\n\n```text\nutils/\n```\n\n```text\nutils/\n```\n\n```text\nutils/\n```\n\n```text\nutils/formatDate.js\n```\n\n```text\nutils/foodApp/food.js\n```\n\n```text\nformatDate.js\n```\n\n```text\nfood.js\n```\n\n```text\nfood.js\n```\n\n```text\nutils/\n```\n\n```text\n// index.js\nexport { food } from './foodApp/food.js'\n```\n\n```text\nimports: {\n dirs: [\n 'utils/**'\n ]\n}\n```\n\n```text\n/utils\n```\n\n```text\n/utils/index.js\n```\n\n```text\ndefineNuxtConfig\n```\n\n```text\n/types\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":134,"estimatedTokens":572}}802{"id":"stack-76067809","source":"stackoverflow","questionId":76067809,"title":"'runtimeConfig' does not exist in type 'NuxtConfig'","tags":["typescript","vue.js","visual-studio-code","nuxt.js","nuxt3.js"],"text":"Title: 'runtimeConfig' does not exist in type 'NuxtConfig'\nTags: typescript, vue.js, visual-studio-code, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a Nuxt 3 project based on installation guide: https://nuxt.com/docs/getting-started/installation.\nI followed it step by step. But when i want to configure `nuxt.config.ts` and i paste sample config file from https://nuxt.com/docs/getting-started/configuration:\n\n```\nexport default defineNuxtConfig({\n runtimeConfig: {\n // The private keys which are only available server-side\n apiSecret: '123',\n // Keys within public are also exposed client-side\n public: {\n apiBase: '/api'\n }\n }\n})\n```\n\nI'm getting a typescript error:\n\n```\nArgument of type '{ runtimeConfig: { apiSecret: string; public: { apiBase: string; }; }; }' is not assignable to parameter of type 'NuxtConfig'.\n Object literal may only specify known properties, and 'runtimeConfig' does not exist in type 'NuxtConfig'.ts(2345)\n```\n\nI'm using node version 16.16.0 and Visual Studio Code is my IDE.\n\n========================================\n\nTop Answer:\nUpdate Typescript IntelliJ\n\nthe second solution to add\n\n```\n\"devDependencies\": {\n \"typescript\": \"5.0.4\"\n },\n```\n\nmade the tric, and intellij detected automatically the good version\n\n========================================\n\nCode:\n```text\nexport default defineNuxtConfig({\n runtimeConfig: {\n // The private keys which are only available server-side\n apiSecret: '123',\n // Keys within public are also exposed client-side\n public: {\n apiBase: '/api'\n }\n }\n})\n```\n\n```text\nArgument of type '{ runtimeConfig: { apiSecret: string; public: { apiBase: string; }; }; }' is not assignable to parameter of type 'NuxtConfig'.\n Object literal may only specify known properties, and 'runtimeConfig' does not exist in type 'NuxtConfig'.ts(2345)\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n\"devDependencies\": {\n \"typescript\": \"5.0.4\"\n },\n```\n\n```bash\nnpm install --save-dev @nuxtjs/tailwindcss\n```\n\n========================================\n\nComments:\n- I have the same problem, but my version of Nuxt it's a 5.0.4 what I need to change on VSC","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":84,"estimatedTokens":537}}803{"id":"stack-50793828","source":"stackoverflow","questionId":50793828,"title":"nuxt js build locally, and run on server of the production","tags":["nuxt.js"],"text":"Title: nuxt js build locally, and run on server of the production\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI build the project of nuxt js locally, i.e., `npm run build`, and push the project with .nuxt folder, but not the folder of node_modules. \nThen run the command of `npm run start`, failed.\n\nThe output info: \nsh: nuxt: command not found\n\nWhy?\n\n========================================\n\nCode:\n```text\nnpm run build\n```\n\n```text\nnpm run start\n```\n\n```text\n\"scripts\": {\n \"start\": \"nuxt start\",\n ...\n}\n```\n\n```text\nnpm run start\n```\n\n```text\npackage.json\n```\n\n```text\nnode_modules/nuxt/bin/nuxt start\n```\n\n```text\nnode_modules/\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":46,"estimatedTokens":162}}804{"id":"stack-77590950","source":"stackoverflow","questionId":77590950,"title":"Using cookies in Nuxt 3 APIs and Middlewares","tags":["javascript","vue.js","nuxt.js","server-side-rendering","nuxt3.js"],"text":"Title: Using cookies in Nuxt 3 APIs and Middlewares\nTags: javascript, vue.js, nuxt.js, server-side-rendering, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nIs there a way to use cookies on server side in Nuxt 3?\nFor example, I want to set cookie in API and then read its data in middleware:\n\n```\n// ~/server/api/testApi.ts\n\nexport default defineEventHandler(event => {\n /* setCookie('myCookie', 'myValue'); */\n});\n\n// ~/middleware/testMw.ts\n\nexport default defineNuxtRouteMiddleware((to, from) => {\n /* getCookie('myCookie'); */ // ~~> myValue\n});\n```\n\nI tried to set cookie with `useCookie` in API but it is `undefined` in middleware.\nI also don't understand how to use `getCookie` in middleware because it needs the `event` object which is not present in middleware.\n\n**Context**\n\nI want to create a very simple auth system. In `/api/auth.post.ts` I create some kind of token which is saved in cookie. Then, in order to check, whether visitor is logged in I need to somehow retrieve this token back from cookie in `/middleware/logged.ts`.\n\nI am open to other suggestions.\n\n========================================\n\nCode:\n```js\n// ~/server/api/testApi.ts\n\nexport default defineEventHandler(event => {\n /* setCookie('myCookie', 'myValue'); */\n});\n\n// ~/middleware/testMw.ts\n\nexport default defineNuxtRouteMiddleware((to, from) => {\n /* getCookie('myCookie'); */ // ~~> myValue\n});\n```\n\n```text\nuseCookie\n```\n\n```text\nundefined\n```\n\n```text\ngetCookie\n```\n\n```text\nevent\n```\n\n```text\n/api/auth.post.ts\n```\n\n```text\n/middleware/logged.ts\n```\n\n```text\n// store/theme.ts\n\nimport { defineStore } from 'pinia';\nimport Cookie from 'js-cookie'; // you can use any Cookie packages you want\n\nexport const useThemeStore = defineStore('theme', {\n state: () => ({\n _theme: {}\n }),\n getters: {\n theme: (state) => stats._theme\n },\n actions: {\n setTheme (value: 'light' | 'dark' | 'system') {\n // update the value in both cookie and memory\n this._theme = value;\n Cookie.set('theme', value);\n }\n }\n});\n```\n\n```text\n// plugin/initial.ts\n\nimport Cookie from 'js-cookie';\nimport { useThemeStore } from '~/stores/theme';\n\nfunction cookieFromRequestHeaders (key: string) {\n const headers = useRequestHeaders(['cookie']);\n if ('cookie' in headers) {\n const cookie = headers.cookie?.split(';').find(\n c => c.trim().startsWith(`${key}=`)\n );\n if (cookie) {\n return cookie.split('=')[1];\n }\n }\n return undefined;\n}\n\nexport default defineNuxtPlugin(async (nuxtApp) => {\n\n const theme = cookieFromRequestHeaders('theme') ?? Cookie.get('theme') ?? 'system';\n\n const themeStore = useThemeStore(nuxtApp.$pinia as Pinia);\n\n themeStore.setTheme(theme);\n});\n```\n\n```text\nimport { useThemeStore } from '~/stores/theme';\n\nexport default defineNuxtRouteMiddleware((to) => {\n\n const themeStore = useThemeStore();\n\n if (themeStore.theme === 'dark') {\n return navigateTo('/dark-index');\n }\n});\n```\n\n```text\n// plugin/initial.ts\n\nimport { useThemeStore } from '~/stores/theme';\n\nexport default defineNuxtPlugin(async (nuxtApp) => {\n\n const theme = useCookie<'system'|'light'|'dark'>('theme', {\n default: () => 'system',\n });\n\n const themeStore = useThemeStore(nuxtApp.$pinia as Pinia);\n\n themeStore.setTheme(theme);\n});\n```\n\n```text\npinia\n```\n\n```text\ntheme\n```\n\n========================================\n\nComments:\n- What is `useCookieStore` in plugin file? You mean `useThemeStore`? And I dont have `setAllow` method...\n- I replaced `useCookieStore` with my own store but in middleware using `useAuthStore` returns undefined.\n- @CMTV sorry for my carelessness, I've updated the answer\n- @CMTV for nuxt3 with auth in cookie and middlewares, here is a full example may help\n- Thank you I will look at your example! The store works in middleware though I can't get it to work in API. But I guess I can simply set token after an API request on client side just like in your example.\n- Thank you again after 3 hard days I finally managed to create custom auth system based on this answer and your example. Yeah, it is kind of ugly, but it works! :) I would suggest you to edit your answer and add a link to your auth example)\n- @CMTV Sure, I've updated the answer, feel free to star it :)","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":172,"estimatedTokens":1083}}805{"id":"stack-58704463","source":"stackoverflow","questionId":58704463,"title":"How to create a helper function in NuxtJs to use inside vuex and components?","tags":["vue.js","nuxt.js"],"text":"Title: How to create a helper function in NuxtJs to use inside vuex and components?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to create a plugin for Nuxtjs to log everything I want only in client mode, something like this : \n\n```\n// ~/plugins/client-log.js\nexport default ({ app }, inject) => {\n app.clog = string => console.log(string)\n}\n```\n\nThis plugin is working in components where I have access to context for example: \n\n```\nexport default {\n\n fetch({app}){\n app.clog(\"some string\")\n }\n};\n```\n\nBut I want to be able to use it inside vuex (actions, mutations...). How can I do that? \n\nThanks in advance.\n\n========================================\n\nCode:\n```text\n// ~/plugins/client-log.js\nexport default ({ app }, inject) => {\n app.clog = string => console.log(string)\n}\n```\n\n```text\nexport default {\n\n fetch({app}){\n app.clog(\"some string\")\n }\n};\n```\n\n```text\n// ~/plugins/client-log.js\nexport default ({ app }, inject) => {\n inject('clog', string => console.log(string))\n}\n```\n\n```text\nexport default {\n\n fetch({app}){\n // Note: inject will automatically prefix with a \"$\"\n app.$clog(\"some string\")\n },\n\n mounted() {\n // this.$clog can also be accessed within vuex\n this.$clog(\"I'm in a component\")\n }\n};\n```\n\n========================================\n\nComments:\n- Thank you, I still can not use it inside vuex actions or mutations, right?\n- My apologies, I've updated with how to access within a component/vuex","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":75,"estimatedTokens":369}}806{"id":"stack-69331638","source":"stackoverflow","questionId":69331638,"title":"What is the difference between @nuxtjs/google-gtag @nuxtjs/gtm @nuxtjs/google-analytics and vue-gtag, what to use for GA4?","tags":["vue.js","google-analytics","nuxt.js","google-analytics-4","gtag.js"],"text":"Title: What is the difference between @nuxtjs/google-gtag @nuxtjs/gtm @nuxtjs/google-analytics and vue-gtag, what to use for GA4?\nTags: vue.js, google-analytics, nuxt.js, google-analytics-4, gtag.js\nSource: Stack Overflow\n\nQuestion:\nNewbie to this whole analytics thing and am finding this very confusing\n\nI wanted to use Google Analytics 4 in my nuxt ssr webapp and am feeling overwhelmed with the number of options\n\nQuick issue on nuxtjs/google-analytics says it does not support GA4 and is asking me to use nuxt/gtm\n\nstackoverflow answer on the same question says use vue-gtag\n\nGoogle's documentation says it covers analytics ads etc\n\nnuxt/google-gtag seems to be another library apart from vue-gtag and nuxt/gtm\n\nwhat am I even supposed to use?\nI just want to integrate Google Analytics 4 on my nuxt.js SSR app\n\n========================================\n\nCode:\n```js\n// example config\n 'google-gtag':{\n id: 'G-XXXXXXXX', // your measurement id\n ... // rest of the config\n }\n```\n\n```text\nUA-XXXX-XX\n```\n\n```text\nG-XXXXXXXX\n```\n\n========================================\n\nComments:\n- This one may maybe help: stackoverflow.com/a/68504060/8816585\n- This issue can also help, here you can find the difference between the different modules / libraries, and what you should use according to your needs. github.com/nuxt-community/gtm-module/issues/82\n- This link says that the google-gtag is deprecated, instead gtm is the new one. stackoverflow.com/questions/65752819/…","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":45,"estimatedTokens":370}}807{"id":"stack-69001648","source":"stackoverflow","questionId":69001648,"title":"My border-bottom is not displayed in Vuetify","tags":["css","vue.js","nuxt.js","vuetify.js"],"text":"Title: My border-bottom is not displayed in Vuetify\nTags: css, vue.js, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nI'm developing a website in nuxt.js using Vuetify. I have created a app bar using v-app-bar and I want to add a white line under it. I wanted it because I will put links under the title as extension and I want to seperate them.\n\nI have tried v-divider; however, there is always a space between the divider and bottom line of the app-bar, and I can't set thickness and color of the divider.\n\n```\n\n \n \n \n \n Title\n \n \n \n \n \n \n\n```\n\nThen I tried it with the bottom border of v-app-bar__content, but border is not displayed. The code:\n\n```\n\n \n \n \n \n Title\n \n \n \n\n.v-toolbar__content{\n border-bottom-width: 2px;\n border-color: white;\n}\n\n```\n\nHow could I add a white line exatcly on bottom border of the app-bar__content?\n\n========================================\n\nCode:\n```html\n<v-app-bar\n color=\"black\"\n app\n>\n <v-row>\n <v-app-bar-nav-icon class=\"d-lg-none\"></v-app-bar-nav-icon>\n <v-spacer />\n <v-app-bar-title\n class=\"text-no-wrap text-h3\"\n style=\"width: fit-content;\">\n Title\n </v-app-bar-title>\n <v-spacer />\n <v-col\n cols=\"12\"\n class=\"pb-0 pt-1\">\n <v-divider></v-divider>\n </v-col>\n </v-row>\n</v-app-bar>\n```\n\n```html\n<template>\n <v-app-bar\n color=\"black\"\n app\n >\n <v-app-bar-nav-icon class=\"d-lg-none\"></v-app-bar-nav-icon>\n <v-spacer />\n <v-app-bar-title\n class=\"text-no-wrap text-h3\"\n style=\"width: fit-content;\">\n Title\n </v-app-bar-title>\n <v-spacer />\n </v-app-bar>\n</template>\n\n<style>\n.v-toolbar__content{\n border-bottom-width: 2px;\n border-color: white;\n}\n</style>\n```\n\n```css\nborder-bottom: 8px solid white;\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":101,"estimatedTokens":441}}808{"id":"stack-74769159","source":"stackoverflow","questionId":74769159,"title":"@nuxt/i18n installation/configuration issue","tags":["typescript","nuxt.js","nuxt-i18n"],"text":"Title: @nuxt/i18n installation/configuration issue\nTags: typescript, nuxt.js, nuxt-i18n\nSource: Stack Overflow\n\nQuestion:\nI tried to install `@nuxt/i18n` on my project but it doesn't work. I executed the command `npm install @nuxtjs/i18n` without problems. Then I added some lines of code in my `nuxt.config.ts` file:\n\n```\n['@nuxtjs/i18n', {\n locales: [\n {\n code: 'it',\n iso: 'it-IT',\n file: 'it-IT.js'\n }\n ],\n defaultLocale: 'it'\n}]\n```\n\nAnd in `tsconfig.json` I added this:\n\n```\n\"compilerOptions\": {\n \"types\": [\n \"@nuxt/types\",\n \"@nuxtjs/i18n\",\n ]\n}\n```\n\nNow, when I build the solution, I obtain this error:\n\n```\nCannot start nuxt: Cannot read properties of undefined (reading 'options')\nat _default (____________/node_modules/@nuxtjs/i18n/src/index.js:13:92)\nat installModule (____________/node_modules/@nuxt/kit/dist/index.mjs:416:9)\nat async initNuxt (____________/node_modules/nuxt/dist/index.mjs:1823:7)\nat async load (____________/node_modules/nuxt/node_modules/nuxi/dist/chunks/dev.mjs:6779:9)\nat async Object.invoke (____________/node_modules/nuxt/node_modules/nuxi/dist/chunks/dev.mjs:6840:5)\nat async _main (____________/node_modules/nuxt/node_modules/nuxi/dist/cli.mjs:50:20)\n```\n\nI followed the guide at this link: https://i18n.nuxtjs.org/setup\n\nProblem persist also without `locales` and `defaultLocale`. What's wrong with my configuration? What is missing?\n\n========================================\n\nTop Answer:\nYou need to add \"vue-i18n\" module...use i18n via plugin... this doc:- https://vue-i18n.intlify.dev/guide/integrations/nuxt3.html\n\n========================================\n\nCode:\n```text\n['@nuxtjs/i18n', {\n locales: [\n {\n code: 'it',\n iso: 'it-IT',\n file: 'it-IT.js'\n }\n ],\n defaultLocale: 'it'\n}]\n```\n\n```text\n\"compilerOptions\": {\n \"types\": [\n \"@nuxt/types\",\n \"@nuxtjs/i18n\",\n ]\n}\n```\n\n```text\nCannot start nuxt: Cannot read properties of undefined (reading 'options')\nat _default (____________/node_modules/@nuxtjs/i18n/src/index.js:13:92)\nat installModule (____________/node_modules/@nuxt/kit/dist/index.mjs:416:9)\nat async initNuxt (____________/node_modules/nuxt/dist/index.mjs:1823:7)\nat async load (____________/node_modules/nuxt/node_modules/nuxi/dist/chunks/dev.mjs:6779:9)\nat async Object.invoke (____________/node_modules/nuxt/node_modules/nuxi/dist/chunks/dev.mjs:6840:5)\nat async _main (____________/node_modules/nuxt/node_modules/nuxi/dist/cli.mjs:50:20)\n```\n\n```text\n@nuxt/i18n\n```\n\n```text\nnpm install @nuxtjs/i18n\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\nlocales\n```\n\n```text\ndefaultLocale\n```\n\n```text\nimport { createI18n } from 'vue-i18n'\n\nexport default defineNuxtPlugin(({ vueApp }) => {\n const i18n = createI18n({\n legacy: false,\n globalInjection: true,\n locale: 'it',\n messages: {\n en: {\n test: 'Hello, {name}!'\n },\n it: {\n test: 'Ciao, {name}!'\n }\n }\n })\n\n vueApp.use(i18n)\n})\n```\n\n```text\nmodules: [\n ...\n '@nuxtjs/i18n',\n ...\n],\n```\n\n```html\n<h1>{{ $t('test', { name: 'vue-i18n' }) }}</h1>\n```\n\n```text\ni18n\n```\n\n```text\n/plugins/i18n.ts\n```\n\n```text\nnuxt.config.ts\n```\n\n========================================\n\nComments:\n- My guess would be that it's an incompatibility between your version of Nuxt and the one of the module.\n- You can also check this issue: github.com/nuxt-modules/i18n/issues/2393\n- I don't see the point of this answer, while the accepted one is already precise and well-written. Please put in some effort if you want to help.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":165,"estimatedTokens":1036}}809{"id":"stack-75994162","source":"stackoverflow","questionId":75994162,"title":"Nuxt 3 SCSS internal error after every save or new SCSS file create","tags":["vue.js","sass","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: Nuxt 3 SCSS internal error after every save or new SCSS file create\nTags: vue.js, sass, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI have fresh nuxt3 project and I try to add some scss styling. I have two issues i want to discuss:\n\n- After every save i have some error in terminal but application still works and error not appear on website. Error down below.\n\n- When i add some new file in scss folder and try to import it to my main.scss by @use I have same error but this one appear on website and i have to use yarn dev again.\n\n### Error for no. 1\n\n```\nERROR Internal server error: [sass] expected \"{\". 11:50:07\n ╷\n9 │ \n │ ^\n ╵\n pages\\index.vue 9:10 root stylesheet\n Plugin: vite:css\n File: F:\\Projekty\\BearDash\\Website\\pages\\index.vue:9:10\n```\n\n### package.json\n\n```\n\"devDependencies\": {\n \"@nuxtjs/i18n\": \"^8.0.0-beta.10\",\n \"nuxt\": \"^3.3.3\",\n \"sass\": \"^1.62.0\"\n },\n \"dependencies\": {\n \"yarn\": \"^1.22.19\"\n }\n```\n\n### nuxt.config.js\n\n```\nexport default defineNuxtConfig({\n css: [\n \"~/assets/scss/main.scss\",\n ],\n vite: {\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: '@use \"@/assets/scss/_variables.scss\" as *;'\n }\n }\n }\n }\n})\n```\n\n========================================\n\nCode:\n```text\nERROR Internal server error: [sass] expected \"{\". 11:50:07\n ╷\n9 │ </script>\n │ ^\n ╵\n pages\\index.vue 9:10 root stylesheet\n Plugin: vite:css\n File: F:\\Projekty\\BearDash\\Website\\pages\\index.vue:9:10\n```\n\n```text\n\"devDependencies\": {\n \"@nuxtjs/i18n\": \"^8.0.0-beta.10\",\n \"nuxt\": \"^3.3.3\",\n \"sass\": \"^1.62.0\"\n },\n \"dependencies\": {\n \"yarn\": \"^1.22.19\"\n }\n```\n\n```text\nexport default defineNuxtConfig({\n css: [\n \"~/assets/scss/main.scss\",\n ],\n vite: {\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: '@use \"@/assets/scss/_variables.scss\" as *;'\n }\n }\n }\n }\n})\n```\n\n```text\n\"devDependencies\": {\n \"sass\": \"^1.59.2\",\n \"sass-loader\": \"^13.2.0\"\n}\n```\n\n```text\ncss: ['@/assets/scss/main.scss'],\nvite: {\n css: {\n preprocessorOptions: {\n scss: {\n additionalData: '@import \"@/assets/scss/_variables.scss\";',\n },\n },\n },\n},\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":117,"estimatedTokens":588}}810{"id":"stack-74510357","source":"stackoverflow","questionId":74510357,"title":"Cannot read properties of undefined (reading 'getters')","tags":["javascript","nuxt.js","vuex-modules"],"text":"Title: Cannot read properties of undefined (reading 'getters')\nTags: javascript, nuxt.js, vuex-modules\nSource: Stack Overflow\n\nQuestion:\nCan anyone help with the below, I am getting the following error Cannot read properties of undefined (reading 'getters')\n\nI am working on a project where my stores should return an array to my index.vue\n\nIs there also any way I can get around this without having to use the Vuex store?\n\nMy store directory contains the below files\n\nindex.js\n\n```\nexport const state = () => ({})\n```\n\nparkingPlaces.js\n\n```\nimport {getters} from '../plugins/base'\n\nconst state = () => ({\n all: []\n});\n\nexport default {\n state,\n mutations: {\n SET_PARKINGPLACES(state, parkingPlaces) {\n state.all = parkingPlaces\n }\n },\n actions: {\n async ENSURE({commit}) {\n\n commit('SET_PARKINGPLACES', [\n {\n \"id\": 1,\n \"name\": \"Chandler Larson\",\n \"post\": \"37757\",\n \"coordinates\": {\n \"lng\": -1.824377,\n \"lat\": 52.488583\n },\n \"total_spots\": 0,\n \"free_spots\": 0\n },\n ]\n )\n }\n },\n getters: {\n ...getters\n }\n}\n```\n\nindex.vue\n\n```\n\n \n \n 0 ? pins.spacefree : pins.spacenotfree}\"\n @click=\"currentLocation = location\"\n >\n \n `lat: {{ location.coordinates.lat }},\n lng: {{ location.coordinates.lng }}`\n \n \n \n \n \n\nimport {mapGetters, mapActions} from 'vuex';\n\nexport default {\n\n // async mounted() {\n // // // console.log('http://localhost:8000/api/parkingPlace')\n // // console.log(process.env.API_URL)\n // // const response = await this.$axios.$get('PARKING_PLACE')\n // //\n // // console.log('response', response)\n //\n // // console.log(location)\n // },\n\n data() {\n return {\n currentLocation: {},\n circleOptions: {},\n // parkingPlaces: [\n //array of parkingPlaces\n // ],\n pins: {\n spacefree: \"/parkingicongreen3.png\",\n spacenotfree: \"/parkingiconred3.png\",\n },\n mapStyle: [],\n clusterStyle: [\n {\n url: \"https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m1.png\",\n width: 56,\n height: 56,\n textColor: \"#fff\"\n }\n ]\n }\n },\n\n computed: {\n ...mapGetters({\n 'parkingPlaces': \"parkingPlaces/all\"\n })\n },\n\n async fetch() {\n await this.ensureParking()\n },\n methods: {\n ...mapActions({\n ensureParking: 'parkingPlaces/ENSURE'\n })\n }\n }\n\n```\n\nbase.js\n\n```\nimport getters from \"./getters\";\n\nexport {getters};\n```\n\ngetters.js\n\n```\nexport default {\n all: state => state.all\n};\n```\n\nImage of my file directory below\nhttps://i.sstatic.net/Vxjv6.png\n\nimage of error\nhttps://i.sstatic.net/9Wmzm.png\n\n========================================\n\nTop Answer:\nIn parkingPlaces.js: Try using `import {getters} from '../plugins/base.js'` instead of `import {getters} from '../plugins/base'`.\n\nIn base.us: try using `import getters from './getters.js'` instead of `import getters from './getters'`.\n\n========================================\n\nCode:\n```text\nexport const state = () => ({})\n```\n\n```text\nimport {getters} from '../plugins/base'\n\nconst state = () => ({\n all: []\n});\n\nexport default {\n state,\n mutations: {\n SET_PARKINGPLACES(state, parkingPlaces) {\n state.all = parkingPlaces\n }\n },\n actions: {\n async ENSURE({commit}) {\n\n commit('SET_PARKINGPLACES', [\n {\n \"id\": 1,\n \"name\": \"Chandler Larson\",\n \"post\": \"37757\",\n \"coordinates\": {\n \"lng\": -1.824377,\n \"lat\": 52.488583\n },\n \"total_spots\": 0,\n \"free_spots\": 0\n },\n ]\n )\n }\n },\n getters: {\n ...getters\n }\n}\n```\n\n```text\n<template>\n <div class=\"min-h-screen relative max-6/6\" >\n <GMap class=\"absolute inset-0 h-100% bg-blue-400\"\n ref=\"gMap\"\n language=\"en\"\n :cluster=\"{options: {styles: clusterStyle}}\"\n :center=\"{lat:parkingPlaces[0].coordinates.lat, lng: parkingPlaces[0].coordinates.lng}\"\n :options=\"{fullscreenControl: false, styles: mapStyle}\"\n :zoom=\"5\"\n >\n <GMapMarker\n v-for=\"location in parkingPlaces\"\n :key=\"location.id\"\n :position=\"{lat: location.coordinates.lat, lng: location.coordinates.lng}\"\n :options=\"{icon: location.free_spots > 0 ? pins.spacefree : pins.spacenotfree}\"\n @click=\"currentLocation = location\"\n >\n <GMapInfoWindow :options=\"{maxWidth: 200}\">\n <code>\n lat: {{ location.coordinates.lat }},\n lng: {{ location.coordinates.lng }}\n </code>\n </GMapInfoWindow>\n </GMapMarker>\n <GMapCircle :options=\"circleOptions\"/>\n </GMap>\n </div>\n</template>\n\n<script>\n\nimport {mapGetters, mapActions} from 'vuex';\n\n\n\n\nexport default {\n\n\n\n\n // async mounted() {\n // // // console.log('http://localhost:8000/api/parkingPlace')\n // // console.log(process.env.API_URL)\n // // const response = await this.$axios.$get('PARKING_PLACE')\n // //\n // // console.log('response', response)\n //\n // // console.log(location)\n // },\n\n data() {\n return {\n currentLocation: {},\n circleOptions: {},\n // parkingPlaces: [\n //array of parkingPlaces\n // ],\n pins: {\n spacefree: \"/parkingicongreen3.png\",\n spacenotfree: \"/parkingiconred3.png\",\n },\n mapStyle: [],\n clusterStyle: [\n {\n url: \"https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m1.png\",\n width: 56,\n height: 56,\n textColor: \"#fff\"\n }\n ]\n }\n },\n\n computed: {\n ...mapGetters({\n 'parkingPlaces': \"parkingPlaces/all\"\n })\n },\n\n async fetch() {\n await this.ensureParking()\n },\n methods: {\n ...mapActions({\n ensureParking: 'parkingPlaces/ENSURE'\n })\n }\n }\n</script>\n```\n\n```text\nimport getters from \"./getters\";\n\nexport {getters};\n```\n\n```text\nexport default {\n all: state => state.all\n};\n```\n\n```text\nexport default {\n //your getters\n};\n```\n\n```text\nimport getters from \"./getters\";\nconst store = createStore({\n state () {\n return {\n something: 0\n }\n },\n getters\n})\n```\n\n```text\n...mapGetters({\n parkingPlaces: 'all'\n})\n```\n\n```text\nconst moduleA = {\n state: () => ({ ... }),\n mutations: { ... },\n actions: { ... },\n getters: { ... }\n}\n\nconst moduleB = {\n state: () => ({ ... }),\n mutations: { ... },\n actions: { ... }\n}\n\nconst store = createStore({\n modules: {\n a: moduleA,\n b: moduleB\n }\n})\n```\n\n```text\nindex.js\n```\n\n```text\nmapGetters\n```\n\n```text\nimport {getters} from '../plugins/base.js'\n```\n\n```text\nimport {getters} from '../plugins/base'\n```\n\n```text\nimport getters from './getters.js'\n```\n\n```text\nimport getters from './getters'\n```\n\n```text\nimport parkingPlacesModule from './parkingPlaces.js';\nconst store = new Vuex.Store({\n modules: {\n parkingPlaces: {\n namespaced: true,\n ...parkingPlacesModule\n }\n }\n});\n```\n\n```text\ncomputed: {\n ...mapGetters('parkingPlaces', [\n 'all', // -> this.all\n ])\n}\n```\n\n```text\nparkingPlaces.js\n```\n\n```text\nnamespaced\n```\n\n```text\nexport const getters = {\n all: state => state.all\n};\n```\n\n```text\nexport * from \"./getters\";\n```\n\n```text\nbase.js\n```\n\n```text\ngetters\n```\n\n========================================\n\nComments:\n- can you add your file directory? or a screenshot\n- Hi @Delanovanlonden I have added this above\n- dev.to/jacobandrewsky/introduction-to-nuxt-3-modules-5h8o this might help you\n- Hey, I have tried this numerous times before but does not seem to fix the error. Thank you for the input :)\n- I have also tried that but no luck :( I have gone through all the possible things it could be for days on end and this error is still there.\n- @newToBeingNerdy is there a line number with the error message? Or any other info?\n- I have updated my post above to show an image of the error, there are no errors in the IDE.\n- Thank you for spending your precious time educate me on this. ;)\n- happy to help my friend","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":441,"estimatedTokens":1932}}811{"id":"stack-72351811","source":"stackoverflow","questionId":72351811,"title":"How to download a file on a link click in Nuxt?","tags":["javascript","vue.js","nuxt.js"],"text":"Title: How to download a file on a link click in Nuxt?\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm coming across an edge case issue where if a user navigates around a few Nuxt routes, clicks the websites \"logo\" which is an anchor tag back home, then clicks the browsers native back button and then finally clicks a link which is supposed to open a pdf, it redirects to my 404 page.\n\nIf the user clicks the pdf link upon page load it behaves as expected. Not sure what is going on here? I tried to add a method to force `window.open` on the pdf and it is still broken.\n\nAnchor example:\n\n```\n\n Instructions \n\n```\n\nMethod:\n\n```\nforceHrefToPdf(pdf) {\n window.open(pdf, \"_blank\")\n}\n```\n\nPDF is inside the `/root/static` directory.\n\n========================================\n\nCode:\n```html\n<a\n class=\"text--uppercase decorate-hover\"\n @click.prevent=\"forceHrefToPdf('Instructions.pdf')\"\n>\n Instructions \n</a>\n```\n\n```js\nforceHrefToPdf(pdf) {\n window.open(pdf, \"_blank\")\n}\n```\n\n```text\nwindow.open\n```\n\n```text\n/root/static\n```\n\n```html\n<template>\n <button @click=\"downloadMe\">download me</button>\n</template>\n\n<script>\nexport default {\n methods: {\n downloadMe() {\n const link = document.createElement('a')\n link.href = '/Instructions.pdf'\n link.download = 'Intructions.pdf'\n link.target = '_blank'\n link.click()\n },\n },\n}\n</script>\n```\n\n```html\n<a href=\"/Instructions.pdf\" target=\"_blank\" download>\n Download my PDF via a link tag\n</a>\n```\n\n```text\na\n```\n\n```text\nbutton\n```\n\n```text\naction\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":90,"estimatedTokens":389}}812{"id":"stack-71317779","source":"stackoverflow","questionId":71317779,"title":"Make API call based on route parameter in Nuxt 3 dynamic compopnent","tags":["vue.js","nuxt.js","watch","nuxt3.js"],"text":"Title: Make API call based on route parameter in Nuxt 3 dynamic compopnent\nTags: vue.js, nuxt.js, watch, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm attempting to create a simple Nuxt 3 app for learning purposes that uses dynamic routes to load data from an API when the page is loaded. What I'm trying to figure out is how to use the route `id` param with the composition API to call an external API and make the data available in the component.\n\nSo here is my basic folder structure:\n\n```\n/pages\n \\\n index.vue\n /currency\n \\\n [id].vue\n```\n\nindex.vue:\n\n```\n\n \n \n\n### Index Page\n\n \n \n \n Name\n Symbol\n Price\n Details\n \n \n {{ currency.name }}\n {{ currency.symbol }}\n {{ currency.price_usd }}\n \n {{ currency.id }}\n \n \n \n \n \n\nexport default {\n async setup() {\n const {data} = await useFetch('/api/coinlore/tickers');\n\n return {\n data\n };\n }\n}\n\n```\n\nand here is what I have for `[id].vue`\n\n```\n\n \n \n\n### {{ data.data.name }} Detail page\n\n {{ $route.params.id }}\n \n\nexport default {\n async setup() {\n const {data} = await useFetch('/api/coinlore/ticker?id=90');\n\n console.log(data);\n\n return {\n data\n };\n }\n}\n\n```\n\nGoing from this blog post I tried this\n\n```\n\n \n \n\n### {{ data.name }} Detail page\n\n {{ $route.params.id }}\n \n\nexport default {\n async setup() {\n const coin = reactive({});\n function fetchCoin(id) {\n const {data} = await useFetch('/api/coinlore/ticker?id=' + $route.params.id);\n coin = data;\n }\n\n watch('$route.params.id', fetchCoin)\n\n return {\n coin\n };\n }\n}\n\n```\n\nbut no dice there, either.\n\nHow can I simply 1) make my API call and 2) populate the data by using the `id` param in my `[id].vue` component?\n\n========================================\n\nTop Answer:\nYou can basically pass the id in route params like:\n\n\r\n\r\n\n```\n{{ currency.id }}\n```\n\n\r\n\r\n\r\n\nThis piece of code will redirect to /currency/id\n\nAlso, the folder structure should be like:\n\n```\n/pages \n /currency \n [id].vue\n```\n\n========================================\n\nCode:\n```text\n/pages\n \\\n index.vue\n /currency\n \\\n [id].vue\n```\n\n```html\n<template>\n <main>\n <h1>Index Page</h1>\n\n <table border=\"1 px solid\">\n <thead>\n <tr>\n <th>Name</th>\n <th>Symbol</th>\n <th>Price</th>\n <th>Details</th>\n </tr>\n <tr v-for=\"currency in data.data\" :key=\"data.id\">\n <td>{{ currency.name }}</td>\n <td>{{ currency.symbol }}</td>\n <td>{{ currency.price_usd }}</td>\n <td>\n <NuxtLink :to=\"'/currency/' + currency.id\">{{ currency.id }}</NuxtLink>\n </td>\n </tr>\n </thead>\n </table>\n </main>\n</template>\n\n<script>\nexport default {\n async setup() {\n const {data} = await useFetch('/api/coinlore/tickers');\n\n return {\n data\n };\n }\n}\n</script>\n```\n\n```html\n<template>\n <main>\n <h1>{{ data.data.name }} Detail page</h1>\n {{ $route.params.id }}\n </main>\n</template>\n\n<script>\nexport default {\n async setup() {\n const {data} = await useFetch('/api/coinlore/ticker?id=90');\n\n console.log(data);\n\n return {\n data\n };\n }\n}\n</script>\n```\n\n```html\n<template>\n <main>\n <h1>{{ data.name }} Detail page</h1>\n {{ $route.params.id }}\n </main>\n</template>\n\n<script>\nexport default {\n async setup() {\n const coin = reactive({});\n function fetchCoin(id) {\n const {data} = await useFetch('/api/coinlore/ticker?id=' + $route.params.id);\n coin = data;\n }\n\n watch('$route.params.id', fetchCoin)\n\n return {\n coin\n };\n }\n}\n</script>\n```\n\n```text\nid\n```\n\n```text\n[id].vue\n```\n\n```text\nid\n```\n\n```text\n[id].vue\n```\n\n```js\nimport { useRoute } from 'vue-router';\n\nexport default {\n setup() { 👇\n const route = useRoute(); \n const { data: coin } = await useFetch('/api/coinlore/ticker?id=' + route.params.id);\n\n return { coin }\n }\n}\n```\n\n```text\nuseRoute()\n```\n\n```js\n<NuxtLink :to=\"{path: '/currency', params : {id: currency.id} }\">{{ currency.id }}</NuxtLink>\n// it will build link: `/currency/[id]`\n```\n\n```js\n// import in script\nimport { useRoute } from 'vue-router';\n\n// define route from 'vue'\nconst route = useRoute()\n \n// read ID from route params\nconst currencyId = route.params.id\n \n// actually it's better use literal string for using dynamic data => better reading\nconst { data: coin } = await useFetch(`/api/coinlore/ticker?id=${currencyId}`);\n```\n\n```html\n<NuxtLink :to=\"{path: '/currency', params : {id: currency.id} }\">{{ currency.id }}</NuxtLink>\n```\n\n```text\n/pages \n /currency \n [id].vue\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":307,"estimatedTokens":1130}}813{"id":"stack-53892664","source":"stackoverflow","questionId":53892664,"title":"use vue/nuxt linting rules in vscode","tags":["vue.js","visual-studio-code","eslint","nuxt.js","prettier"],"text":"Title: use vue/nuxt linting rules in vscode\nTags: vue.js, visual-studio-code, eslint, nuxt.js, prettier\nSource: Stack Overflow\n\nQuestion:\nI created a new nuxt app using `npx create-nuxt-app ` and chose to use eslint and prettier. \n\nI opened the project's directory using vscode and installed the ESLint and Prettier - Code formatter, and Vetur extensions.\n\nWhen I save a `.vue` file vscode formats the code, but in a way that breaks the settings in the nuxt project. \n\nFor example vscode transforms\n\n```\n\n test\n \n```\n\nto\n\n```\ntest\n```\n\nbut this breaks the `vue/max-attributes-per-line` rule. \n\nHow do I set up vscode to use the nuxt project's linting and prettyfying rules?\n\n========================================\n\nTop Answer:\nInstall the extensions:\n\nVue\nVue 2 Snippets\nVue Peek\nVetur\nESLint\n\nGo to File > Preferences > Settings and edit the User Settings file, adding the following configuration:\n\n```\n{\n ...... ,\n\n \"vetur.format.defaultFormatter.js\": \"vscode-typescript\",\n \"vetur.format.defaultFormatter.html\": \"js-beautify-html\",\n \"javascript.format.insertSpaceBeforeFunctionParenthesis\": true,\n \"eslint.autoFixOnSave\": true,\n \"eslint.validate\": [\n {\n \"language\": \"vue\",\n \"autoFix\": true\n },\n {\n \"language\": \"html\",\n \"autoFix\": true\n },\n {\n \"language\": \"javascript\",\n \"autoFix\": true\n }\n ],\n}\n```\n\nWith this configuration, VSCode will perform validation for these three file types: vue, HTML and JavaScript. Now go back to the src/App.vue file and press ctrl+alt+f on Windows or ctrl+shift+i on Linux or ctrl+options+f on Mac OS to perform the formatting of the code. ESLint will validate the code and display some errors on the screen.\n\nAny errors can be corrected automatically, and it’s not necessary to correct each error manually. To do this, you can \n\npress \n\nctrl+shift+p \n\nand select \n\nESLint: Fix all problems\n\n========================================\n\nCode:\n```text\n<div \n class=\"test\" \n style=\"background: red\">\n test\n </div>\n```\n\n```text\n<div class=\"test\" style=\"background: red\">test</div>\n```\n\n```text\nnpx create-nuxt-app <project-name>\n```\n\n```text\n.vue\n```\n\n```text\nvue/max-attributes-per-line\n```\n\n```text\nnpm install --save-dev babel-eslint eslint eslint-config-prettier eslint-loader eslint-plugin-vue eslint-plugin-prettier prettier\n```\n\n```text\n{\n \"eslint.format.enable\": true,\n \"vetur.format.defaultFormatter.html\": \"prettier\"\n }\n```\n\n```text\n{\n \"editor.formatOnPaste\": true,\n \"editor.formatOnSave\": true,\n \"editor.formatOnType\": true\n }\n```\n\n```text\n{\n \"semi\": false,\n \"arrowParens\": \"always\",\n \"singleQuote\": true,\n \"trailingComma\": \"none\",\n \"bracketSpacing\": true,\n \"endOfLine\": \"lf\"\n}\n```\n\n```text\nnpx create-nuxt-app\n```\n\n```text\njsconfig.json\n```\n\n```text\n.vscode/settings.json\n```\n\n```text\nFormatting Toggle\n```\n\n```text\n.prettierrc\n```\n\n```text\n{\n ...... ,\n\n \"vetur.format.defaultFormatter.js\": \"vscode-typescript\",\n \"vetur.format.defaultFormatter.html\": \"js-beautify-html\",\n \"javascript.format.insertSpaceBeforeFunctionParenthesis\": true,\n \"eslint.autoFixOnSave\": true,\n \"eslint.validate\": [\n {\n \"language\": \"vue\",\n \"autoFix\": true\n },\n {\n \"language\": \"html\",\n \"autoFix\": true\n },\n {\n \"language\": \"javascript\",\n \"autoFix\": true\n }\n ],\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":180,"estimatedTokens":820}}814{"id":"stack-70181978","source":"stackoverflow","questionId":70181978,"title":"Tailwind CSS in Nuxt project trying to use SCSS variable throws \"Unknown word\" error","tags":["sass","nuxt.js","less","tailwind-css","postcss"],"text":"Title: Tailwind CSS in Nuxt project trying to use SCSS variable throws \"Unknown word\" error\nTags: sass, nuxt.js, less, tailwind-css, postcss\nSource: Stack Overflow\n\nQuestion:\nI'm using Tailwind CSS in my Nuxt JS project and need to create a simple scss file with some variables that are then used in the `:root` selector to generate some theme colours. I've created my variables, and then have included them inside of my `tailwind.scss` file inside of **assets/scss**\n\nThe issue I'm facing is that PostCSS thinks that there's an error with my variable defined in this selector and throws the following error:\n\npostcss-custom-properties: Unknown word\n\nTo me, this isn't an error as I'm working in a SCSS file which supports variables, what am I missing here?\n\n**assets/scss/tailwind.scss**\n\n```\n@import '../../brand-theme';\n\n/* In your CSS */\n:root {\n --color-primary: $primary;\n --color-primary-darken: $primary;\n --color-secondary: $secondary;\n}\n\n@import './layout/base';\n@import './vendors/hooper';\n```\n\n**brand-theme.scss *(in root of my project)* **\n\n```\n$primary: 238, 121, 61;\n$secondary: 146, 74, 139;\n```\n\nhttps://i.sstatic.net/MfnFm.png\n\n========================================\n\nCode:\n```css\n@import '../../brand-theme';\n\n/* In your CSS */\n:root {\n --color-primary: $primary;\n --color-primary-darken: $primary;\n --color-secondary: $secondary;\n}\n\n@import './layout/base';\n@import './vendors/hooper';\n```\n\n```text\n$primary: 238, 121, 61;\n$secondary: 146, 74, 139;\n```\n\n```text\n:root\n```\n\n```text\ntailwind.scss\n```\n\n```css\n--color-primary: #{$primary};\n```\n\n```text\n:root\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":75,"estimatedTokens":398}}815{"id":"stack-68771762","source":"stackoverflow","questionId":68771762,"title":"How to pass layout property to page component in nuxtjs","tags":["vue.js","nuxt.js"],"text":"Title: How to pass layout property to page component in nuxtjs\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am completely new to VueJS and NuxtJS. I can't seem to pass a property in the layout to a page component.\n\nThis is my `layouts/default.vue`\n\n```\n\n \n\nexport default {\n data: () => ({\n myprop: 'hello galaxy',\n }),\n}\n\n```\n\nThis is my `pages/index.vue`\n\n```\n\n My Prop is: {{myprop}}\n\nexport default {\n props: {\n myprop: {\n type: String\n },\n },\n}\n\n```\n\nWhen I load up my app, I expect to see `My Prop is: hello world`. But instead, I see `My Prop is:`, and it seems `myprop` is empty.\n\nWhat am I doing wrong? How does a layout component pass a property to child component in VueJS or NuxtJS?\n\n========================================\n\nCode:\n```html\n<template>\n <Nuxt myprop=\"hello world\" />\n</template>\n\n<script>\nexport default {\n data: () => ({\n myprop: 'hello galaxy',\n }),\n}\n</script>\n```\n\n```html\n<template>\n <div>My Prop is: {{myprop}}</div>\n</template>\n\n<script>\nexport default {\n props: {\n myprop: {\n type: String\n },\n },\n}\n</script>\n```\n\n```text\nlayouts/default.vue\n```\n\n```text\npages/index.vue\n```\n\n```text\nMy Prop is: hello world\n```\n\n```text\nMy Prop is:\n```\n\n```text\nmyprop\n```\n\n```html\n<template>\n <Nuxt />\n</template>\n\n<script>\nexport default {\n provide: function () {\n return { myprop: this.myprop };\n },\n data: () => ({\n myprop: 'hello galaxy',\n }),\n}\n</script>\n```\n\n```html\n<template>\n <div>My Prop is: {{myprop}}</div>\n</template>\n\n<script>\nexport default {\n inject: [\"myprop\"],\n}\n</script>\n```\n\n```text\nprovide/inject\n```\n\n```text\nlayout/default.vue\n```\n\n```text\npages/index.vue\n```\n\n========================================\n\nComments:\n- This works for my context; I will keep it as an option. Alternatively I may just use VueX anyways since everything else is stored there globally.","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":139,"estimatedTokens":465}}816{"id":"stack-68739592","source":"stackoverflow","questionId":68739592,"title":"Vue 3 Access to a DOM Element before mount","tags":["javascript","vue.js","nuxt.js","vuejs3"],"text":"Title: Vue 3 Access to a DOM Element before mount\nTags: javascript, vue.js, nuxt.js, vuejs3\nSource: Stack Overflow\n\nQuestion:\nI'm creating a Vue `` component inside NuxtJS with the new composition API syntax.\nI would like to automatically set the `color` of my `UiIcon` when the root of the template has the `disabled` class.\n\nI first thought to this approach, but then I realized that in the setup method, the DOM was not yet accessible. What could be another viable solution ?\n\nPS: Managed to solve it using CSS `stroke` attribute because `UiIcon` is an SVG but I was curious if there as another solution utilizing the `color` pop already defined.\n\n```\n\n \n \n \n \n \n \n\nimport {\n defineComponent,\n computed,\n ref,\n toRefs,\n} from '@nuxtjs/composition-api';\nimport { Colors } from '~/helpers/styles';\n\nexport default defineComponent({\n name: 'Link',\n props: {\n href: {\n type: String,\n default: undefined,\n },\n target: {\n type: String as () => '_blank' | '_self' | '_parent' | '_top',\n default: '_self',\n },\n icon: {\n type: String,\n default: undefined,\n },\n iconColor: {\n type: String,\n default: undefined,\n },\n iconHoverColor: {\n type: String,\n default: undefined,\n },\n },\n setup(props) {\n const { href, target, icon, iconHoverColor } = toRefs(props);\n const linkActive = ref(false);\n const row = ref(null);\n\n const linkIconColor = computed(() => {\n const linkDisabled = row.value?.classList.contains('disabled');\n\n if (linkDisabled) {\n return Colors.DARK_GREY;\n }\n if (linkActive.value && iconHoverColor.value) {\n return props.iconHoverColor;\n }\n return props.iconColor;\n });\n\n return {\n linkHref: href,\n linkTarget: target,\n linkIcon: icon,\n linkIconColor,\n linkActive,\n };\n },\n});\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div ref=\"row\" class=\"row\">\n <UiIcon\n v-if=\"linkIcon\"\n :type=\"linkIcon\"\n :color=\"linkIconColor\"\n class=\"icon\"\n />\n <a\n class=\"link\"\n :href=\"linkHref\"\n :target=\"linkTarget\"\n :rel=\"linkTarget === 'blank' ? 'noopener noreferrer' : null\"\n @mouseover=\"linkActive = true\"\n @mouseout=\"linkActive = false\"\n >\n <slot></slot>\n </a>\n </div>\n</template>\n\n<script lang=\"ts\">\nimport {\n defineComponent,\n computed,\n ref,\n toRefs,\n} from '@nuxtjs/composition-api';\nimport { Colors } from '~/helpers/styles';\n\nexport default defineComponent({\n name: 'Link',\n props: {\n href: {\n type: String,\n default: undefined,\n },\n target: {\n type: String as () => '_blank' | '_self' | '_parent' | '_top',\n default: '_self',\n },\n icon: {\n type: String,\n default: undefined,\n },\n iconColor: {\n type: String,\n default: undefined,\n },\n iconHoverColor: {\n type: String,\n default: undefined,\n },\n },\n setup(props) {\n const { href, target, icon, iconHoverColor } = toRefs(props);\n const linkActive = ref(false);\n const row = ref<HTMLDivElement | null>(null);\n\n const linkIconColor = computed(() => {\n const linkDisabled = row.value?.classList.contains('disabled');\n\n if (linkDisabled) {\n return Colors.DARK_GREY;\n }\n if (linkActive.value && iconHoverColor.value) {\n return props.iconHoverColor;\n }\n return props.iconColor;\n });\n\n return {\n linkHref: href,\n linkTarget: target,\n linkIcon: icon,\n linkIconColor,\n linkActive,\n };\n },\n});\n</script>\n```\n\n```text\n<Link>\n```\n\n```text\ncolor\n```\n\n```text\nUiIcon\n```\n\n```text\ndisabled\n```\n\n```text\nstroke\n```\n\n```text\nUiIcon\n```\n\n```text\ncolor\n```\n\n```text\nbeforeMount() {\n this.$nextTick(function () {\n //code here\n })\n}\n```\n\n========================================\n\nComments:\n- Did you try `onBeforeMount`?\n- No, I didn't know this hook was for such use case!\n- Sweet, is there a `this.$nextTick` equivalent with the Vue 3 `onBeforeMount`? From there I can update the computed property ?\n- yes you can use setup({ root }) { onBeforeMount(){root.$nextTick(function () { //code here })} }\n- The thing is the computed property is read-only so how could I modify it's value in here ?\n- Also, I get a deprecation warning on `context.root` which is apprently deprecated. Is there a new way to do in Vue 3 ?\n- You can use set and get methods of computed property as described here v3.vuejs.org/guide/…\n- But inside `get/set` I can't use the DOM either so I have the same problem ? Could you an example of what you're thinking about ?\n- For next tick you can import it directly from vue as described here v3.vuejs.org/api/global-api.html#nexttick\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":218,"estimatedTokens":1153}}817{"id":"stack-68652147","source":"stackoverflow","questionId":68652147,"title":"Why image path is not resolved by require() when passed as prop in NuxtJS?","tags":["javascript","vue.js","webpack","vuejs2","nuxt.js"],"text":"Title: Why image path is not resolved by require() when passed as prop in NuxtJS?\nTags: javascript, vue.js, webpack, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn my NuxtJS project I have a component that recieves an image path as a prop. I tried passing it directly to `:src=\"imageAddress\"` but it neither resolve nor throws an error. Then I tried to use this path inside `require()` to resolve it properly. But I get this Nuxt error: Cannot find module '~/assets/icons/crown.png'. The path is correct and I tested that by placing an `img` element directly in `index.vue`. Do you have any idea why this happens?\n\nThis is how my code is structured:\n\n\r\n\r\n\n```\npages/index.vue\n\n \n\n___________________________________________________________________\n\ncomponents/ChildComponent.vue\n\n \n\nexport default {\n name: 'ChildComponent',\n props: {\n imageAddress: {\n type: String,\n required: true,\n default: ''\n }\n }\n}\n\n```\n\n========================================\n\nTop Answer:\nJust want to what worked for me. Since using `require` gives undefined error. I used `import` instead.\n\n```\nimport imageAddress from '~/asset/icons/crown.png';\n```\n\n```\n\n \n\n```\n\n========================================\n\nCode:\n```html\npages/index.vue\n<template>\n <ChildComponent image-address=\"~/assets/icons/crown.png\" />\n</template>\n\n___________________________________________________________________\n\ncomponents/ChildComponent.vue\n<template>\n <img v-if=\"imageAddress.length\" :src=\"require(imageAddress)\">\n</template>\n\n<script>\nexport default {\n name: 'ChildComponent',\n props: {\n imageAddress: {\n type: String,\n required: true,\n default: ''\n }\n }\n}\n</script>\n```\n\n```text\n:src=\"imageAddress\"\n```\n\n```text\nrequire()\n```\n\n```text\nimg\n```\n\n```text\nindex.vue\n```\n\n```text\ngetUrl (img) {\n return require(`~/assets/icons/${img}.png`);\n}\n```\n\n```html\n<img :src=\"getUrl(imageAddress)\" alt=\"\" />\n```\n\n```js\nimport imageAddress from '~/asset/icons/crown.png';\n```\n\n```js\n<template>\n <ChildComponent :image-address=\"imageAddress\" />\n</template>\n```\n\n```text\nrequire\n```\n\n```text\nimport\n```\n\n========================================\n\nComments:\n- no need for require just add url directly#\n- @ToufiqAhmed I mentioned in the question that I have done that. it doesn't resolve. it is placed inside src as it is ~/assets/icons/crown.png.\n- This worked, thanks, I used a computed property instead of a method.\n- `require` is indeed for old build tools (Webpack).","metadata":{"transformedAt":"2026-08-18T18:33:07.895Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":132,"estimatedTokens":612}}818{"id":"stack-67705419","source":"stackoverflow","questionId":67705419,"title":"Composition API with Nuxt 2 to get template refs array","tags":["javascript","vue.js","nuxt.js","vue-composition-api"],"text":"Title: Composition API with Nuxt 2 to get template refs array\nTags: javascript, vue.js, nuxt.js, vue-composition-api\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get the array of element refs that are not in `v-for`. I'm using `@nuxtjs/composition-api` on Nuxt 2.\n\n(Truth: I want to make an array of input elements, so that I can perform validations on them before submit)\n\nThis sounds too easy on vue 2 as `$refs` becomes an array when one or more compnents have the same ref name on html. However, this doesn't sound simple with composition api and trying to perform simple task with that got me stuck from long.\n\nSo to handle this scenario, I've created 1 composable function. (Soruce: https://v3-migration.vuejs.org/breaking-changes/array-refs.html#frontmatter-title)\n\n```\n// file: viewRefs.js\n\nimport { onBeforeUpdate, onUpdated } from '@nuxtjs/composition-api'\nexport default () => {\n let itemRefs = []\n const setItemRef = el => {\n console.log('adding item ref')\n if (el) {\n itemRefs.push(el)\n }\n }\n onBeforeUpdate(() => {\n itemRefs = []\n })\n onUpdated(() => {\n console.log(itemRefs)\n })\n return {\n itemRefs,\n setItemRef\n }\n}\n```\n\nHere is my `vue` file:\n\n```\n\n \n \n \n \n \n \n \n // rest of my cool html\n \n\nimport {\n defineComponent,\n reactive,\n useRouter,\n ref\n} from '@nuxtjs/composition-api'\nimport viewRefs from '~/composables/viewRefs'\nexport default defineComponent({\n setup() {\n\n const input = viewRefs()\n\n // awesome vue code here...\n \n return {\n input\n }\n }\n})\n\n```\n\nNow when I run this file, I don't see any `adding item ref` logs. And on click of a button, I'm logging `input`. That has 0 items in the `itemRefs` array.\n\nWhat's going wrong?\n\n========================================\n\nCode:\n```text\n// file: viewRefs.js\n\nimport { onBeforeUpdate, onUpdated } from '@nuxtjs/composition-api'\nexport default () => {\n let itemRefs = []\n const setItemRef = el => {\n console.log('adding item ref')\n if (el) {\n itemRefs.push(el)\n }\n }\n onBeforeUpdate(() => {\n itemRefs = []\n })\n onUpdated(() => {\n console.log(itemRefs)\n })\n return {\n itemRefs,\n setItemRef\n }\n}\n```\n\n```text\n<template>\n <div>\n <input :ref=\"input.setItemRef\" />\n <input :ref=\"input.setItemRef\" />\n <input :ref=\"input.setItemRef\" />\n <input :ref=\"input.setItemRef\" />\n <input :ref=\"input.setItemRef\" />\n <input :ref=\"input.setItemRef\" />\n // rest of my cool html\n </div>\n</template>\n\n<script>\nimport {\n defineComponent,\n reactive,\n useRouter,\n ref\n} from '@nuxtjs/composition-api'\nimport viewRefs from '~/composables/viewRefs'\nexport default defineComponent({\n setup() {\n\n const input = viewRefs()\n\n // awesome vue code here...\n \n return {\n input\n }\n }\n})\n</script>\n```\n\n```text\nv-for\n```\n\n```text\n@nuxtjs/composition-api\n```\n\n```text\n$refs\n```\n\n```text\nvue\n```\n\n```text\nadding item ref\n```\n\n```text\ninput\n```\n\n```text\nitemRefs\n```\n\n```html\n<template>\n <div id=\"app\">\n <button @click=\"logRefs\">Log refs</button>\n <input v-for=\"i in 4\" :key=\"i\" ref=\"itemRef\" />\n </div>\n</template>\n\n<script>\nimport { ref } from '@vue/composition-api'\n\nexport default {\n setup() {\n const itemRef = ref(null)\n return {\n itemRef,\n logRefs() {\n console.log(itemRef.value) // => array of inputs\n },\n }\n }\n}\n</script>\n```\n\n```text\nref\n```\n\n```text\nref\n```\n\n```text\nref\n```\n\n```text\nv-for\n```\n\n```text\nref\n```\n\n```text\nsetup()\n```\n\n```text\n$refs\n```\n\n```text\nref\n```\n\n========================================\n\nComments:\n- `itemRefs = []` is incorrect because you reassign local variable. Make it `ref` and never reassign.\n- @EstusFlask Made it ref and used `itemRefs.value.push`, but still not working","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":232,"estimatedTokens":918}}819{"id":"stack-66470346","source":"stackoverflow","questionId":66470346,"title":"how to pass data to mixins and then displaying them in your component?","tags":["javascript","vue.js","nuxt.js","mixins"],"text":"Title: how to pass data to mixins and then displaying them in your component?\nTags: javascript, vue.js, nuxt.js, mixins\nSource: Stack Overflow\n\nQuestion:\nI want to pass data to my mixin's method, and then display it in my component. Something like:\n\n```\n//component A\n\nmixins: [mixinOne],\ndata(){\n return{\n val = null\n }\n},\nmounted(){\n this.mixinMethod('good value', this.val);\n}\n```\n\n```\n//mixinOne\nmixinMethod(valOne, valTwo) {\n valTwo = valOne;\n}\n```\n\nAnd in my template I want to display val:\n\n```\n// component A\n\n {{val}}\n\n```\n\nI have written the above code and it doesn't work. It returns null for `{{val}}`! So basically I want to see 'good value' in my component for `{{val}}` which is setup through my mixin. How can I do that?\n\n========================================\n\nCode:\n```text\n//component A\n\nmixins: [mixinOne],\ndata(){\n return{\n val = null\n }\n},\nmounted(){\n this.mixinMethod('good value', this.val);\n}\n```\n\n```text\n//mixinOne\nmixinMethod(valOne, valTwo) {\n valTwo = valOne;\n}\n```\n\n```text\n// component A\n<template>\n {{val}}\n</template>\n```\n\n```text\n{{val}}\n```\n\n```text\n{{val}}\n```\n\n```text\n// MmixinOne\ndata () {\n return {\n val = null\n }\n},\nmethods: {\n mixinMethod (valOne, valTwo) {\n valTwo = valOne\n }\n}\n\n// Component A\n<template>\n {{val}}\n</template>\n\n<script>\nimport MmixinOne from './MmixinOne'\n\nexport default {\n mixins: [MmixinOne],\n mounted () {\n this.mixinMethod('good value', this.val)\n }\n}\n</script>\n```\n\n```text\nmounted () {\n this.val = 'good value'\n}\n```\n\n========================================\n\nComments:\n- On top of the answer that was given to you, you do have this part of the docs: vuejs.org/v2/guide/mixins.html#Basics","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":118,"estimatedTokens":422}}820{"id":"stack-66543079","source":"stackoverflow","questionId":66543079,"title":"PurgeCSS ignore regex in whitelistPatterns and remove TailwindCSS classes (on NuxtJS)","tags":["tailwind-css","nuxt.js","css-purge"],"text":"Title: PurgeCSS ignore regex in whitelistPatterns and remove TailwindCSS classes (on NuxtJS)\nTags: tailwind-css, nuxt.js, css-purge\nSource: Stack Overflow\n\nQuestion:\nI'm using NuxtJS (VueJS) with TailwindCSS and PurgeCSS.\nUntil now, I was specifying complete CSS classes for colors like `text-green-800`, `bg-red-400`, etc. But when creating component it's not ideal while the color can be passed as a Prop, but it's also not possible to directly do `bg-{color}-400` while PurgeCSS while remove the background colors not found.\n\nSo, I wanted to put those classes in the whitelistPatterns from PurgeCSS, allowing regex to protect some classes.\nThis is what I've set up :\n\n```\npurgeCSS: {\n whitelistPatterns: [/^bg-/, /^text-/, /^border-/]\n },\n```\n\nBut PurgeCSS is completely ignoring the configuration. I've tried many regex : `/bg-/`, `/bg/`, `/^bg-.*/`, etc. None have worked.\nI thought that maybe it's using the new version of PurgeCSS which uses `safelist` instead, but when I set the whitelistPatterns like this :\n\n```\npurgeCSS: {\n whitelistPatterns: ['text-green-800', /^bg-/, /^text-/, /^border-/]\n },\n```\n\nThen the `text-green-800` class is successfully protected. So i'm completely lost, nothing seems to work. And obviously only happening on production, so difficult to debug.\n\nI've already found this post which gives exactly what I've done :\nPurgeCSS whitelist patterns with TailwindCSS\n\nIf anyone has a lead... Thank you!\n\n========================================\n\nCode:\n```text\npurgeCSS: {\n whitelistPatterns: [/^bg-/, /^text-/, /^border-/]\n },\n```\n\n```text\npurgeCSS: {\n whitelistPatterns: ['text-green-800', /^bg-/, /^text-/, /^border-/]\n },\n```\n\n```text\ntext-green-800\n```\n\n```text\nbg-red-400\n```\n\n```text\nbg-{color}-400\n```\n\n```text\n/bg-/\n```\n\n```text\n/bg/\n```\n\n```text\n/^bg-.*/\n```\n\n```text\nsafelist\n```\n\n```text\ntext-green-800\n```\n\n```html\npurge: {\n content: [\n './components/**/*.{vue,js}',\n './layouts/**/*.vue',\n './pages/**/*.vue',\n './plugins/**/*.{js,ts}',\n './nuxt.config.{js,ts}'\n\n ],\n options: {\n // Whitelisting some classes to avoid purge\n safelist: [/^bg-/, /^text-/, /^border-/]\n }\n },\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nbg-blue-200\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ntailwind.config.js\n```\n\n========================================\n\nComments:\n- Which version of PurgeCSS are you using?\n- For god sake I was having the same issue as you and was trying to use `whitelistPatterns` (which was previously working). As a side note; to keep media queries I had to specify a regex like : `/^(\\D{2}:)?border-/`\n- Using gatsby 2.30.3 with gatsby-plugin-purgecss 5.0.0 require to use the old 'whitelistPatterns' key. Thanks @Baldráni","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":123,"estimatedTokens":692}}821{"id":"stack-68028690","source":"stackoverflow","questionId":68028690,"title":"Is it possible to add .html at the end of the URL as you like while using NuxtJS or NextJS?","tags":["vue.js","next.js","nuxt.js","server-side-rendering"],"text":"Title: Is it possible to add .html at the end of the URL as you like while using NuxtJS or NextJS?\nTags: vue.js, next.js, nuxt.js, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nI am currently planning to develop a web application using **NuxtJS/NextJS** framework with SSR Universal architecture, I am facing difficulties related to SEO, because previously my project was written in .NET , so all URLs have `.html` at the end..\n\nEx:\n\n- domain.com/hotels (this is *Cate*)\n\n- domain.com/hotels-5-star.html (this is a *Sub cate* of Hotels Cate)\n\nThe example above is specific to my problem, which means that according to Google, the shorter the URL, the better, so my pages have all been shortened to a single \"/\", however because of the structure page has 2 hierarchies, Cate and Sub cate, so for Google to distinguish this, the URL (sub cate) must insert `.html` at the end.\n\nCan I use **NuxtJS/NextJS** build pages with the same URL as above?, I have researched but found a specific solution, maybe my experience is not much so I need the help of experts on **NuxtJS/NextJS**\n\n========================================\n\nTop Answer:\nI'm not an expert in SEO, but I would just use `5-star` as a query in `domain.com/hotels`\n\nThis would mean you could use the single hierarchy like so:\n\n`domain.com/hotels?rating=5-stars`\n\nAs far as using html files as URL routing for the site, the nuxt `generate` property builds the project into html files which is under your control. The structure comes from what you set in the pages directory\n\n========================================\n\nCode:\n```text\n.html\n```\n\n```text\n.html\n```\n\n```js\nbuildModules: [\n '@nuxtjs/router'\n]\n```\n\n```js\nimport Vue from 'vue';\nimport VueRouter from 'vue-router';\n\nVue.use(VueRouter);\n\nconst page = path => () => import(`./pages/${path}.vue`).then(m => m.default || m);\n\nconst routes = [\n {\n path: '/hotels-:star-star.html',\n name: 'hotels',\n props: true,\n component: page('hotels')\n }\n];\nexport function createRouter(){\n return new VueRouter({\n routes\n });\n}\n```\n\n```html\n<template>\n <main>\n {{ star }}\n </main>\n</template>\n\n<script>\nexport default{\n props: {\n star: {\n type: Number\n }\n }\n}\n</script>\n```\n\n```text\nnuxtjs\n```\n\n```text\n@nuxtjs/router\n```\n\n```text\n5-star\n```\n\n```text\ndomain.com/hotels\n```\n\n```text\ndomain.com/hotels?rating=5-stars\n```\n\n```text\ngenerate\n```\n\n```text\n-- pages\n---- hotels.vue\n```\n\n```text\n-- pages\n---- hotels\n------ index.vue\n```\n\n```text\ndomain.com/hotels/\n```\n\n```text\ndomain.com/hotels/\n```\n\n```text\n.html\n```\n\n```text\n.vue\n```\n\n```text\ndomain.com/h5s\n```\n\n```text\ndomain.com/hotels/5-stars\n```\n\n```text\ndomain.com/hotels/?rating=5\n```\n\n========================================\n\nComments:\n- Why not just use subfolders? Eg., `domain.com/hotels/five-star`? That's how Nuxt's setup to work already.\n- @selfagency Good question. According to google, the shorter the URL, the more optimized it will be for SEO, and Google Search will also rate that website higher than other websites.\n- This is fine, but there will be a small problem, assuming you are SEO with the keyword \"5 star hotel in New York\", then the URL should be `/5-star-hotel-in-new-york.html` is best with Google.\n- Thanks for your answer, you're right. But since the old version of my project existed such URL structure, especially for `sub-cate-name.html`, so the migration to **NuxtJS/NextJS** must keep the current URLs as it is,","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":156,"estimatedTokens":878}}822{"id":"stack-67212731","source":"stackoverflow","questionId":67212731,"title":"Dynamically created classes not available when using 'nuxt build' - tailwindcss nuxtjs","tags":["nuxt.js","tailwind-css","postcss"],"text":"Title: Dynamically created classes not available when using 'nuxt build' - tailwindcss nuxtjs\nTags: nuxt.js, tailwind-css, postcss\nSource: Stack Overflow\n\nQuestion:\nI have a nuxtjs project that I use with tailwindcss.\n\nIn that project I generate classes on the fly for negative margins like so:\n\n```\n\n```\n\nThe entire project works fine locally, but if I run `nuxt build; nuxt start;` it gets compiled without errors but none of the dynamic classes seem to work.\n\nSo I finally found out that the `nuxt build` process does some ***css tree shaking***, and since these classes are not included anywhere in the dom, they are not included in the css build process.\n\nTo test this I have created a hidden div like so:\n\n```\nok needed classes\n```\n\nAnd voila, that will make my project workable after `nuxt build` since now the classes needed are present in the dom and will be included.\n\nThis seems very hacky!\n\n**Now to my question:**\n\nWhat would be the proper way to include dynamically created classes in the build process in a nuxtjs project?\n\n**UPDATED tailwind.config.js (Did NOT work with JIT MODE turned on!)**\n\n```\nconst colors = require(\"tailwindcss/colors\")\nmodule.exports = {\n purge: {\n enabled: process.env.NODE_ENV === 'production',\n content: [\n 'components/**/*.vue',\n 'layouts/**/*.vue',\n 'pages/**/*.vue',\n 'plugins/**/*.js',\n 'nuxt.config.js',\n // TypeScript\n 'plugins/**/*.ts',\n 'nuxt.config.ts'\n ],\n // UPDATE: safelist does NOT work in combination with JIT\n options: {\n safelist: ['mt-0', '-mt-8', '-mt-16', '-mt-24', '-mt-32', '-mt-40', '-mt-48', '-mt-56', '-mt-64', '-mt-72', '-mt-80'],\n }\n },\n darkMode: false, // or 'media' or 'class'\n theme: {\n extend: {\n colors: {\n emerald: colors.emerald,\n gray: colors.trueGray,\n cyan: colors.cyan\n },\n },\n },\n variants: {\n extend: {},\n },\n plugins: [],\n}\n```\n\n========================================\n\nTop Answer:\nYou can safelist classes with Tailwind CSS version 3.\nI use HTML components in my CMS and for that I have safelisted a couple of classes!\n\n```\nmodule.exports = {\ndarkMode: \"class\",\ncontent: [\n \"./components/**/*.{js,vue,ts}\",\n \"./layouts/**/*.vue\",\n \"./pages/**/*.vue\",\n \"./plugins/**/*.{js,ts}\",\n \"./nuxt.config.{js,ts}\",\n],\nsafelist: [\n 'border-l-2',\n 'border-blue-500',\n {\n pattern: /(bg|text|border)-(red|green|blue|purple|yellow)-(100|200|300|400|500)/,\n },\n {\n pattern: /(h|w)-(12|16|24|32|48|64|72|96)/,\n },\n 'absolute',\n '-mt-9',\n '-ml-9',\n 'pl-4',\n 'overflow-scroll'\n],}\n```\n\n========================================\n\nCode:\n```html\n<div class=\"mins-1\" :class=\"['-mt-'+ m1*8]\"></div>\n```\n\n```html\n<div class=\"hidden -mt-8 -mt-16 -mt-24 -mt-32 -mt-40 -mt-48 -mt-56 -mt-64 -mt-72 -mt-80\">ok needed classes</div>\n```\n\n```js\nconst colors = require(\"tailwindcss/colors\")\nmodule.exports = {\n purge: {\n enabled: process.env.NODE_ENV === 'production',\n content: [\n 'components/**/*.vue',\n 'layouts/**/*.vue',\n 'pages/**/*.vue',\n 'plugins/**/*.js',\n 'nuxt.config.js',\n // TypeScript\n 'plugins/**/*.ts',\n 'nuxt.config.ts'\n ],\n // UPDATE: safelist does NOT work in combination with JIT\n options: {\n safelist: ['mt-0', '-mt-8', '-mt-16', '-mt-24', '-mt-32', '-mt-40', '-mt-48', '-mt-56', '-mt-64', '-mt-72', '-mt-80'],\n }\n },\n darkMode: false, // or 'media' or 'class'\n theme: {\n extend: {\n colors: {\n emerald: colors.emerald,\n gray: colors.trueGray,\n cyan: colors.cyan\n },\n },\n },\n variants: {\n extend: {},\n },\n plugins: [],\n}\n```\n\n```text\nnuxt build; nuxt start;\n```\n\n```text\nnuxt build\n```\n\n```text\nnuxt build\n```\n\n```js\n// tailwind.config.js\nmodule.exports = {\n purge: {\n // Configure as you need\n content: ['./src/**/*.html'],\n // These options are passed through directly to PurgeCSS\n options: {\n // List your classes here, or you can even use RegExp\n safelist: ['bg-red-500', 'px-4', /^text-/],\n blocklist: [/^debug-/],\n keyframes: true,\n fontFace: true,\n },\n },\n // ...\n}\n```\n\n```text\nsafelist\n```\n\n```text\nstub.html\n```\n\n```text\nsafelist\n```\n\n```js\nmodule.exports = {\n mode: 'jit',\n // These paths are just examples, customize them to match your project structure\n purge: [\n './public/**/*.html',\n './src/**/*.{js,jsx,ts,tsx,vue}',\n ],\n ...\n}\n```\n\n```text\nmodule.exports = {\ndarkMode: \"class\",\ncontent: [\n \"./components/**/*.{js,vue,ts}\",\n \"./layouts/**/*.vue\",\n \"./pages/**/*.vue\",\n \"./plugins/**/*.{js,ts}\",\n \"./nuxt.config.{js,ts}\",\n],\nsafelist: [\n 'border-l-2',\n 'border-blue-500',\n {\n pattern: /(bg|text|border)-(red|green|blue|purple|yellow)-(100|200|300|400|500)/,\n },\n {\n pattern: /(h|w)-(12|16|24|32|48|64|72|96)/,\n },\n 'absolute',\n '-mt-9',\n '-ml-9',\n 'pl-4',\n 'overflow-scroll'\n],}\n```\n\n========================================\n\nComments:\n- What is your version of tailwind ?\n- Latest 2.1.1 unsing @nuxt/tailwindcss 4.0.3\n- see my updated tailwind css file with options safelist, that did not work ...\n- It won't work if you are using JIT which you did not mention in the post. With JIT the best way you can do right now is to place some stub file like `stub.html` somewhere with all the classes you need to generate in advance\n- Ok I removed jit and now it works, great! So it is either fast development and adding a stub file, or removing jit and have a safelist if I understand you correctly?\n- Right now yes, but keep an eye on the docs, I'm sure tailwind team will add some way to generate classes for JIT mode too\n- Thank you for your TIME to explain the problem!\n- I am using jit in nuxtjs config, but it did not help.\n- What about the rest (`purge` key containing an array).\n- Can you give more debugging details?\n- I also believe that you did not fully understand my issue ...\n- I did, just did not spent more time digging into the configuration issues. Also, I kinda prefer using `windy`. Glad you found a solution.","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":248,"estimatedTokens":1483}}823{"id":"stack-54055360","source":"stackoverflow","questionId":54055360,"title":"How to make Vuex state update after axios call","tags":["vuex","nuxt.js"],"text":"Title: How to make Vuex state update after axios call\nTags: vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a Nuxt app and I'm fetching some data from a node backend I've got running on my localhost.\n\nI have a plugin getApps.js\n\n```\nexport default ({ store }) => {\n store.dispatch('getApps')\n}\n```\n\nThat is calling a getApps action in my Vuex\n\n```\nactions: {\n getApps (context) {\n const {commit, state} = context\n commit('setLoading', true)\n\n let url = `apps?limit=${state.loadLimit}&page=${state.page}`\n\n if (state.query)\n url = `${url}/q=${state.query}`\n\n this.$axios.get(url)\n .then((res) => {\n const apps = res.data.apps\n console.log(apps)\n commit('addApps', apps)\n commit('setPage', state.page + 1)\n commit('setLoading', false)\n\n })\n }\n ...\n```\n\nThe console.log here does indeed return the list of apps, however, after my addApps mutation\n\n```\naddApps (state, payload) {\n state.apps = payload\n}\n```\n\nAnd this is the state definition\n\n```\nstate: () => ({\n apps: [],\n query: '',\n loading: false,\n filters: [],\n loadLimit: 25,\n page: 1,\n showFilters: true,\n currentUser: null,\n showLoginModal: false,\n showCreateAppModal: false\n})\n```\n\nThe state doesn't get updated. As far as I could tell, this is due to the async nature of actions. I did also try to wrap the action around an async and prepend an await to the axios call, however, this did not work.\n\nWhy is this happening? How do I have to structure my code to make it work?\n\n========================================\n\nCode:\n```text\nexport default ({ store }) => {\n store.dispatch('getApps')\n}\n```\n\n```text\nactions: {\n getApps (context) {\n const {commit, state} = context\n commit('setLoading', true)\n\n let url = `apps?limit=${state.loadLimit}&page=${state.page}`\n\n if (state.query)\n url = `${url}/q=${state.query}`\n\n this.$axios.get(url)\n .then((res) => {\n const apps = res.data.apps\n console.log(apps)\n commit('addApps', apps)\n commit('setPage', state.page + 1)\n commit('setLoading', false)\n\n })\n }\n ...\n```\n\n```text\naddApps (state, payload) {\n state.apps = payload\n}\n```\n\n```text\nstate: () => ({\n apps: [],\n query: '',\n loading: false,\n filters: [],\n loadLimit: 25,\n page: 1,\n showFilters: true,\n currentUser: null,\n showLoginModal: false,\n showCreateAppModal: false\n})\n```\n\n```text\nexport default async ({ store }) => {\n await store.dispatch('getApps')\n}\n```\n\n```text\nactions: {\n getApps (context) {\n ...\n return this.$axios.get(url)\n .then((res) => {\n const apps = res.data.apps\n\n commit('addApps', apps)\n ...\n })\n },\n ...\n}\n```\n\n```text\nactions: {\n async getApps (context) {\n ...\n await this.$axios.get(url)\n .then((res) => {\n const apps = res.data.apps\n\n commit('addApps', apps)\n ...\n })\n },\n ...\n}\n```\n\n```text\nawait\n```\n\n```text\nawait\n```\n\n```text\nasync\n```\n\n```text\nawait\n```\n\n========================================\n\nComments:\n- show your state definition\n- Sure, just added it right below the mutation\n- Awesome, it does work indeed! Thanks a lot for your help\n- @ilrock Cool! Glad if it helps. Up vote is more appreciated :D\n- Totally right, sorry! Just marked it as best answer. I also upvoted it now :)","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":186,"estimatedTokens":813}}824{"id":"stack-67478576","source":"stackoverflow","questionId":67478576,"title":"How to setup a netlify form in Nuxt","tags":["vue.js","nuxt.js","single-page-application","vue-router","netlify"],"text":"Title: How to setup a netlify form in Nuxt\nTags: vue.js, nuxt.js, single-page-application, vue-router, netlify\nSource: Stack Overflow\n\nQuestion:\nWhen I navigate to a form using vue-router by adding a link with a `` element, the form does not work. When I hit submit I get a 404 response.\n\nHowever, if I navigate to it using an `` tag (triggering a page reload) then it works perfectly.\n\nI suspect that this has to do with the page rendering as a SPA and for some reason not loading an important part of the form for Netlify unless the form page is reloaded? Why is this happening and is there an elegant solution to the problem? I could just replace all links to forms with tags but I'm sure that there is a better solution, I just don't understand the problem well enough to find it.\n\nFor context, I am using Nuxt. The forms are recognized by Netlify on the backend and can accept submission with the tag link so that is not the problem.\n\n========================================\n\nCode:\n```text\n<router-link>\n```\n\n```text\n<a>\n```\n\n```html\n<template>\n <div>\n <form\n netlify\n action=\"/\"\n method=\"POST\"\n name=\"Contact\"\n >\n <input type=\"hidden\" name=\"form-name\" value=\"Contact\" />\n <!-- ... -->\n </form>\n </div>\n</template>\n```\n\n```text\ntarget: 'static'\n```\n\n```text\ntarget: 'server'\n```\n\n```text\nssr: true\n```\n\n```text\n<nuxt-link>\n```\n\n```text\n<router-link>\n```\n\n```text\n<router-link>\n```\n\n```text\n<a>\n```\n\n========================================\n\nComments:\n- See this : stackoverflow.com/a/62287223/14945696\n- Thank you so much for your answer! Unfortunately, it is already set to target:static and sr:true already. I was originally using as well but it was not working either. This is really confusing to me since I have used forms with Netlify on other Nuxt projects that have worked. I am unable to the repo since it is private, but is there anything else that I should check or code that I should ? Thank you again!\n- Hm, I didn't add a netlify form on Nuxt recently, will probably do in the next future hours/days. But you can check that your form is actually properly generated by the backend (disable the JS for this). Check that there is no build cache issues (had once with Netlify, image added to my answer). Double-check that you do have a `data-netlify=\"true\"` on your form and maybe also add a honeypot field: docs.netlify.com/forms/spam-filters/#honeypot-field If it's still not working, I can guess that you can create a new project and try to spot every small difference. A minor typo or alike IMO.\n- Hello again! I've been driving myself crazy trying to figure this out with no luck. As you suggested, I tried to make a new project to spot the differences but even that project is not working now. Is there any chance you might be able to look at this test repository and let me know if you see anything broken? It must be so obvious and I've just been staring for too long. github.com/John-Church/test\n- Thank you again for your help. Adding the hidden field fixed it for me. What confuses me, though, is that it appears I've accidentally left out the hidden field on other sites and the forms have still worked? Also, why would they work without the hidden field when a page refresh is triggered?","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":76,"estimatedTokens":814}}825{"id":"stack-53098309","source":"stackoverflow","questionId":53098309,"title":"How to cherry-pick bootstrap-vue.js modules in nuxt.js?","tags":["javascript","vue.js","nuxt.js","bootstrap-vue"],"text":"Title: How to cherry-pick bootstrap-vue.js modules in nuxt.js?\nTags: javascript, vue.js, nuxt.js, bootstrap-vue\nSource: Stack Overflow\n\nQuestion:\nI am not able to understand how to cherry-pick bootstrap-vue.js modules in nuxt.js\n\nThe below code in `nuxt.config.js` is pulling entire library (excluding css) but as mentioned above how to include required modules.\n\n```\nmodules: [\n ['bootstrap-vue/nuxt', { css: false }]\n]\n```\n\nI referring docs here:\n\nhttps://bootstrap-vue.js.org/docs/ please check for `Individual\ncomponents and directives` section.\n\n- https://nuxtjs.org/guide/modules/#provide-plugins\n\nThings described in above docs are passing over my head :) Please help, thanks.\n\n========================================\n\nCode:\n```text\nmodules: [\n ['bootstrap-vue/nuxt', { css: false }]\n]\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nIndividual\ncomponents and directives\n```\n\n```text\nplugins: [\n '@/plugins/mybs',\n ],\n```\n\n```text\nimport Vue from 'vue'\n\nimport bModal from 'bootstrap-vue/es/components/modal/modal'\nimport bModalDirective from 'bootstrap-vue/es/directives/modal/modal'\n\nVue.component('b-modal', bModal);\nVue.directive('b-modal', bModalDirective);\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":57,"estimatedTokens":293}}826{"id":"stack-67219934","source":"stackoverflow","questionId":67219934,"title":"Paddle with Nuxt/Vue.js","tags":["javascript","vue.js","vue-component","nuxt.js","paddle-paddle"],"text":"Title: Paddle with Nuxt/Vue.js\nTags: javascript, vue.js, vue-component, nuxt.js, paddle-paddle\nSource: Stack Overflow\n\nQuestion:\nHas anyone implemented Paddle with Nuxt? Trying to run this within a Nuxt app page (component):\n\n```\n\n Paddle.Setup({ vendor: 1234567 });\n\n```\n\nI have tried three ways unsuccessfully.\n\n- NPM with paddle-sdk\n\nhttps://www.npmjs.com/package/paddle-sdk\n\nOut of data dependencies and will not build on a modern project. When installing npm i --save paddle-sdk, I get the following errors. Some of these dependencies are not available via npm:\n\n```\nWARN in ./node_modules/paddle-sdk/node_modules/keyv/src/index.js friendly-errors 09:02:21\n\nCritical dependency: the request of a dependency is an expression friendly-errors 09:02:21\n friendly-errors 09:02:21\n\n ERROR Failed to compile with 4 errors friendly-errors 09:02:21\n\nThese dependencies were not found: friendly-errors 09:02:21\n friendly-errors 09:02:21\n* dns in ./node_modules/cacheable-lookup/index.js friendly-errors 09:02:21\n* fs in ./node_modules/paddle-sdk/node_modules/got/dist/source/request-as-event-emitter.js, ./node_modules/paddle-sdk/node_modules/got/dist/source/utils/get-body-size.js\n* net in ./node_modules/paddle-sdk/node_modules/got/dist/source/utils/timed-out.js friendly-errors 09:02:21\n friendly-errors 09:02:21\nTo install them, you can run: npm install --save dns fs net friendly-errors 09:02:21\n```\n\n- Nuxt Plugins\n\nhttps://nuxtjs.org/docs/2.x/directory-structure/plugins/\n\nCannot create a nuxt plugin with a remote (third party) script, only local in the plugins directory. Paddle from their website asks: \"Please do not self-host Paddle.js, this will prevent you from receiving bug fixes and new features.\"\n\n- Head method\n\nI can implement the script in the head method within the page, but I cannot execute methods from the script within the nuxt page. In other words this works:\n\n``\n\nBut this does not:\n\n```\n\n Paddle.Setup({ vendor: 1234567 });\n\n```\n\nHere is my head portion of my .vue file:\n\n```\nhead: {\n script: [\n {\n hid: 'Paddle',\n src: 'https://cdn.paddle.com/paddle/paddle.js',\n async: true,\n defer: false\n }\n ]\n },\n```\n\nAnyone had any luck or alternative solutions?\n\n========================================\n\nCode:\n```text\n<script src=\"https://cdn.paddle.com/paddle/paddle.js\"></script>\n<script type=\"text/javascript\">\n Paddle.Setup({ vendor: 1234567 });\n</script>\n```\n\n```text\nWARN in ./node_modules/paddle-sdk/node_modules/keyv/src/index.js friendly-errors 09:02:21\n\nCritical dependency: the request of a dependency is an expression friendly-errors 09:02:21\n friendly-errors 09:02:21\n\n ERROR Failed to compile with 4 errors friendly-errors 09:02:21\n\nThese dependencies were not found: friendly-errors 09:02:21\n friendly-errors 09:02:21\n* dns in ./node_modules/cacheable-lookup/index.js friendly-errors 09:02:21\n* fs in ./node_modules/paddle-sdk/node_modules/got/dist/source/request-as-event-emitter.js, ./node_modules/paddle-sdk/node_modules/got/dist/source/utils/get-body-size.js\n* net in ./node_modules/paddle-sdk/node_modules/got/dist/source/utils/timed-out.js friendly-errors 09:02:21\n friendly-errors 09:02:21\nTo install them, you can run: npm install --save dns fs net friendly-errors 09:02:21\n```\n\n```text\n<script type=\"text/javascript\">\n Paddle.Setup({ vendor: 1234567 });\n</script>\n```\n\n```text\nhead: {\n script: [\n {\n hid: 'Paddle',\n src: 'https://cdn.paddle.com/paddle/paddle.js',\n async: true,\n defer: false\n }\n ]\n },\n```\n\n```text\n<script src=\"https://cdn.paddle.com/paddle/paddle.js\"></script>\n```\n\n```text\nhead: {\n script: [{\n src: 'https://cdn.paddle.com/paddle/paddle.js',\n }]\n}\n```\n\n```text\nmounted() {\n Paddle.Setup({ vendor: 1234567 });\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nYou must specify a valid Paddle Vendor ID\n```\n\n========================================\n\nComments:\n- What are the out of date dependencies? What errors do you get with method 1?\n- Did you import the script using `head()`? In the first method, Could you please the plugin code?\n- @ImanShafiei I added the code here.\n- @JesseRezaKhorasanee I added the dependency errors too.\n- This loads only on the second visit to the site, can I force it to load during the initial page load?\n- Do you mean that when you refresh the page, the `Paddle` variable is undefined? I tested it, and it was working. Also, maybe you want to use `defer: true` or `async: true`. See this w3schools.com/tags/att_script_defer.asp for more info.\n- No, only on a refresh does the Paddle CSS and button work.\n- Ok, I see now. It's because we put the initiator in the `mounted()`. When do you want to `Paddle` initiate? I think you can put the initiator in a method and call it when you want. If you have more information, I'll be able to help you more.\n- I moved it to beforeCreated and will see if that helps. Thank you for your assistance.","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":159,"estimatedTokens":1454}}827{"id":"stack-52528983","source":"stackoverflow","questionId":52528983,"title":"How to validate route parameter in Nuxt?","tags":["javascript","vue.js","async-await","nuxt.js"],"text":"Title: How to validate route parameter in Nuxt?\nTags: javascript, vue.js, async-await, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to validate route parameter in my page component like this:\n\n```\nasync validate({ params, store }) {\n await store.dispatch(types.VALIDATE_PARAMS_ASYNC, params.id)\n}\n```\n\nThen in store:\n\n```\nasync [types.VALIDATE_PARAMS_ASYNC]({state, commit, dispatch}, payload) {\n try {\n const res = await this.$axios.$post('/api/params/validate', {\n params: payload\n })\n commit(types.MUTATE_SET_INFO, res.data) // this mutation is in another module. This doesn't work either\n return true\n } catch(e) {\n return false\n }\n}\n```\n\nThis doesn't work at all. Even if I type invalid params, it still loads the page. Please help!\n\n========================================\n\nCode:\n```text\nasync validate({ params, store }) {\n await store.dispatch(types.VALIDATE_PARAMS_ASYNC, params.id)\n}\n```\n\n```text\nasync [types.VALIDATE_PARAMS_ASYNC]({state, commit, dispatch}, payload) {\n try {\n const res = await this.$axios.$post('/api/params/validate', {\n params: payload\n })\n commit(types.MUTATE_SET_INFO, res.data) // this mutation is in another module. This doesn't work either\n return true\n } catch(e) {\n return false\n }\n}\n```\n\n```text\nasync validate({ params, store}) {\n // await operations\n return true // if the params are valid\n return false // will stop Nuxt.js to render the route and display the error page\n}\n```\n\n```text\nasync validate({ params, store }) {\n return await store.dispatch(types.VALIDATE_PARAMS_ASYNC, params.id)\n}\n```\n\n```text\nvalidate\n```\n\n========================================\n\nComments:\n- I am returning the boolean!\n- not here : async validate({ params, store }) { await store.dispatch(types.VALIDATE_PARAMS_ASYNC, params.id) }","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":77,"estimatedTokens":459}}828{"id":"stack-66325289","source":"stackoverflow","questionId":66325289,"title":"Is it possible to use vite with Nuxt.js for fast reloading?","tags":["vue.js","nuxt.js","vite"],"text":"Title: Is it possible to use vite with Nuxt.js for fast reloading?\nTags: vue.js, nuxt.js, vite\nSource: Stack Overflow\n\nQuestion:\nAccording to this documentation https://v3.vuejs.org/guide/installation.html#vite, we can use vite with Vue.js for fast reloading.\n\nI'm now switching to Nuxt.js and I'm wondering if it is possible to use vite with Nuxt.js.\n\nI did not find an official way to do that, but it there any way?","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":10,"estimatedTokens":105}}829{"id":"stack-58931647","source":"stackoverflow","questionId":58931647,"title":"nuxt component : computed vs data","tags":["vue-component","nuxt.js"],"text":"Title: nuxt component : computed vs data\nTags: vue-component, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn my nuxt component, I can't understand the difference between `computed` and `data`. I get the difference between `data` and `asyncData` but there is nothing regarding those two attributes.\n\n```\n\n {{computedMessage}}\n {{dataMessage}}\n\n export default {\n computed: {\n computedMessage(){\n return this.$store.state.whatever;\n }\n },\n data() {\n return {\n dataMessage: \"Hi there\"\n }\n }\n }\n\n```\n\nIf `data` is 100% static, then why make it a function?\n\nIf I want to have `process.env` in the function, should it be in `computed` or in `data`?\n\n========================================\n\nTop Answer:\nWell the difference between `data` and `computed` is that computed is reactive and data is static. So if you want to use data that gets automatically updated, you have to use `computed`.\n\n`computed`is for example often used when you have to wait for data (e.g. from REST api), but you don't want to block your UI. So you assign a `computed`variable and the part of your UI is updated when the data has arrived.\n\nTo understand, why `data` needs to be a function, you should have a look at this.\n\n========================================\n\nCode:\n```text\n<template>\n {{computedMessage}}\n {{dataMessage}}\n</template>\n<script>\n export default {\n computed: {\n computedMessage(){\n return this.$store.state.whatever;\n }\n },\n data() {\n return {\n dataMessage: \"Hi there\"\n }\n }\n }\n</script>\n```\n\n```text\ncomputed\n```\n\n```text\ndata\n```\n\n```text\ndata\n```\n\n```text\nasyncData\n```\n\n```text\ndata\n```\n\n```text\nprocess.env\n```\n\n```text\ncomputed\n```\n\n```text\ndata\n```\n\n```text\nexport default {\n mounted() {\n console.log(this.adults)\n }\n data() {\n return {\n users: [\n { name: 'Jack', age: 12 },\n { name: 'Jill', age: 53 },\n { name: 'Smith', age: 29 },\n { name: 'Matt', age: 18 }\n ]\n }\n },\n computed: {\n adults() {\n return this.users.filter(user => user.age >= 18)\n }\n }\n}\n```\n\n```text\ncomputed\n```\n\n```text\ndata\n```\n\n```text\ndata\n```\n\n```text\ncomputed\n```\n\n```text\nthis.adults\n```\n\n```text\ncomputed\n```\n\n```text\nmethod\n```\n\n```text\ncomputed\n```\n\n```text\ngetters\n```\n\n```text\ndata\n```\n\n```text\ncomputed\n```\n\n```text\ndata\n```\n\n```text\ndata\n```\n\n```text\ncomputed\n```\n\n```text\ndata\n```\n\n```text\nthis\n```\n\n```text\nprocess.env\n```\n\n```text\ndata\n```\n\n```text\ncomputed\n```\n\n```text\ncomputed\n```\n\n```text\ncomputed\n```\n\n```text\ncomputed\n```\n\n```text\ndata\n```\n\n========================================\n\nComments:\n- This isn't correct. Data in Vue is reactive. vuejs.org/v2/guide/instance.html#Data-and-Methods\n- no, data is not reactive. If you want to change it, you have to change this explicit! The view reacts on changed data, but data itself is not reacting on changes...\n- That is not what reactive means in the context of Vuejs. Reactive means that Vue will react to changes to the property. It does not mean that the property will react to changes made to anything other than itself. Indeed, computed properties only behave reactively when watching reactive properties. Try returning a value like `Date.now()`, which is not reactive, from a computed property. The timestamp will not change throughout the lifespan of the component, because computed properties cache their response, and only update due to reactivity.\n- See this link where they go over how reactive properties are declared: vuejs.org/v2/guide/…. Notice, they're talking specifically about `data`\n- computed sets a link to something. so calling it will give you the source.","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":33,"totalLines":219,"estimatedTokens":908}}830{"id":"stack-63947473","source":"stackoverflow","questionId":63947473,"title":"Vuetify Autocomplete Links","tags":["vue.js","hyperlink","autocomplete","vuetify.js","nuxt.js"],"text":"Title: Vuetify Autocomplete Links\nTags: vue.js, hyperlink, autocomplete, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am wondering how I can attach links to items within a Vuetify autocomplete. I would like to do this so that it would act as a search bar. As of right now, I can attach links to the v-list-item but the link won't cover the entire width of the container. It appears to just form a link around the text instead of the entire item. I've tried to wrap the entire component but that doesn't seem to work either. I've also tried looking at the docs (https://vuetifyjs.com/en/components/autocompletes/) but I can't seem to find anything on making items links there either. Thanks for any help in advance.\n\nhttps://i.sstatic.net/RU6l4.png\n\n```\n\n \n \n \n \n \n {{item.username}}\n \n \n \n \n \n \n```\n\n========================================\n\nCode:\n```js\n<v-autocomplete\n v-model=\"model\"\n :items=\"users\"\n :loading=\"isLoading\"\n :search-input.sync=\"search\"\n clearable\n hide-details\n hide-selected\n item-text=\"username\"\n item-value=\"symbol\"\n placeholder=\"Search\"\n flat\n solo\n dense\n >\n <template v-slot:item=\"{ item }\">\n <v-list>\n <v-list-item-group v-model=\"item\">\n <v-list-item-content>\n <v-list-item link :to=\"'users/' + item.id\">\n {{item.username}}\n </v-list-item>\n </v-list-item-content>\n </v-list-item-group>\n </v-list>\n </template>\n </v-autocomplete>\n```\n\n```html\n<v-autocomplete\n...\n>\n\n <template v-slot:item=\"{ item }\">\n <v-list-item link :to=\"'users/' + item.id\">{{item.username}}</v-list-item>\n </template>\n\n</v-autocomplete>\n```\n\n```text\n<v-list-item/>\n```\n\n```text\n<v-list/>\n```\n\n========================================\n\nComments:\n- This results in a link, but does not redirect. The drop-down menu remains\n- @avimimoun in his demo that's true yeah, I tried locally on my project and link seems to work - redirects to any page normally when clicked\n- @avimimoun, that's true because the demo does not have vue-router configured. That's why the `:to` prop of v-list-item does not work. More info on the `:to` prop here: router.vuejs.org/api/#to","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":84,"estimatedTokens":575}}831{"id":"stack-50670964","source":"stackoverflow","questionId":50670964,"title":"Importing external .js file to nuxt.config.js","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Importing external .js file to nuxt.config.js\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to import config.js which includes project's API keys. But It returns undefined.\n\n```\n//config.js\nvar config = {\n fbAPI: \"key\"\n}\n```\n\n-\n\n```\n//nuxt.config.js\n\nconst cfg = require('./config')\nenv: {\n fbAPI: cfg.apiKey\n}\n```\n\nIs this problem about run-time or am I missing something?\n\n========================================\n\nCode:\n```text\n//config.js\nvar config = {\n fbAPI: \"key\"\n}\n```\n\n```text\n//nuxt.config.js\n\nconst cfg = require('./config')\nenv: {\n fbAPI: cfg.apiKey\n}\n```\n\n```text\nvar config = {\n fbAPI: \"key\"\n}\n\nmodule.exports = config;\n```\n\n```text\nmodules.export\n```\n\n```text\nconfig.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":61,"estimatedTokens":183}}832{"id":"stack-79900219","source":"stackoverflow","questionId":79900219,"title":"Nuxt useFetch does not refetch on URL parameter change","tags":["vue.js","nuxt.js","nuxtui"],"text":"Title: Nuxt useFetch does not refetch on URL parameter change\nTags: vue.js, nuxt.js, nuxtui\nSource: Stack Overflow\n\nQuestion:\nGiven this Nuxt example code of the app root component using the Nuxt UI calendar component to handle the current selected day\n\n```\n\nimport { today, getLocalTimeZone } from '@internationalized/date';\n\nconst foo = 'some-id'; // this is a page parameter but for the sake of simplicity...\n\nconst currentSelectedDate = shallowRef(today(getLocalTimeZone()));\n\nconst currentSelectedISODate = computed(() => {\n return currentSelectedDate.value.toString();\n});\n\n \n \n \n \n\n```\n\nNow I got a child component expecting the values as props\n\n```\n\nconst { foo, bar } = defineProps();\n\n// does not refetch on bar ( isoDate ) change\nconst { data, pending, error } = await useFetch(`/api/${foo}/${bar}`);\n\n \n Foo: {{ foo }} \n Bar: {{ bar }} \n \n \n data: {{ data }} \n pending: {{ pending }}\n error: {{ error }} \n \n\n```\n\nFor the sake of simplicity I created an API endpoint at\n\n/api/[foo]/[bar].get.ts\n\n```\nexport default defineEventHandler(async (event) => {\n return new Date().toISOString();\n});\n```\n\nI can see that the props change but `useFetch` won't refetch if `bar` changes. Whenever I select another day I can see that `bar` changes but `data` never changes. Further there is no API call so `useFetch` is not reactive anymore.\n\n*I'm currently working on a sandbox*\n\nhttps://stackblitz.com/edit/nuxt-starter-a1s1dox4?file=app%2Fapp.vue\n\nHow can I take care of the reactivity?\n\n========================================\n\nCode:\n```js\n<script setup lang=\"ts\">\nimport { today, getLocalTimeZone } from '@internationalized/date';\n\nconst foo = 'some-id'; // this is a page parameter but for the sake of simplicity...\n\nconst currentSelectedDate = shallowRef(today(getLocalTimeZone()));\n\nconst currentSelectedISODate = computed(() => {\n return currentSelectedDate.value.toString();\n});\n</script>\n\n<template>\n <UApp>\n <UCalendar v-model:model-value=\"currentSelectedDate\" />\n <Child :foo=\"foo\" :bar=\"currentSelectedISODate\" />\n </UApp>\n</template>\n```\n\n```js\n<script setup lang=\"ts\">\nconst { foo, bar } = defineProps<{\n foo: string;\n bar: string;\n}>();\n\n// does not refetch on bar ( isoDate ) change\nconst { data, pending, error } = await useFetch(`/api/${foo}/${bar}`);\n</script>\n\n<template>\n <UCard>\n <template #header> Foo: {{ foo }} </template>\n <template #footer> Bar: {{ bar }} </template>\n </UCard>\n <UCard>\n <template #header> data: {{ data }} </template>\n <div>pending: {{ pending }}</div>\n <template #footer> error: {{ error }} </template>\n </UCard>\n</template>\n```\n\n```ts\nexport default defineEventHandler(async (event) => {\n return new Date().toISOString();\n});\n```\n\n```text\nuseFetch\n```\n\n```text\nbar\n```\n\n```text\nbar\n```\n\n```text\ndata\n```\n\n```text\nuseFetch\n```\n\n```text\nconst { data, pending, error } = await useFetch(() => `/api/${foo}/${bar}`);\n```\n\n```text\nuseFetch\n```\n\n```text\ntoValue\n```\n\n```text\nfoo\n```\n\n```text\nbar\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":158,"estimatedTokens":743}}833{"id":"stack-49735461","source":"stackoverflow","questionId":49735461,"title":"NuxtJS & SASS Loader - Build with sass-loader (SCSS) on production","tags":["webpack","vue.js","sass","nuxt.js","sass-loader"],"text":"Title: NuxtJS & SASS Loader - Build with sass-loader (SCSS) on production\nTags: webpack, vue.js, sass, nuxt.js, sass-loader\nSource: Stack Overflow\n\nQuestion:\nI've added this lines to build with sass-loader on development (local) server:\n\n**nuxt.config.js**\n\n```\nmodule.exports = {\n\n mode: 'spa',\n\n build: {\n analyze: {\n analyzerMode: 'static',\n generateStatsFile: true,\n statsFilename: 'webpack-stats.json',\n openAnalyzer: false\n },\n vendor: [\n 'axios',\n 'vuetify'\n ],\n extend (config) {\n config.resolve.alias['vue'] = 'vue/dist/vue.common'\n const vueLoader = config.module.rules.find((rule) => rule.loader === 'vue-loader')\n vueLoader.options.loaders.scss = 'vue-style-loader!css-loader!sass-loader?' + JSON.stringify({\n includePaths: [\n path.resolve(__dirname), 'node_modules'\n ]\n })\n }\n }\n\n ...\n}\n```\n\nThe problem is on production, I've this error:\n\n Cannot find module \"!!vue-style-loader!css-loader!../../../node_modules/vue-loader/lib/style-compiler/index?{\"vue\":true,\"id\":\"data-v-7ef06ffa\",\"scoped\":true,\"hasInlineConfig\":true}!sass-loader?{\"includePaths\":[\"/app/config\",\"node_modules\"]}!../../../node_modules/vue-loader/lib/selector?type=styles&index=0!./index.vue\"\n\n*This question is available on Nuxt.js community (#c6871)*\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n\n mode: 'spa',\n\n build: {\n analyze: {\n analyzerMode: 'static',\n generateStatsFile: true,\n statsFilename: 'webpack-stats.json',\n openAnalyzer: false\n },\n vendor: [\n 'axios',\n 'vuetify'\n ],\n extend (config) {\n config.resolve.alias['vue'] = 'vue/dist/vue.common'\n const vueLoader = config.module.rules.find((rule) => rule.loader === 'vue-loader')\n vueLoader.options.loaders.scss = 'vue-style-loader!css-loader!sass-loader?' + JSON.stringify({\n includePaths: [\n path.resolve(__dirname), 'node_modules'\n ]\n })\n }\n }\n\n ...\n}\n```\n\n========================================\n\nComments:\n- you are facing this issue only on production ? no issue in development environment is it?\n- Yes issue only on production.","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":85,"estimatedTokens":526}}834{"id":"stack-54290443","source":"stackoverflow","questionId":54290443,"title":"Responsive flag for Plotly.js results in error when resizing window","tags":["vue.js","nuxt.js","plotly.js"],"text":"Title: Responsive flag for Plotly.js results in error when resizing window\nTags: vue.js, nuxt.js, plotly.js\nSource: Stack Overflow\n\nQuestion:\nWe are using Plotly.js in our Vue/Nuxt single page application. To ensure the created plots are automatically resized whenever their parent DOM node changes (for example when a user changes the window size), we enabled the `responsive: true` option for the Plotly chart.\n\nEnabling this flag automatically resizes the plots whenever the user has changed the screen size (as expected). However, the following error is logged multiple times while the window is being resized:\n\n```\nError: Resize must be passed a displayed plot div element.\n```\n\nReproducing this for a single plot or simple example didn't seem to work. From what we have discovered so far this only seems to happen when multiple plots are visible.\n\n========================================\n\nCode:\n```text\nError: Resize must be passed a displayed plot div element.\n```\n\n```text\nresponsive: true\n```\n\n```text\nresponsive: true\n```\n\n```text\nPlotly.purge($myPlot)\n```\n\n========================================\n\nComments:\n- But what in cases I don't want destroy my chart while navigate to another page because I want display it once user navigates back? Is there any way?\n- @DuFuS Because Plotly directly requires a DOM element to draw its chart, you would have to ensure the DOM element is defined on a \"global\" level instead of component level, at which point the issue in this SO post might no longer be relevant. Changing the DOM node used for a chart is possible, but peformance wise that is essentially the same as creating a new chart.","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":39,"estimatedTokens":411}}835{"id":"stack-67279784","source":"stackoverflow","questionId":67279784,"title":"Nuxt / Vue : Component call a Method in a page","tags":["vue.js","methods","components","nuxt.js"],"text":"Title: Nuxt / Vue : Component call a Method in a page\nTags: vue.js, methods, components, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nThere is my issue:\n\nMy page listing.vue list all products.\nTheses products are in a Component, `Product.vue`.\n\nIn this component, there is a button to add this product to a selection, displaying on the listing.vue.\n\npage/listing.vue :\n\n```\n\n \n \n \n \n \n \n- Produit 1\n \n- Produit 3\n \n \n\nexport default {\n methods: {\n addToSelection(id) {\n // Code to add Product to //\n }\n }\n}\n\n```\n\ncomponent/product.vue:\n\n```\n\n \n {{ product.title }}\n \n Add product to selection\n \n \n\nexport default {\n props: ['product'],\n}\n\n```\n\nThe problem is nuxt render an error:\n\nthe addToSelection method is unknown.\n\n========================================\n\nCode:\n```html\n<template>\n <div>\n <product v-for=\"....\" />\n \n <section>\n <ul>\n <li>Produit 1</li>\n <li>Produit 3</li>\n </section>\n </div>\n</template>\n\n<script>\nexport default {\n methods: {\n addToSelection(id) {\n // Code to add Product to <ul> //\n }\n }\n}\n</script>\n```\n\n```html\n<template>\n <div>\n {{ product.title }}\n <button @click=\"addToSelection(product.id)\">\n Add product to selection\n </button>\n </div>\n</template>\n\n<script>\nexport default {\n props: ['product'],\n}\n</script>\n```\n\n```text\nProduct.vue\n```\n\n```html\n<button @click=\"emitProductToParent(product.id)\">\n\n...\nmethods: {\n emitProductToParent(id) {\n this.$emit('input', id)\n }\n}\n```\n\n```html\n<Product @input=\"addToSelection\" v-for=\"....\" />\n```\n\n```text\nProduct.vue\n```\n\n```text\nListing.vue\n```\n\n========================================\n\nComments:\n- You should use `` or `` but not a mix as explained here: vuejs.org/v2/style-guide/…","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":134,"estimatedTokens":433}}836{"id":"stack-65752819","source":"stackoverflow","questionId":65752819,"title":"How to use Google tags in Nuxt.js","tags":["nuxt.js","google-tag-manager","gtag.js"],"text":"Title: How to use Google tags in Nuxt.js\nTags: nuxt.js, google-tag-manager, gtag.js\nSource: Stack Overflow\n\nQuestion:\nI'm on Nuxt.js 2.13 and I want to use Google tags in my project.\n\nBut there are several things that are not clear to me!\n\nFirst: there are two packages by pi0 in Nuxt.js community, @nuxtjs/gtm and @nuxtjs/google-gtag. Which one should I use?\n\nSecond: How can I use `dataLayer.push({'varName':'value'})` with these packages? As in their documentation they only instructed about `push('event')`.\n\n========================================\n\nCode:\n```text\ndataLayer.push({'varName':'value'})\n```\n\n```text\npush('event')\n```\n\n```js\n<script>\nexport default {\n middleware ({ $gtm }) {\n $gtm.push({ 'varName': 'value' })\n }\n}\n</script>\n```\n\n```text\n$gtm.push\n```\n\n```text\npages/index.vue\n```\n\n========================================\n\nComments:\n- thanks for your answer, but, the depricated version of `@Nuxt/gtm` is this package: `https://www.npmjs.com/package/@nuxtjs/google-tag-manager` and `https://github.com/nuxt-community/google-gtag-module` is still in Nuxt community and not depricated!\n- that's exactly what I explained","metadata":{"transformedAt":"2026-08-18T18:33:07.896Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":47,"estimatedTokens":296}}837{"id":"stack-63946467","source":"stackoverflow","questionId":63946467,"title":"Where to put 'monkeypatches' in Nuxt.js?","tags":["vue.js","nuxt.js","monkeypatching"],"text":"Title: Where to put 'monkeypatches' in Nuxt.js?\nTags: vue.js, nuxt.js, monkeypatching\nSource: Stack Overflow\n\nQuestion:\nwhere can I put 'monkeypatches' and 'my extensions' to prototypes of basic javascript objects in Nuxt framework to have it's functionality accesible accros all files ?\n\nfor example:\n\n```\nString.prototype.capitalize = function () {\n\n return this.replace(/\\w\\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});\n}\n```\n\n========================================\n\nTop Answer:\nThis is prototype pollution and a bad practice. There are better ways to common function:\n\n- Put them in a utility file (e.g. under `utils/helpers.js` and import them from there\n\n```\nexport const capitalize = s => s.replace(/\\w\\S*/g, \n txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()\n )\n```\n\n- Use a Nuxt plugin to `inject` the helper function, so it's available in all components (though this might be a bit overkill here). See here\n\nI highly suggest to avoid prototype pollution.\n\n========================================\n\nCode:\n```text\nString.prototype.capitalize = function () {\n\n return this.replace(/\\w\\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});\n}\n```\n\n```js\nexport default {\n plugins: ['~/plugins/my-extensions.js']\n}\n```\n\n```text\n~/plugins/my-extensions.js\n```\n\n```text\nnuxt.config.js\n```\n\n```js\nexport const capitalize = s => s.replace(/\\w\\S*/g, \n txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()\n )\n```\n\n```text\nutils/helpers.js\n```\n\n```text\ninject\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":70,"estimatedTokens":394}}838{"id":"stack-79863375","source":"stackoverflow","questionId":79863375,"title":"How to get rid of the background inside Vue.js double curly braces (mustache) in Visual Studio Code","tags":["javascript","typescript","vue.js","visual-studio-code","nuxt.js"],"text":"Title: How to get rid of the background inside Vue.js double curly braces (mustache) in Visual Studio Code\nTags: javascript, typescript, vue.js, visual-studio-code, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSorry, I really tried, but I can't find the corresponding setting inside the Visual Studio Code settings. After an update, it was just there, and I think it’s ugly and also distracting.\n\nTo be clear, I want to get rid of the bordered box and background inside the curly braces.\n\nAlso I am curious why such a high emphasis on the JavaScript portion of the template is deemed necessary. The two yellow curly braces on each side are more than enough to quickly spot it.\n\n========================================\n\nComments:\n- Is this from the TextMate syntax highlight or some other decoration. Use command **Developer: Inspect Editor Tokens and Scopes**","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":15,"estimatedTokens":215}}839{"id":"stack-66793153","source":"stackoverflow","questionId":66793153,"title":"How to redirect in Nuxt's asyncData","tags":["vue.js","vuejs2","vue-component","nuxt.js","vue-router"],"text":"Title: How to redirect in Nuxt's asyncData\nTags: vue.js, vuejs2, vue-component, nuxt.js, vue-router\nSource: Stack Overflow\n\nQuestion:\nI'm new to the vue.js and I have a simple question.\n\nI have a code like below:\n\n```\nasyncData({ params, error }) {\n return Job.api()\n .fetchByID(params.id)\n .then((response) => {\n const selectedJob = response.entities.jobs[0]\n if (selectedJob) {\n const industryID = selectedJob.industryId\n return Industry.api()\n .fetchByID(industryID)\n .then((result) => {\n const jobInd = result.response.data\n return {\n tagsArray:\n selectedJob.tags === 'null' || selectedJob.tags === ''\n ? []\n : selectedJob.tags.split(','),\n job: selectedJob,\n jobIndustry: jobInd,\n }\n })\n .catch(() => {\n error({\n statusCode: 404,\n message: 'Job Industry not found',\n })\n })\n }\n })\n .catch(() => {\n error({\n statusCode: 404,\n message: 'Job not found',\n })\n })\n },\n```\n\nI want to know how should I redirect the page to the home page after catching the error 404.\n\n========================================\n\nTop Answer:\nyou can use `redirect` in asyncdata in nuxt :\n\n```\nasync asyncData({ params ,error , redirect }) {\n #\n #\n #\n #\n # any code you want \n return redirect(301, \"YourNewRoutePath\")\n\n}\n```\n\n========================================\n\nCode:\n```js\nasyncData({ params, error }) {\n return Job.api()\n .fetchByID(params.id)\n .then((response) => {\n const selectedJob = response.entities.jobs[0]\n if (selectedJob) {\n const industryID = selectedJob.industryId\n return Industry.api()\n .fetchByID(industryID)\n .then((result) => {\n const jobInd = result.response.data\n return {\n tagsArray:\n selectedJob.tags === 'null' || selectedJob.tags === ''\n ? []\n : selectedJob.tags.split(','),\n job: selectedJob,\n jobIndustry: jobInd,\n }\n })\n .catch(() => {\n error({\n statusCode: 404,\n message: 'Job Industry not found',\n })\n })\n }\n })\n .catch(() => {\n error({\n statusCode: 404,\n message: 'Job not found',\n })\n })\n },\n```\n\n```js\nexport default {\n asyncData({ redirect, params, error }) {\n return Job.api()\n .fetchByID(params.id)\n .then(/*...*/)\n .catch(() => {\n redirect('/')\n })\n }\n}\n```\n\n```text\nasyncData()\n```\n\n```text\nredirect()\n```\n\n```text\nthis.$router.push({ name: 'home' })\n```\n\n```text\nthis.$router.push('/')\n```\n\n```text\n.catch((error) => {\n error({\n statusCode: 404,\n message: 'Job not found',\n })\n this.$router.push({ name: 'home' })\n })\n```\n\n```text\nasync asyncData({ params ,error , redirect }) {\n #\n #\n #\n #\n # any code you want \n return redirect(301, \"YourNewRoutePath\")\n\n}\n```\n\n```text\nredirect\n```\n\n========================================\n\nComments:\n- receiving new error saying that unexpected this in asyncData\n- redirect('/somePage') Check this link : nuxtjs.org/docs/2.x/internals-glossary/context","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":167,"estimatedTokens":779}}840{"id":"stack-66609106","source":"stackoverflow","questionId":66609106,"title":"Nuxt: i18n.localePath access in middleware","tags":["vue.js","nuxt.js","nuxt-i18n"],"text":"Title: Nuxt: i18n.localePath access in middleware\nTags: vue.js, nuxt.js, nuxt-i18n\nSource: Stack Overflow\n\nQuestion:\nI've defined a namespaced middleware for Nuxt like so:\n\n```\nexport default function({ store, redirect, app }){\n if (!store.state.isAuth) {\n return redirect(app.i18n.localePath('/auth'))\n }\n}\n```\n\nwhere if the user is *not* authenticated, they're redirected to the authentication page, located at `/auth`. However, this is a multilingual site, so I need to generate the path corresponding to the current locale. Normally I'd do this using `$i18n.localePath` or in this case, using Nuxt's context, `app.i18n.localePath()`, however I get this error:\n\n```\napp.i18n.localePath is not a function\n```\n\nand I'm not sure why, given that there's a context, and `console.log(app.i18n)` shows me that app.i18n.localePath *is* a function:\n\n```\n...\nlocalePath: [Function: bound ],\n...\n```\n\nAny suggestions? Thanks!\n\n========================================\n\nTop Answer:\nUse `app.localePath('/auth')` instead\n\n========================================\n\nCode:\n```text\nexport default function({ store, redirect, app }){\n if (!store.state.isAuth) {\n return redirect(app.i18n.localePath('/auth'))\n }\n}\n```\n\n```text\napp.i18n.localePath is not a function\n```\n\n```text\n...\nlocalePath: [Function: bound ],\n...\n```\n\n```text\n/auth\n```\n\n```text\n$i18n.localePath\n```\n\n```text\napp.i18n.localePath()\n```\n\n```text\nconsole.log(app.i18n)\n```\n\n```js\nlet locale = app.i18n.locale === app.i18n.defaultLocale ? '' : '/' + app.i18n.locale;\n\nreturn redirect( locale + '/auth' );\n```\n\n```text\napp.localePath('/auth')\n```\n\n========================================\n\nComments:\n- It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code.","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":87,"estimatedTokens":453}}841{"id":"stack-67188647","source":"stackoverflow","questionId":67188647,"title":"How we can access to Vuex store instance inside store module file in vuex-module-decorators + Nuxt TypeScript?","tags":["typescript","nuxt.js","vuex","vuex-modules","vuex-module-decorators"],"text":"Title: How we can access to Vuex store instance inside store module file in vuex-module-decorators + Nuxt TypeScript?\nTags: typescript, nuxt.js, vuex, vuex-modules, vuex-module-decorators\nSource: Stack Overflow\n\nQuestion:\nThere are **many** possible ways to construct your modules.\n\nvuex-module-decorators official\nreadme\n\n**One of** the most popular approaches is vuex-module-decorators.\n\nNuxt TypeScript official\ndocumentation\n\nWell, where at least two approaches has been introduced? The documentations are introducing just one approach and most articles are refers to it.\n\n### The official approach listing\n\n### ~/store/index.ts\n\n```\nimport { Store } from 'vuex'\nimport { initialiseStores } from '~/utils/store-accessor'\nconst initializer = (store: Store) => initialiseStores(store)\nexport const plugins = [initializer]\nexport * from '~/utils/store-accessor'\n```\n\n### ~/utils/store-accessor.ts\n\n```\nimport { Store } from 'vuex'\nimport { getModule } from 'vuex-module-decorators'\nimport example from '~/store/example'\n\nlet exampleStore: example\n\nfunction initialiseStores(store: Store): void {\n exampleStore = getModule(example, store)\n}\n\nexport { initialiseStores, exampleStore }\n```\n\n### Why I don't accept it\n\n- I don't understand **what** we doing. Although the code volume is small, there are a lot of not obvious things. For example: Why we need to define the `plugins` constant? Why we need to export it? How and where we using this export?\n\n- I don't understand **why** we need to the acrobatics such as. If there are the other approaches, it must the more intuitive solution.\n\n- I don't understand why we should to to this approach, **not other one**.\n\n- It's not enough type-safe. 'any' has been used.\n\n### What I want to do\n\nIf it's possible, I want to use the 'vuex-module-decorators' as usual, or, at least understand what going on and develop more clean solution.\n\nThe standard usage of dynamic modules in 'vuex-module-decorators' is:\n\n```\nimport store from \"@store\";\nimport { Module, VuexModule } from \"vuex-module-decorators\";\n\n@Module({\n name: \"PRODUCTS_MANAGER\",\n dynamic: true,\n namespaced: true,\n store\n})\nclass ProductsManagerStoreModule extends VuexModule {}\n```\n\nBut how we get the `store` instance in Nuxt TypeScript application?\nThe Nuxt takes out the vuex store from us (same as routing and webpack control) to make the development simply, but here is the reverse effect.\n\n### Try to use the vuex store as usual\n\nIt's interesting, but it works in development environment, but not in production.\n\n**store/index.ts**\n\n```\nimport Vuex, { Store } from \"vuex\";\n\nexport const store: Store = new Vuex.Store({});\n\nexport default store;\n```\n\n**pages/index.vue**\n\n```\nimport { Component, Vue } from \"nuxt-property-decorator\"\nimport { getModule } from \"nuxt-property-decorator\";\nimport TestStoreModule from \"./../Store/TestStoreModule\";\n\n@Component\nexport default class extends Vue {\n\n private readonly title: string = \"It Works!\";\n\n private mounted(): void {\n console.log(\"=========\");\n console.log(getModule(TestStoreModule).currentCount);\n }\n}\n```\n\nhttps://i.sstatic.net/r3Qd3.png\n\n**store/TestStoreModule.ts**\n\n```\nimport { Module, VuexModule, Mutation } from \"vuex-module-decorators\";\nimport store from \"./index\";\n\n@Module({\n name: \"TestStoreModule\",\n namespaced: true,\n dynamic: true,\n store\n})\nexport default class TestStoreModule extends VuexModule {\n\n private count: number = 0\n\n @Mutation\n public increment(delta: number): void {\n this.count += delta\n }\n @Mutation\n public decrement(delta: number): void {\n this.count -= delta\n }\n\n public get currentCount(): number {\n return this.count;\n }\n}\n```\n\nBut after production build, I have below error displaying in console:\n\n```\nERROR [nuxt] store/index.ts should export a method that returns a Vuex instance.\n```\n\n🌎 Application in above state (GitHub repository) (The project structure a little bit different, I am sorry).\n\nI tried to fix it as has been told. Now, `store/index.ts` is:\n\n```\n// config.rawError = true;\n/* 〔 see 〕 https://develop365.gitlab.io/nuxtjs-2.1.0-doc/pt-BR/guide/vuex-store/ */\nexport default function createStore(): Store {\n return new Vuex.Store({});\n}\n```\n\nThe `TestStoreModule` can not refer to `store` now (if can, how?).\n\n```\n@Module({\n name: \"TestStoreModule\",\n namespaced: true,\n stateFactory: true\n})\nexport default class TestStoreModule extends VuexModule { /* ... */ }\n```\n\nIn the component, tried to access to store module as:\n\n```\nconsole.log(getModule(TestStoreModule, this.$store).currentCount);\n```\n\nThe output is:\n\nhttps://i.sstatic.net/K4nGX.png\n\nSeems like the 'this' problem. If we output the `console.log(getModule(TestStoreModule, this.$store));` and call the `currentCount` from Chrome console:\n\nhttps://i.sstatic.net/Jemcf.png\n\nwe get the error:\n\n```\nException: TypeError: Cannot read property 'count' of undefined at Object.get\n(webpack-internal:///./node_modules/vuex-module-decorators/dist/esm/index.js:165:36) \nat Object.r (:1:83)\n```\n\n🌎 Application in above state (GitHub repository)\n\n========================================\n\nTop Answer:\nI can't answer all the why's in this questions, but I'll try to help\n\nFirstly, you right, Nuxt implements Vuex in its core. That's why you have some of why's. For example, definition of `plugins` constant you can find here in nuxt docs\n\nSecondly, to understand how to cook vue + typescript I advise to read article about really typing vue. It doesn`t cover usage of vuex-module-decorator, but introduce vuex-simple. Also, it have very good template to bootstrap new projects\n\nI hope this will help you and improve understanding!\n\n========================================\n\nCode:\n```js\nimport { Store } from 'vuex'\nimport { initialiseStores } from '~/utils/store-accessor'\nconst initializer = (store: Store<any>) => initialiseStores(store)\nexport const plugins = [initializer]\nexport * from '~/utils/store-accessor'\n```\n\n```js\nimport { Store } from 'vuex'\nimport { getModule } from 'vuex-module-decorators'\nimport example from '~/store/example'\n\nlet exampleStore: example\n\nfunction initialiseStores(store: Store<any>): void {\n exampleStore = getModule(example, store)\n}\n\nexport { initialiseStores, exampleStore }\n```\n\n```js\nimport store from \"@store\";\nimport { Module, VuexModule } from \"vuex-module-decorators\";\n\n@Module({\n name: \"PRODUCTS_MANAGER\",\n dynamic: true,\n namespaced: true,\n store\n})\nclass ProductsManagerStoreModule extends VuexModule {}\n```\n\n```js\nimport Vuex, { Store } from \"vuex\";\n\n\nexport const store: Store<unknown> = new Vuex.Store({});\n\n\nexport default store;\n```\n\n```text\nimport { Component, Vue } from \"nuxt-property-decorator\"\nimport { getModule } from \"nuxt-property-decorator\";\nimport TestStoreModule from \"./../Store/TestStoreModule\";\n\n\n@Component\nexport default class extends Vue {\n\n private readonly title: string = \"It Works!\";\n\n private mounted(): void {\n console.log(\"=========\");\n console.log(getModule(TestStoreModule).currentCount);\n }\n}\n```\n\n```text\nimport { Module, VuexModule, Mutation } from \"vuex-module-decorators\";\nimport store from \"./index\";\n\n@Module({\n name: \"TestStoreModule\",\n namespaced: true,\n dynamic: true,\n store\n})\nexport default class TestStoreModule extends VuexModule {\n\n private count: number = 0\n\n\n @Mutation\n public increment(delta: number): void {\n this.count += delta\n }\n @Mutation\n public decrement(delta: number): void {\n this.count -= delta\n }\n\n public get currentCount(): number {\n return this.count;\n }\n}\n```\n\n```text\nERROR [nuxt] store/index.ts should export a method that returns a Vuex instance.\n```\n\n```text\n// config.rawError = true;\n/* 〔 see 〕 https://develop365.gitlab.io/nuxtjs-2.1.0-doc/pt-BR/guide/vuex-store/ */\nexport default function createStore(): Store<unknown> {\n return new Vuex.Store({});\n}\n```\n\n```text\n@Module({\n name: \"TestStoreModule\",\n namespaced: true,\n stateFactory: true\n})\nexport default class TestStoreModule extends VuexModule { /* ... */ }\n```\n\n```text\nconsole.log(getModule(TestStoreModule, this.$store).currentCount);\n```\n\n```text\nException: TypeError: Cannot read property 'count' of undefined at Object.get\n(webpack-internal:///./node_modules/vuex-module-decorators/dist/esm/index.js:165:36) \nat Object.r (<anonymous>:1:83)\n```\n\n```text\nplugins\n```\n\n```text\nstore\n```\n\n```text\nstore/index.ts\n```\n\n```text\nTestStoreModule\n```\n\n```text\nstore\n```\n\n```text\nconsole.log(getModule(TestStoreModule, this.$store));\n```\n\n```text\ncurrentCount\n```\n\n```js\nimport Vue from \"vue\";\nimport Vuex, { Store } from \"vuex\";\n\n\nVue.use(Vuex);\n\nexport const store: Store<unknown> = new Vuex.Store<unknown>({});\n```\n\n```text\nstore-accessor.ts\n```\n\n```text\nvuex-module-decorators\n```\n\n```text\nstore/index.ts\n```\n\n```text\nplugins\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":387,"estimatedTokens":2178}}842{"id":"stack-66247131","source":"stackoverflow","questionId":66247131,"title":"How do i block page from production but show in development in nuxt?","tags":["nuxt.js"],"text":"Title: How do i block page from production but show in development in nuxt?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI tried to do this with `.nuxtignore` because with it you can ignore files \"during the build phase\". But then I realized the page was no longer visible in development either.\n\nI'm making a reference page (more involved than a .md) for developers to use with the project while doing component development. But i don't want end users to ever see the page when in production. How do I block the page from production but show in development in Nuxt?\n\n========================================\n\nTop Answer:\nYou can add `ignore` property in `nuxt.config.js` to ignore files (or pages). Also use `env variable` to judge weather it is in production mode or development mode.\n\n### Nuxt2\n\nTo use env variable in nuxt2, you can install `cross-env` package, and add some configs in `package.json` file. Also remember to create `.env` file for different environment first. The example codes are as :\n\n```\n// nuxt.config.js\n\n export default {\n // ...\n ignore: [\n process.env.ENVIROMENT === 'production' ? 'pages/debug/*' : '',\n process.env.ENVIROMENT === 'production' ? 'pages/someOtherPage.vue' : '',\n ],\n }\n```\n\n```\n// .env.local\n\n ENVIROMENT = local\n```\n\n```\n// .env.prod\n\n ENVIROMENT = production\n```\n\n```\n// package.json\n\n {\n // ...\n \"scripts\": {\n \"local\": \"cross-env ENV=local nuxt\",\n \"generate:prod\": \"cross-env ENV=prod nuxt generate\"\n },\n \"dependencies\": {\n \"corss-env\": \"7.0.3\"\n }\n // ...\n }\n```\n\n### Nuxt3\n\nIn nuxt3 `dotenv` is a build-in package, you just need to add some configs. Remember to add `VITE` prefix in you `.env.xxx` file. Sample codes are as :\n\n```\n// nuxt.config.ts\n\n export default defineNuxtConfig({\n // ...\n ignore: [\n process.env.VITE_ENVIROMENT == \"production\" ? 'pages/poc/carousel.vue' : ''\n ]\n })\n```\n\n```\n// .env.local\n\n VITE_ENVIROMENT = local\n```\n\n```\n// .env.prod\n\n VITE_ENVIROMENT = production\n```\n\n```\n// package.json\n\n {\n // ...\n \"scripts\": {\n \"local\": \"nuxt dev --dotenv .env.local\",\n \"generate:prod\": \"nuxt generate --dotenv .env.prod\"\n }\n // ...\n }\n```\n\n========================================\n\nCode:\n```text\n.nuxtignore\n```\n\n```js\n<template>\n <div>Dev Only</div>\n</template>\n\n<script>\nexport default {\n asyncData({ isDev, redirect }) {\n if (!isDev) {\n redirect({ name: 'index' })\n }\n }\n}\n</script>\n```\n\n```text\npages/test.vue\n```\n\n```js\n// nuxt.config.js\n\n export default {\n // ...\n ignore: [\n process.env.ENVIROMENT === 'production' ? 'pages/debug/*' : '',\n process.env.ENVIROMENT === 'production' ? 'pages/someOtherPage.vue' : '',\n ],\n }\n```\n\n```text\n// .env.local\n\n ENVIROMENT = local\n```\n\n```text\n// .env.prod\n\n ENVIROMENT = production\n```\n\n```text\n// package.json\n\n {\n // ...\n \"scripts\": {\n \"local\": \"cross-env ENV=local nuxt\",\n \"generate:prod\": \"cross-env ENV=prod nuxt generate\"\n },\n \"dependencies\": {\n \"corss-env\": \"7.0.3\"\n }\n // ...\n }\n```\n\n```js\n// nuxt.config.ts\n\n export default defineNuxtConfig({\n // ...\n ignore: [\n process.env.VITE_ENVIROMENT == \"production\" ? 'pages/poc/carousel.vue' : ''\n ]\n })\n```\n\n```text\n// .env.local\n\n VITE_ENVIROMENT = local\n```\n\n```text\n// .env.prod\n\n VITE_ENVIROMENT = production\n```\n\n```json\n// package.json\n\n {\n // ...\n \"scripts\": {\n \"local\": \"nuxt dev --dotenv .env.local\",\n \"generate:prod\": \"nuxt generate --dotenv .env.prod\"\n }\n // ...\n }\n```\n\n```text\nignore\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nenv variable\n```\n\n```text\ncross-env\n```\n\n```text\npackage.json\n```\n\n```text\n.env\n```\n\n```text\ndotenv\n```\n\n```text\nVITE\n```\n\n```text\n.env.xxx\n```\n\n========================================\n\nComments:\n- Context options for asyncData documentation nuxtjs.org/docs/2.x/internals-glossary/context","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":241,"estimatedTokens":954}}843{"id":"stack-66888855","source":"stackoverflow","questionId":66888855,"title":"How to properly import component in nuxt.config.js to use as a custom icon?","tags":["nuxt.js","vuetify.js"],"text":"Title: How to properly import component in nuxt.config.js to use as a custom icon?\nTags: nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use an SVG file as a custom icon, using this structure in `nuxt.config.js`:\n\n```\nimport UploadIcon from '@/components/icons/UploadIcon'\n\nexport default {\n...\n vuetify: {\n customVariables: ['~/assets/variables.scss'],\n icons: {\n values: {\n upload: {\n component: UploadIcon Nuxt is showing error:\n\n```\n│ ✖ Nuxt Fatal Error │\n │ │\n │ Error: Cannot find module '@/components/icons/UploadIcon' │\n │ Require stack: │\n │ - C:\\Users\\Admin\\Documents\\portfolio\\artwork\\artwork\\nuxt.config.js │\n```\n\nThe thing is that IDE automatically does such import:\n`import UploadIcon from '@/components/icons/UploadIcon'`\n\nAnd it doesn't work.\nWhat I tried:\n\n- doing `~` instead of `@` in path to component.\n\n- other variations of path, including absolute path.\n\nHowever, when I try to use absolute path it shows such an error:\n\n```\n╭───────────────────────────────────────╮\n │ │\n │ ✖ Nuxt Fatal Error │\n │ │\n │ SyntaxError: Unexpected token 'So I can't find a way, I checked these documentations:\n\n- https://github.com/nuxt-community/vuetify-module#defaultassets\n\n- https://vuetifyjs.com/en/features/icon-fonts/\n\nGenerally I've been trying to this answer: https://stackoverflow.com/a/58563938/7017890\nbut there is a regular `vuetify.js` config file being used. With Nuxt it doesn't work.\n\n========================================\n\nTop Answer:\nAvraham's solution above is correct.\n\nIn addition, if you're using the vuetify template in Nuxt, you can use it like this:\n\n\r\n\r\n\n```\n\nexport default {\n data() {\n return {\n clipped: false,\n drawer: false,\n fixed: false,\n items: [\n {\n icon: \"$myCustomIcon_1\",\n title: \"TitleText_1\",\n to: \"/\",\n },\n {\n icon: \"$myCustomIcon_2\",\n title: \"TitleText_2\",\n to: \"/\",\n },\n {\n icon: \"$myCustomIcon_3\",\n title: \"TitleText_3\",\n to: \"/\",\n },\n {\n icon: \"$myCustomIcon_4\",\n title: \"TitleText_4\",\n to: \"/\",\n },\n ],\n miniVariant: false,\n right: true,\n rightDrawer: false,\n };\n },\n};\n\n```\n\n\r\n\r\n\r\n\nand then the proper syntax to use in the v-list for loop is the following:\n\n\r\n\r\n\n```\n\n {{ `${item.icon}` }}\n\n```\n\n========================================\n\nCode:\n```text\nimport UploadIcon from '@/components/icons/UploadIcon'\n\nexport default {\n...\n vuetify: {\n customVariables: ['~/assets/variables.scss'],\n icons: {\n values: {\n upload: {\n component: UploadIcon <------here is my custom icon\n }\n }\n }\n }\n },\n```\n\n```text\n│ ✖ Nuxt Fatal Error │\n │ │\n │ Error: Cannot find module '@/components/icons/UploadIcon' │\n │ Require stack: │\n │ - C:\\Users\\Admin\\Documents\\portfolio\\artwork\\artwork\\nuxt.config.js │\n```\n\n```text\n╭───────────────────────────────────────╮\n │ │\n │ ✖ Nuxt Fatal Error │\n │ │\n │ SyntaxError: Unexpected token '<' │\n │ │\n ╰───────────────────────────────────────╯\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nimport UploadIcon from '@/components/icons/UploadIcon'\n```\n\n```text\n~\n```\n\n```text\n@\n```\n\n```text\nvuetify.js\n```\n\n```js\n// Note the lack of a leading slash (/)\nimport myCustomIcon from \"components/icons/UploadIcon\";\n\nexport default function () {\n return {\n // other vuetify options here,\n icons: {\n values: {\n upload: { component: myCustomIcon }\n }\n }\n };\n};\n```\n\n```text\nvuetify.options.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nvuetify.options.js\n```\n\n```js\n<script>\nexport default {\n data() {\n return {\n clipped: false,\n drawer: false,\n fixed: false,\n items: [\n {\n icon: \"$myCustomIcon_1\",\n title: \"TitleText_1\",\n to: \"/\",\n },\n {\n icon: \"$myCustomIcon_2\",\n title: \"TitleText_2\",\n to: \"/\",\n },\n {\n icon: \"$myCustomIcon_3\",\n title: \"TitleText_3\",\n to: \"/\",\n },\n {\n icon: \"$myCustomIcon_4\",\n title: \"TitleText_4\",\n to: \"/\",\n },\n ],\n miniVariant: false,\n right: true,\n rightDrawer: false,\n };\n },\n};\n</script>\n```\n\n```js\n<v-list-item-action>\n <v-icon size=\"30\">{{ `${item.icon}` }}</v-icon>\n</v-list-item-action>\n```\n\n========================================\n\nComments:\n- Perfect, I didn't even think about using an external `vuetify.options.js` file. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":253,"estimatedTokens":1190}}844{"id":"stack-59500223","source":"stackoverflow","questionId":59500223,"title":"vue + nuxt js - how to access context in a plugin for server side?","tags":["vue.js","plugins","nuxt.js"],"text":"Title: vue + nuxt js - how to access context in a plugin for server side?\nTags: vue.js, plugins, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI like to know if there is a way to access in a plugin the context variables? Which other variables / objects exists apart from the \"process\" object? Unfortunately I could not found a clear description nor a reference about the \"process\" object at the nuxt side\n\ni.e. plugins/helper.js\n\n```\nconst myHelper = {\n helpFunction(arg) {\n if (process.server) {\n ...\n }\n return ...;\n },\n```\n\n========================================\n\nCode:\n```text\nconst myHelper = {\n helpFunction(arg) {\n if (process.server) {\n ...\n }\n return ...;\n },\n```\n\n```js\nexport default (context, inject) => {\n context.app.helpFunction= (arg) => {\n if (process.server) {\n ...\n }\n return ...;\n }\n }\n```\n\n```js\nthis.$helpFunction(someArgs)...\n```\n\n```text\ncontext\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":50,"estimatedTokens":235}}845{"id":"stack-78813400","source":"stackoverflow","questionId":78813400,"title":"Instantly set Embla Carousel slide index without animation","tags":["javascript","vue.js","vuejs3","nuxt.js","nuxt3.js"],"text":"Title: Instantly set Embla Carousel slide index without animation\nTags: javascript, vue.js, vuejs3, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI’m building a gallery component in where clicking on an image opens a `` containing an `embla-carousel`. The problem is that when I click on an image, the carousel always opens at index `1`, regardless of which image was clicked. I tried to fix this by using `emblaMainApi.scrollTo(selectedIdx.value)` to get to the carousel's position based on the clicked image index, but this causes an scrolling animation from slide 1 to the selected slide, which looks weird.\n\nI want the selected image to appear instantly in the carousel without any scrolling animation.\n\nI'm looking for a possible solution.\n\n```\n// gallery.vue template\n\n \n \n \n \n\n// gallery.vue script\nconst imgs = [\n \"/images/gallery/gallery-1.jpg\",\n \"/images/gallery/gallery-2.jpg\",\n \"/images/gallery/gallery-3.jpg\",\n];\n\nconst modalRef = ref(null);\n\nconst showImg = (index) => {\n if (modalRef.value) {\n modalRef.value.show(index);\n }\n};\n\n// modal.vue script. Here I expose the 'show' method to the 'gallery' parent component so I can use it there\ndefineExpose({\n show: (index: number) => {\n selectedIdx.value = index;\n isOpen.value = true;\n dialog.value?.showModal(); // showModal() is a native `dialog`'s method\n },\n});\n```\n\n========================================\n\nCode:\n```text\n// gallery.vue template\n<template>\n<div>\n <ItemModal ref=\"modalRef\" :imgs=\"imgs\" />\n <div v-for=\"(item, idx) in imgs\" :key=\"item\">\n <NuxtImg\n :src=\"`${item}`\"\n :alt=\"`gallery image ${idx}`\"\n @click=\"showImg(idx)\"\n />\n </div>\n</div>\n</template>\n\n// gallery.vue script\nconst imgs = [\n \"/images/gallery/gallery-1.jpg\",\n \"/images/gallery/gallery-2.jpg\",\n \"/images/gallery/gallery-3.jpg\",\n];\n\nconst modalRef = ref(null);\n\nconst showImg = (index) => {\n if (modalRef.value) {\n modalRef.value.show(index);\n }\n};\n\n// modal.vue script. Here I expose the 'show' method to the 'gallery' parent component so I can use it there\ndefineExpose({\n show: (index: number) => {\n selectedIdx.value = index;\n isOpen.value = true;\n dialog.value?.showModal(); // showModal() is a native `dialog`'s method\n },\n});\n```\n\n```text\n<dialog>\n```\n\n```text\nembla-carousel\n```\n\n```text\n1\n```\n\n```text\nemblaMainApi.scrollTo(selectedIdx.value)\n```\n\n```text\njump\n```\n\n```text\ntrue\n```\n\n```text\nscrollTo\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":114,"estimatedTokens":600}}846{"id":"stack-62755962","source":"stackoverflow","questionId":62755962,"title":"How to access one Vuex state from another in Nuxt?","tags":["javascript","vue.js","vuex","nuxt.js"],"text":"Title: How to access one Vuex state from another in Nuxt?\nTags: javascript, vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have two Vuex stores inside the Nuxt `store` directory. I'm not able to access one store's states from another, even through `routeState`.\n\nStore 1: `index.js`\n\n```\nexport const state = () => ({\n token: false\n})\nexport const getters = {}\nexport const mutations = {}\nexport const actions = {}\n```\n\nStore 2: `api.js`\n\n```\nexport const state = () => ({\n apiBase: 'https://myurl.com/'\n})\nexport const getters = {\n getAPI: (state, rootState) => {\n // Need the state token from index.js here\n },\n}\nexport const mutations = {}\nexport const actions = {}\n```\n\nHere,\n\n- `state` returns the state variables in `api.js`, that is `apiBase`\n\n- `routeState` returns the getters in `api.js`\n\n- `this` is undefined inside Vuex getters, it doesn't work\n\nHow do I access the state or getters from index.js?\n\n========================================\n\nCode:\n```text\nexport const state = () => ({\n token: false\n})\nexport const getters = {}\nexport const mutations = {}\nexport const actions = {}\n```\n\n```text\nexport const state = () => ({\n apiBase: 'https://myurl.com/'\n})\nexport const getters = {\n getAPI: (state, rootState) => {\n // Need the state token from index.js here\n },\n}\nexport const mutations = {}\nexport const actions = {}\n```\n\n```text\nstore\n```\n\n```text\nrouteState\n```\n\n```text\nindex.js\n```\n\n```text\napi.js\n```\n\n```text\nstate\n```\n\n```text\napi.js\n```\n\n```text\napiBase\n```\n\n```text\nrouteState\n```\n\n```text\napi.js\n```\n\n```text\nthis\n```\n\n```text\nconst getters = {\n getApi: (state, getters, rootState) => {\n // Access the state token from index.js\n rootState.token\n }}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":115,"estimatedTokens":429}}847{"id":"stack-65903746","source":"stackoverflow","questionId":65903746,"title":"Go to next input field at maxLength?","tags":["javascript","html","vue.js","nuxt.js","vuelidate"],"text":"Title: Go to next input field at maxLength?\nTags: javascript, html, vue.js, nuxt.js, vuelidate\nSource: Stack Overflow\n\nQuestion:\nI have a form in Vue that has some combined inputs for styling reasons for a phone number input.\n\nMy problem is that the user has to hit tab in order to go to the next input field of the phone number.\n\nIs there a way to check for the max length of the current and input and when that is met go to the next input?\n\n```\n\n \n\n \n\n \n\n \n\n \n\n \n\n```\n\n========================================\n\nCode:\n```js\n<div class=\"combined-input combined-input--phone\" :class=\"{'error--input': phoneInvalid('patientInformation')}\">\n <div class=\"open-parenthesis\"></div>\n\n <input type=\"text\" id=\"phoneArea\" maxlength=\"3\" @blur=\"$v.formData.patientInformation.phone.$touch()\" v-model.trim=\"$v.formData.patientInformation.phone.area.$model\">\n\n <div class=\"close-parenthesis\"></div>\n\n <input type=\"text\" id=\"phoneA\" maxlength=\"3\" @blur=\"$v.formData.patientInformation.phone.$touch()\" v-model.trim=\"$v.formData.patientInformation.phone.a.$model\">\n\n <div class=\"dash\"></div>\n\n <input type=\"text\" id=\"phoneB\" maxlength=\"4\" @blur=\"$v.formData.patientInformation.phone.$touch()\" v-model.trim=\"$v.formData.patientInformation.phone.b.$model\">\n</div>\n```\n\n```js\nfocusNextOncePopulated(event, max) {\n if (event.target.value.length === max) {\n const nextElement = this.$refs?.[`input-${Number(event.target.dataset.index) +1}`]\n if (nextElement) nextElement.focus()\n }\n},\n```\n\n```text\ndebounce\n```\n\n```text\ninput\n```\n\n```text\nmax\n```\n\n```text\ndata-index\n```\n\n```text\n?.\n```\n\n```text\ninput\n```\n\n```text\nmax\n```\n\n```text\n$refs\n```\n\n```text\n@input\n```\n\n========================================\n\nComments:\n- aaa nice! of course my nextSibling is the div close parenthesis or div dash...lol....thanks for advice though!\n- You need to setup a selector for the next input. Just updated my answer on a possible way to do it. It's a bit more verbose but allows to go back to a previous field and to have the next focused again, rather than the last we left of. If you want later's behavior, setting up a state in `data` and incrementing it all the way could be a solution.","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":96,"estimatedTokens":542}}848{"id":"stack-61287986","source":"stackoverflow","questionId":61287986,"title":"How do I only import Navbar, Dropdown and Modal from buefy in Nuxt?","tags":["vue.js","vuejs2","nuxt.js","buefy"],"text":"Title: How do I only import Navbar, Dropdown and Modal from buefy in Nuxt?\nTags: vue.js, vuejs2, nuxt.js, buefy\nSource: Stack Overflow\n\nQuestion:\n- I am trying to import only the Navbar, Modal and Dropdown from Buefy and running into errors trying to do the same\n\n- I also want only the relevant scss files\n\n- I have tried multiple methods so far and nothing works\n\n**Method 1**\n\n- npx create-nuxt-app custombuefy\n\n- Do not select any frontend framework here\n\n**Step 1 Install Bulma**\n\n- npm i node-sass sass-loader -D\n\n- npm i bulma\n\n- Create app.scss inside styles folder inside assets directory\n\n- @import \"~bulma\" inside app.scss\n\n- Include '~/assets/styles/app,scss' inside css section of nuxt.config.js\n\n- npm run build && npm run start, Check if page with Bulma runs on localhost:3000\n\n- Runs successfully at this stage\n\n**Step 2 Install Normal Buefy without nuxt-buefy**\n\n- npm i buefy\n\n- Create buefy.js file inside plugins directory\n\n- Add '~/plugins/buefy.js' to plugins section of nuxt.config.js\n\n- Add the following code to import BDropdown, BModal, BNavbar from buefy\n\nIncluded the CSS directly here initially\n\n```\nimport Vue from 'vue'\nimport { BDropdown, BDropdownItem, BModal, BNavbar } from 'buefy'\nimport 'buefy/dist/buefy.min.css'\n\nVue.use(BDropdownItem)\nVue.use(BDropdown)\nVue.use(BModal)\nVue.use(BNavbar)\n```\n\n- Add the dropdown to the code in index.\n\npages/index.vue file\n\n```\n\n \n \n \n \n \n Click me!\n \n \n\n Action\n Another action\n Something else\n \n \n \n\nimport Logo from '~/components/Logo.vue'\n\nexport default {\n components: {\n Logo,\n },\n}\n\n.container {\n margin: 0 auto;\n min-height: 100vh;\n display: flex;\n justify-content: center;\n align-items: center;\n text-align: center;\n}\n\n.title {\n font-family: 'Quicksand', 'Source Sans Pro', -apple-system, BlinkMacSystemFont,\n 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n display: block;\n font-weight: 300;\n font-size: 100px;\n color: #35495e;\n letter-spacing: 1px;\n}\n\n.subtitle {\n font-weight: 300;\n font-size: 42px;\n color: #526488;\n word-spacing: 5px;\n padding-bottom: 15px;\n}\n\n.links {\n padding-top: 15px;\n}\n\n```\n\n**nuxt.config.js**\n\n```\nmodule.exports = {\n mode: 'universal',\n /*\n ** Headers of the page\n */\n head: {\n title: process.env.npm_package_name || '',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n {\n hid: 'description',\n name: 'description',\n content: process.env.npm_package_description || '',\n },\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],\n },\n /*\n ** Customize the progress-bar color\n */\n loading: { color: '#fff' },\n /*\n ** Global CSS\n */\n css: ['~/assets/styles/app.scss'],\n /*\n ** Plugins to load before mounting the App\n */\n plugins: ['~/plugins/buefy'],\n /*\n ** Nuxt.js dev-modules\n */\n buildModules: [\n // Doc: https://github.com/nuxt-community/eslint-module\n '@nuxtjs/eslint-module',\n // Doc: https://github.com/nuxt-community/stylelint-module\n '@nuxtjs/stylelint-module',\n ],\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://axios.nuxtjs.org/usage\n '@nuxtjs/axios',\n '@nuxtjs/pwa',\n // Doc: https://github.com/nuxt-community/dotenv-module\n '@nuxtjs/dotenv',\n ],\n /*\n ** Axios module configuration\n ** See https://axios.nuxtjs.org/options\n */\n axios: {},\n /*\n ** Build configuration\n */\n build: {\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {},\n },\n}\n```\n\n**Result**\n\n```\nERROR Cannot read property 'install' of undefined 16:19:41\n\n at Function.t.use (node_modules/vue/dist/vue.runtime.common.prod.js:6:36869)\n at Module. (server.js:1:559776)\n at r (server.js:1:194)\n at Object. (server.js:1:5233)\n at r (server.js:1:194)\n at server.js:1:1259\n at Object. (server.js:1:1269)\n at o (node_modules/vue-server-renderer/build.prod.js:1:77607)\n at node_modules/vue-server-renderer/build.prod.js:1:78200\n at new Promise ()\n```\n\n**Method 2**\n\nLets modify the plugins/buefy.js file to instead use dist/esm modules\n\n```\nimport Vue from 'vue'\nimport { BDropdown, BDropdownItem } from 'buefy/dist/esm/dropdown'\nimport 'buefy/dist/buefy.min.css'\n\nVue.use(BDropdownItem)\nVue.use(BDropdown)\n```\n\n**Result**\n\n```\nERROR Cannot use import statement outside a module 16:23:03\n\n (function (exports, require, module, __filename, __dirname) { import './chunk-6ea13200.js';\n ^^^^^^\n\n SyntaxError: Cannot use import statement outside a module\n at new Script (vm.js:88:7)\n at createScript (vm.js:263:10)\n at Object.runInThisContext (vm.js:311:10)\n at wrapSafe (internal/modules/cjs/loader.js:1059:15)\n at Module._compile (internal/modules/cjs/loader.js:1122:27)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)\n at Module.load (internal/modules/cjs/loader.js:1002:32)\n at Function.Module._load (internal/modules/cjs/loader.js:901:14)\n at Module.require (internal/modules/cjs/loader.js:1044:19)\n at require (internal/modules/cjs/helpers.js:77:18)\n```\n\n**Method 3**\n\nLets use the components from the components directory instead. We again modify plugins/buefy.js file as follows\n\n```\nimport Vue from 'vue'\nimport { BDropdown, BDropdownItem } from 'buefy/dist/components/dropdown'\nimport 'buefy/dist/buefy.min.css'\n\nVue.use(BDropdownItem)\nVue.use(BDropdown)\n```\n\n**Result**\n\nNow I get a new error saying Unknown custom element in Browser console and the dropdown appears completely broken\n\nhttps://i.sstatic.net/uvUEa.png\n\nIn case this is a dependency issue, here is my package.json file\n\n```\n{\n \"name\": \"custombuefy\",\n \"version\": \"1.0.0\",\n \"description\": \"My marvelous Nuxt.js project\",\n \"author\": \"\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"cross-env NODE_ENV=development nodemon server/index.js --watch server\",\n \"build\": \"nuxt build\",\n \"start\": \"cross-env NODE_ENV=production node server/index.js\",\n \"generate\": \"nuxt generate\",\n \"lint\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"test\": \"jest\"\n },\n \"lint-staged\": {\n \"*.{js,vue}\": \"npm run lint\",\n \"*.{css,vue}\": \"stylelint\"\n },\n \"husky\": {\n \"hooks\": {\n \"pre-commit\": \"lint-staged\"\n }\n },\n \"dependencies\": {\n \"@nuxtjs/axios\": \"^5.9.7\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"@nuxtjs/pwa\": \"^3.0.0-beta.20\",\n \"buefy\": \"^0.8.15\",\n \"bulma\": \"^0.8.2\",\n \"cross-env\": \"^7.0.2\",\n \"express\": \"^4.17.1\",\n \"nuxt\": \"^2.12.2\"\n },\n \"devDependencies\": {\n \"@nuxtjs/eslint-config\": \"^2.0.2\",\n \"@nuxtjs/eslint-module\": \"^1.1.0\",\n \"@nuxtjs/stylelint-module\": \"^3.2.2\",\n \"@vue/test-utils\": \"^1.0.0-beta.33\",\n \"babel-eslint\": \"^10.1.0\",\n \"babel-jest\": \"^25.3.0\",\n \"eslint\": \"^6.8.0\",\n \"eslint-config-prettier\": \"^6.10.1\",\n \"eslint-plugin-nuxt\": \">=0.5.2\",\n \"eslint-plugin-prettier\": \"^3.1.3\",\n \"husky\": \"^4.2.5\",\n \"jest\": \"^25.3.0\",\n \"lint-staged\": \"^10.1.5\",\n \"node-sass\": \"^4.13.1\",\n \"nodemon\": \"^2.0.3\",\n \"prettier\": \"^2.0.4\",\n \"sass-loader\": \"^8.0.2\",\n \"stylelint\": \"^13.3.2\",\n \"vue-jest\": \"^4.0.0-0\"\n }\n}\n```\n\nCan someone please tell me how I can import only the Dropdown, Navbar and Modal from Buefy without running into all these errors?\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\nimport { BDropdown, BDropdownItem, BModal, BNavbar } from 'buefy'\nimport 'buefy/dist/buefy.min.css'\n\nVue.use(BDropdownItem)\nVue.use(BDropdown)\nVue.use(BModal)\nVue.use(BNavbar)\n```\n\n```text\n<template>\n <div class=\"container\">\n <div>\n <logo />\n <b-dropdown aria-role=\"list\">\n <button\n slot=\"trigger\"\n slot-scope=\"{ active }\"\n class=\"button is-primary\"\n >\n <span>Click me!</span>\n <b-icon :icon=\"active ? 'menu-up' : 'menu-down'\"></b-icon>\n </button>\n\n <b-dropdown-item aria-role=\"listitem\">Action</b-dropdown-item>\n <b-dropdown-item aria-role=\"listitem\">Another action</b-dropdown-item>\n <b-dropdown-item aria-role=\"listitem\">Something else</b-dropdown-item>\n </b-dropdown>\n </div>\n </div>\n</template>\n\n<script>\nimport Logo from '~/components/Logo.vue'\n\nexport default {\n components: {\n Logo,\n },\n}\n</script>\n\n<style>\n.container {\n margin: 0 auto;\n min-height: 100vh;\n display: flex;\n justify-content: center;\n align-items: center;\n text-align: center;\n}\n\n.title {\n font-family: 'Quicksand', 'Source Sans Pro', -apple-system, BlinkMacSystemFont,\n 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n display: block;\n font-weight: 300;\n font-size: 100px;\n color: #35495e;\n letter-spacing: 1px;\n}\n\n.subtitle {\n font-weight: 300;\n font-size: 42px;\n color: #526488;\n word-spacing: 5px;\n padding-bottom: 15px;\n}\n\n.links {\n padding-top: 15px;\n}\n</style>\n```\n\n```text\nmodule.exports = {\n mode: 'universal',\n /*\n ** Headers of the page\n */\n head: {\n title: process.env.npm_package_name || '',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n {\n hid: 'description',\n name: 'description',\n content: process.env.npm_package_description || '',\n },\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],\n },\n /*\n ** Customize the progress-bar color\n */\n loading: { color: '#fff' },\n /*\n ** Global CSS\n */\n css: ['~/assets/styles/app.scss'],\n /*\n ** Plugins to load before mounting the App\n */\n plugins: ['~/plugins/buefy'],\n /*\n ** Nuxt.js dev-modules\n */\n buildModules: [\n // Doc: https://github.com/nuxt-community/eslint-module\n '@nuxtjs/eslint-module',\n // Doc: https://github.com/nuxt-community/stylelint-module\n '@nuxtjs/stylelint-module',\n ],\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://axios.nuxtjs.org/usage\n '@nuxtjs/axios',\n '@nuxtjs/pwa',\n // Doc: https://github.com/nuxt-community/dotenv-module\n '@nuxtjs/dotenv',\n ],\n /*\n ** Axios module configuration\n ** See https://axios.nuxtjs.org/options\n */\n axios: {},\n /*\n ** Build configuration\n */\n build: {\n /*\n ** You can extend webpack config here\n */\n extend(config, ctx) {},\n },\n}\n```\n\n```text\nERROR Cannot read property 'install' of undefined 16:19:41\n\n at Function.t.use (node_modules/vue/dist/vue.runtime.common.prod.js:6:36869)\n at Module.<anonymous> (server.js:1:559776)\n at r (server.js:1:194)\n at Object.<anonymous> (server.js:1:5233)\n at r (server.js:1:194)\n at server.js:1:1259\n at Object.<anonymous> (server.js:1:1269)\n at o (node_modules/vue-server-renderer/build.prod.js:1:77607)\n at node_modules/vue-server-renderer/build.prod.js:1:78200\n at new Promise (<anonymous>)\n```\n\n```text\nimport Vue from 'vue'\nimport { BDropdown, BDropdownItem } from 'buefy/dist/esm/dropdown'\nimport 'buefy/dist/buefy.min.css'\n\nVue.use(BDropdownItem)\nVue.use(BDropdown)\n```\n\n```text\nERROR Cannot use import statement outside a module 16:23:03\n\n (function (exports, require, module, __filename, __dirname) { import './chunk-6ea13200.js';\n ^^^^^^\n\n SyntaxError: Cannot use import statement outside a module\n at new Script (vm.js:88:7)\n at createScript (vm.js:263:10)\n at Object.runInThisContext (vm.js:311:10)\n at wrapSafe (internal/modules/cjs/loader.js:1059:15)\n at Module._compile (internal/modules/cjs/loader.js:1122:27)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)\n at Module.load (internal/modules/cjs/loader.js:1002:32)\n at Function.Module._load (internal/modules/cjs/loader.js:901:14)\n at Module.require (internal/modules/cjs/loader.js:1044:19)\n at require (internal/modules/cjs/helpers.js:77:18)\n```\n\n```text\nimport Vue from 'vue'\nimport { BDropdown, BDropdownItem } from 'buefy/dist/components/dropdown'\nimport 'buefy/dist/buefy.min.css'\n\nVue.use(BDropdownItem)\nVue.use(BDropdown)\n```\n\n```text\n{\n \"name\": \"custombuefy\",\n \"version\": \"1.0.0\",\n \"description\": \"My marvelous Nuxt.js project\",\n \"author\": \"\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"cross-env NODE_ENV=development nodemon server/index.js --watch server\",\n \"build\": \"nuxt build\",\n \"start\": \"cross-env NODE_ENV=production node server/index.js\",\n \"generate\": \"nuxt generate\",\n \"lint\": \"eslint --ext .js,.vue --ignore-path .gitignore .\",\n \"test\": \"jest\"\n },\n \"lint-staged\": {\n \"*.{js,vue}\": \"npm run lint\",\n \"*.{css,vue}\": \"stylelint\"\n },\n \"husky\": {\n \"hooks\": {\n \"pre-commit\": \"lint-staged\"\n }\n },\n \"dependencies\": {\n \"@nuxtjs/axios\": \"^5.9.7\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"@nuxtjs/pwa\": \"^3.0.0-beta.20\",\n \"buefy\": \"^0.8.15\",\n \"bulma\": \"^0.8.2\",\n \"cross-env\": \"^7.0.2\",\n \"express\": \"^4.17.1\",\n \"nuxt\": \"^2.12.2\"\n },\n \"devDependencies\": {\n \"@nuxtjs/eslint-config\": \"^2.0.2\",\n \"@nuxtjs/eslint-module\": \"^1.1.0\",\n \"@nuxtjs/stylelint-module\": \"^3.2.2\",\n \"@vue/test-utils\": \"^1.0.0-beta.33\",\n \"babel-eslint\": \"^10.1.0\",\n \"babel-jest\": \"^25.3.0\",\n \"eslint\": \"^6.8.0\",\n \"eslint-config-prettier\": \"^6.10.1\",\n \"eslint-plugin-nuxt\": \">=0.5.2\",\n \"eslint-plugin-prettier\": \"^3.1.3\",\n \"husky\": \"^4.2.5\",\n \"jest\": \"^25.3.0\",\n \"lint-staged\": \"^10.1.5\",\n \"node-sass\": \"^4.13.1\",\n \"nodemon\": \"^2.0.3\",\n \"prettier\": \"^2.0.4\",\n \"sass-loader\": \"^8.0.2\",\n \"stylelint\": \"^13.3.2\",\n \"vue-jest\": \"^4.0.0-0\"\n }\n}\n```\n\n```text\nimport Vue from 'vue'\nimport { Dropdown, Icon } from 'buefy'\n\nVue.use(Dropdown)\nVue.use(Icon)\n```\n\n```text\n@import \"~bulma\";\n@import \"~buefy/src/scss/buefy\";\n```\n\n```text\n@import \"~buefy/src/scss/utils/_all\";\n@import \"~buefy/src/scss/components/_autocomplete\";\n@import \"~buefy/src/scss/components/_dropdown\";\n@import \"~buefy/src/scss/components/_notices\";\n```\n\n========================================\n\nComments:\n- even scss can be imported partially","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":602,"estimatedTokens":3499}}849{"id":"stack-60316441","source":"stackoverflow","questionId":60316441,"title":"nuxt.js - \"This page could not be found\" on static page with base ./","tags":["build","static","http-status-code-404","nuxt.js","router"],"text":"Title: nuxt.js - \"This page could not be found\" on static page with base ./\nTags: build, static, http-status-code-404, nuxt.js, router\nSource: Stack Overflow\n\nQuestion:\nI tried to generate a static web site with nuxt, but when i open the `index.html` file, it show an infinite load screen with this JS error :\n\n fail to load element whose source is « file:///_nuxt/42185af33c638e7022a3.js ».\n\nso, after i have search, i change `router.base` configuration by `./` and it throw this error : \n\n This page could not be found\n\n Back to the home page\n\nbut when i click on `Back to the home page` it showing my home page.\n\nAnyone have an idea how to open `index.html` file from static build ?\n\ni explain my project : i wish to run my app with Capacitor so i need static build work fine.\n\nThank by advance and my apologies for my bad english write.\n\n========================================\n\nTop Answer:\nI found two solution:\n\nSolution 1 : **Make your project to \"universal\" instead \"single page app\"**\n\nWhen you generate a static web app, it work fine when you run `index.html`. However, Capacitor display the page but don't recognize the router, so you can't switch page in your app.\n\nSolution 2 : **Set `router` in nuxt.config.js in spa**\n\nAdd this configuration to nuxt.config.js :\n\n```\nrouter: {\n base: './'\n mode: 'hash'\n}\n```\n\nit work when you open the `index.html` file in dist, but does not work with capacitor.\n\nMy request is therefore partially resolved.\n\n========================================\n\nCode:\n```text\nindex.html\n```\n\n```text\nrouter.base\n```\n\n```text\n./\n```\n\n```text\nBack to the home page\n```\n\n```text\nindex.html\n```\n\n```js\nbuild: {\n publicPath: '/nuxt/',\n // ...\n},\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n_nuxt\n```\n\n```text\nnuxt\n```\n\n```text\nrouter: {\n base: './'\n mode: 'hash'\n}\n```\n\n```text\nindex.html\n```\n\n```text\nrouter\n```\n\n```text\nindex.html\n```\n\n========================================\n\nComments:\n- 1. Remove router base 2. Run `npm run generate` 3. open `index.html` file search for `/_nuxt/` and replace it with `_nuxt`\n- i think you mean : replace `/_nuxt/` by `_nuxt/`, i tried and it not work. i have edit my post, the error do not contained `/app/`","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":113,"estimatedTokens":553}}850{"id":"stack-66458778","source":"stackoverflow","questionId":66458778,"title":"Nuxt Content async fetch in component","tags":["vue.js","nuxt.js","nuxt-content"],"text":"Title: Nuxt Content async fetch in component\nTags: vue.js, nuxt.js, nuxt-content\nSource: Stack Overflow\n\nQuestion:\nI'm new to the **@nuxt/content** module and it's working well except **within components**.\n\nHere I'm trying to get the content like so:\n\n*layout.vue*\n\n```\nexport default {\n name: 'Default',\n CONTENT: 'content',\n async asyncData({ $content }) {\n const content = await $content('content').fetch()\n return { content }\n },\n}\n```\n\n*component.vue*\n\n```\nexport default {\n async fetch({ $content }) {\n this.content = await this.$content('content', { deep: true }).fetch()\n },\n data() {\n return { content }\n },\n}\n```\n\nHow can I use content within components?\n\n========================================\n\nCode:\n```js\nexport default {\n name: 'Default',\n CONTENT: 'content',\n async asyncData({ $content }) {\n const content = await $content('content').fetch()\n return { content }\n },\n}\n```\n\n```js\nexport default {\n async fetch({ $content }) {\n this.content = await this.$content('content', { deep: true }).fetch()\n },\n data() {\n return { content }\n },\n}\n```\n\n```js\nexport default {\n data() {\n return {\n content: [],\n }\n },\n async fetch({ $content }) {\n this.content = await $content('content', { deep: true }).fetch()\n // ! it's $content and not this.$content here since you've imported it in the scope\n },\n}\n```\n\n```text\n$content\n```\n\n```text\nfetch\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n========================================\n\nComments:\n- First note! you can't use `asyncData` in your layout. `asyncData` is just available in pages not components or layouts.\n- Please do not print that kind of code in a comment. Edit and format your answer with the new code/result.\n- wups : ) soo it's working now! <3 I tried a few things and I had to remove the deep true part : ) thank you so much!\n- No issues, glad it works. Welcome to StackOverflow and enjoy your Nuxt ! :)\n- This does not work for me on version 2.15 . I had to use: `async fetch() { this.$content(); }`\n- @OsvaldoMaria either destructure it or call `this` I guess.","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":101,"estimatedTokens":519}}851{"id":"stack-65654930","source":"stackoverflow","questionId":65654930,"title":"Create class instance and inject it dynamically","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Create class instance and inject it dynamically\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nMy project is using Nuxt, and I would like to implement dynamic injection of my services. It means I just add a class to my specific folder, and the class will be automatically injected into the context.\n\nFor instance, these are my classes placed in `nuxtApp/service`:\n\n```\n// /service/foo.service.js\nexport class FooService {\n constructor (context) {\n this.context = context\n }\n \n functionFoo (param) {\n console.log(`FooService.functionFoo: ${param}`)\n }\n}\n\n// /service/bar.service.js\nexport class BarService {\n constructor (context) {\n this.context = context\n }\n \n functionBar (param) {\n console.log(`BarService.functionBar: ${param}`)\n }\n}\n```\n\nAnd this is how my plugin currently looks like, but I would like to automate it:\n\n```\n// /plugins/service-loader.js\nimport { FooService } from '../service/foo.service'\nimport { BarService } from '../service/bar.service'\n\nexport default ({ app }, inject) => {\n const fooService = new FooService(app)\n inject('fooService', fooService)\n\n const barService = new BarService(app)\n inject('barService', barService)\n}\n```\n\nIs it possible to create automatically loading of services placed in the `/service` folder, and then inject their instance into the context?\n\n========================================\n\nCode:\n```text\n// /service/foo.service.js\nexport class FooService {\n constructor (context) {\n this.context = context\n }\n \n functionFoo (param) {\n console.log(`FooService.functionFoo: ${param}`)\n }\n}\n\n// /service/bar.service.js\nexport class BarService {\n constructor (context) {\n this.context = context\n }\n \n functionBar (param) {\n console.log(`BarService.functionBar: ${param}`)\n }\n}\n```\n\n```text\n// /plugins/service-loader.js\nimport { FooService } from '../service/foo.service'\nimport { BarService } from '../service/bar.service'\n\nexport default ({ app }, inject) => {\n const fooService = new FooService(app)\n inject('fooService', fooService)\n\n const barService = new BarService(app)\n inject('barService', barService)\n}\n```\n\n```text\nnuxtApp/service\n```\n\n```text\n/service\n```\n\n```js\n// ~/modules/service-loader.js\nimport path from 'path'\nimport glob from 'glob'\n\nexport default function serviceLoader() {\n glob(path.resolve(__dirname, '../service/**/*.service.js'), { follow: true }, (err, files) => {\n if (err) throw err\n\n for (const file of files) {\n const exportedMembers = Object.keys(require(file))\n if (!exportedMembers.length) return\n\n const className = exportedMembers[0]\n this.addPlugin({\n src: path.resolve(__dirname, './service-template.js'),\n fileName: path.basename(file),\n options: {\n className,\n propName: className.slice(0,1).toLowerCase() + className.substring(1),\n moduleName: file,\n }\n })\n }\n })\n}\n```\n\n```text\n// ~/modules/service-template.js\nimport { <%= options.className %> } from '<%= options.moduleName %>'\n\nexport default ({ app }, inject) => {\n const <%= options.propName %> = new <%= options.className %> (app)\n inject('<%= options.propName %>', <%= options.propName %>)\n}\n```\n\n```js\n// nuxt.config.js\nexport default {\n modules: [\n '~/modules/service-loader'\n ],\n}\n```\n\n```text\n~/service/*.service.js\n```\n\n```text\nservice/\n```\n\n```text\naddPlugin()\n```\n\n```text\n.service.js\n```\n\n```text\nmodules\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":166,"estimatedTokens":855}}852{"id":"stack-61305993","source":"stackoverflow","questionId":61305993,"title":"e.$OneSignal.on is not a function for Nuxtjs PWA - OneSignal","tags":["vue.js","nuxt.js","progressive-web-apps","onesignal"],"text":"Title: e.$OneSignal.on is not a function for Nuxtjs PWA - OneSignal\nTags: vue.js, nuxt.js, progressive-web-apps, onesignal\nSource: Stack Overflow\n\nQuestion:\nI'm using **@nuxtjs/pwa** along with **@nuxtjs/onesignal**.\nI'm having an issue with listener to the **subscriptionChange** event on mounted.\nIt's working very well with **localhost**,\nthe issue is happened on **production**.\n\n```\nmounted() {\n let self = this;\n this.$OneSignal.push(() => {\n self.$OneSignal.on('subscriptionChange', (isSubscribed) => {\n if (isSubscribed) {\n self.$OneSignal.getUserId().then((deviceId) => {\n self.addDeviceId(deviceId)\n });\n }\n });\n });\n}\n```\n\n**On production error:**\nhttps://i.sstatic.net/k0Lzu.png\n\nThank you and appreciate.\n\n========================================\n\nTop Answer:\nFortunately, I had these issues some hours back you need to access Onesignal using the global window method\n\n```\nwindow.OneSignal = window.OneSignal || []\nwindow.OneSignal.push(() => {\n window.OneSignal.on('subscriptionChange', (isSubscribed) => {\n if (isSubscribed) {\n window.OneSignal.getUserId().then((deviceId) => {\n self.addDeviceId(deviceId)\n });\n }\n });\n})\n```\n\n========================================\n\nCode:\n```text\nmounted() {\n let self = this;\n this.$OneSignal.push(() => {\n self.$OneSignal.on('subscriptionChange', (isSubscribed) => {\n if (isSubscribed) {\n self.$OneSignal.getUserId().then((deviceId) => {\n self.addDeviceId(deviceId)\n });\n }\n });\n });\n}\n```\n\n```text\nwindow.OneSignal = window.OneSignal || []\n window.OneSignal.push(() => {\n window.OneSignal.getUserId(async (userId) => {\n await this.$store.dispatch(\n 'Authenticated/overview/updatePushID',\n userId\n )\n })\n })\n```\n\n```text\nwindow.OneSignal = window.OneSignal || []\nwindow.OneSignal.push(() => {\n window.OneSignal.on('subscriptionChange', (isSubscribed) => {\n if (isSubscribed) {\n window.OneSignal.getUserId().then((deviceId) => {\n self.addDeviceId(deviceId)\n });\n }\n });\n})\n```\n\n========================================\n\nComments:\n- Hi brother, I've copied yours. It's also work on local. And now on production it's not error any more but Won't send playerId to OneSignal, it seems not work. ;(\n- window.OneSignal = window.OneSignal || [] window.OneSignal.push(() => { window.OneSignal.getUserId(userId => { console.log(userId) }) }) } I've consoled: -- Locally, I can see userId -- Production, userId is Null\n- check your one signal config i think you need to make your one signal config match your url else user_id will always be null","metadata":{"transformedAt":"2026-08-18T18:33:07.897Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":97,"estimatedTokens":648}}853{"id":"stack-60053031","source":"stackoverflow","questionId":60053031,"title":"Render a page after its layout is fully mounted in Nuxt","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Render a page after its layout is fully mounted in Nuxt\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using a layout for my admin pages which brings user informations in a layout, so I don't have to query user information every time the page changes.\n\nHowever, the problem is, when I query user information in layout, the page does not wait for the layout to load.\n\n***myLayout.vue***\n\n```\nbeforeMount() {\n // getting user info from the server by Vuex action\n}\n```\n\n***myPage.vue***\n\n```\nlayout: \"myLayout\"\n...\nmounted() {\n // bring user info from the Vuex store\n}\n```\n\nIn this case, I expect `beforeMount` to be done in `myLayout.vue`,\n\nbut `myPage.vue` does not wait and get `mounted` before Vuex action is completed.\n\nso the lifecycle would be\n\n`layout's beforeMount` -> `page's beforeMount` -> `page's mounted` -> `layout's mounted`\n\nbecause page does not wait for beforeMount of a layout to be done.\n\nIs there a way to prevent a page to be mounted before layout is mounted?\n\n========================================\n\nTop Answer:\nThis is how I solved it.\n\nThe nuxt component which renders the page is mounted after the loading is complete. This is achieved using a variable and a conditional statement.\n\n*layout.vue*\n\n```\n\n \n\nexport default {\n data () {\n return {\n hasLoaded: false,\n }\n },\n async created () {\n // do stuff\n\n this.hasLoaded = true;\n },\n}\n\n```\n\n========================================\n\nCode:\n```text\nbeforeMount() {\n // getting user info from the server by Vuex action\n}\n```\n\n```text\nlayout: \"myLayout\"\n...\nmounted() {\n // bring user info from the Vuex store\n}\n```\n\n```text\nbeforeMount\n```\n\n```text\nmyLayout.vue\n```\n\n```text\nmyPage.vue\n```\n\n```text\nmounted\n```\n\n```text\nlayout's beforeMount\n```\n\n```text\npage's beforeMount\n```\n\n```text\npage's mounted\n```\n\n```text\nlayout's mounted\n```\n\n```js\nexport default {\n ...\n async middleware({ store }) {\n await store.dispatch('fetch-some-data-with-vuex')\n },\n ...\n}\n```\n\n```text\nmiddleware\n```\n\n```text\nthis.$root.$emit('layout_loaded', true);\n```\n\n```text\nmounted(){\n this.$root.$on('layout_loaded', (state) => {\n // bring user info from the Vuex store\n });\n}\n```\n\n```text\n<template>\n <Nuxt v-if=\"hasLoaded\" />\n</template>\n\n<script>\nexport default {\n data () {\n return {\n hasLoaded: false,\n }\n },\n async created () {\n // do stuff\n\n this.hasLoaded = true;\n },\n}\n</script>\n```\n\n========================================\n\nComments:\n- Problem is not in the order of hook calls. Problem is your async action in Vuex store started in `beforeMount`. It's not possible to simply wait for async call (promise) in JS - you need to work around it...ie. write all components in a way that data is not here on 1st render and will become available later...\n- Have you considered `nuxtServerInit`? is that a possibility for you?\n- @Ohgodwhy the problem is, that I am doing the authentication with middlewares. Therefore, if I use `nuxtServerInit` to bring user information, it would fail because the authentication is not done yet. If possible, I don't want to rebuild the whole structure.\n- i think simple solution is asyncData, you should use this\n- This solution helped me a lot. The middleware answer great if you are not using SSR. The other 'mounted' answer would lock up the server render of pages that didn't need authorization checks.","metadata":{"transformedAt":"2026-08-18T18:33:07.898Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":171,"estimatedTokens":843}}854{"id":"stack-66465069","source":"stackoverflow","questionId":66465069,"title":"Can part of a website be static site generated and the other be a traditional spa?","tags":["vue.js","nuxt.js","single-page-application","ssg","static-site-generation"],"text":"Title: Can part of a website be static site generated and the other be a traditional spa?\nTags: vue.js, nuxt.js, single-page-application, ssg, static-site-generation\nSource: Stack Overflow\n\nQuestion:\nSo, I've built a website in Nuxt and used ssg. It's great, but for another website 90% of it is all static text and images, but I want a customer login portal where they can see statuses of their products. With my understanding, I don't see how this could be ssg as well. So is it possible to have both?\n\n========================================\n\nTop Answer:\nVue.js is rendered into #app. Everything outside of that div will be static. So yes, you can have both. BTW, if you don't need SPA completely, check for alphine.js which is a lightweight alternative.\n\n========================================\n\nCode:\n```js\nexport default {\n generate: {\n exclude: [\n /^\\/admin/ // path starts with /admin\n ]\n }\n}\n```\n\n```text\npages\n--admin\n----secure-dashboard.vue\n----info.vue\n--blog\n--pricing\n```\n\n```text\ngenerate-exclude\n```\n\n```text\nadmin\n```\n\n```text\nadmin\n```\n\n```text\nblog\n```\n\n```text\npricing\n```\n\n```text\nserver\n```\n\n```text\nclient\n```\n\n```text\nadmin.vue\n```\n\n========================================\n\nComments:\n- You meant: \"and used SSR\" ? Or do you mean: \"generated on the server\" by *ssg* ?\n- @kissu, Sorry, I mean \"generated on the server by ssg\"\n- You can't really write any code outside of the basic scope (`#app` div). In a clean way at least. Also, I'm not sure that bringing alpine is a thing to do when you already have a JS framework. It usually used in pure HTML+CSS context only.\n- You can't write any Vue code outside of #app, but you can write Vanilla JS. So you can have both, and they can be very clear. Alphine is not for using among Vue, it's an alternative. If you build a page with 90% of static content, it's not logical to use any big framework.\n- Okay, I think I understand now. So I could have an `admin.vue` file in the pages directory of the Nuxt app, but it would be treated an a traditional SPA vs how it would treat an SSG route with it's cached assets and api calls?","metadata":{"transformedAt":"2026-08-18T18:33:07.898Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":74,"estimatedTokens":528}}855{"id":"stack-77882887","source":"stackoverflow","questionId":77882887,"title":"Persist State Between Reloads in Nuxt v3","tags":["nuxt.js"],"text":"Title: Persist State Between Reloads in Nuxt v3\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nAnyone know what the best way is to persist state between reloads in Nuxt v3?\n\nI have my composables file states.ts:\n\n```\nexport const useUser = () => useState('user', retrieveUser)\nconst retrieveUser = () => {\n if (process.server) return null\n const user = localStorage.getItem('user')\n if (user) {\n try {\n const parsedUser: User = JSON.parse(user)\n if (new Date(parsedUser.expires) However, this does not do the trick. Any ideas? And how do you then go about avoiding hydration mismatches caused by using values from localStorage. It's a headache and it seems like the documentation and usage isn't too great with Nuxtjs 3 yet either.\n\n========================================\n\nTop Answer:\nI would probably go with `useLocalStorage` from vueuse. You can also use custom serialisation for user object.\n\n```\nexport const user = useLocalStorage('user', () => null)\n```\n\nBeware that you cannot use `useStorage`, as it conflicts with the method of the same name from nitro.\n\n========================================\n\nCode:\n```text\nexport const useUser = () => useState<User | null>('user', retrieveUser)\nconst retrieveUser = () => {\n if (process.server) return null\n const user = localStorage.getItem('user')\n if (user) {\n try {\n const parsedUser: User = JSON.parse(user)\n if (new Date(parsedUser.expires) < new Date()) {\n localStorage.removeItem('user')\n return null\n }\n return parsedUser\n } catch (error) {\n return null\n } \n }\n return null\n}\n\nexport type User = {\n email: string\n username: string\n name: string\n zipCode: string\n profilePicture: string\n expires: Date\n}\n```\n\n```js\nexport const useUser = () => useCookie<User | null>('user', {\n default: () => null,\n watch: true,\n})\n```\n\n```text\nuseCookie\n```\n\n```js\nexport const user = useLocalStorage<User | null>('user', () => null)\n```\n\n```text\nuseLocalStorage\n```\n\n```text\nuseStorage\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.898Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":85,"estimatedTokens":520}}856{"id":"stack-65473255","source":"stackoverflow","questionId":65473255,"title":"How to escape 'Duplicate keys detected' in v-for loop at Vue.Js?","tags":["javascript","typescript","vue.js","nuxt.js","vuetify.js"],"text":"Title: How to escape 'Duplicate keys detected' in v-for loop at Vue.Js?\nTags: javascript, typescript, vue.js, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nI have used Nuxt.Js in my latest project and I also used Vuetify.js as UI framework, and language is TypeScript.\nI tried to make this image below using following arrays.\n\nhttps://i.sstatic.net/t1Xsc.jpg\n\n```\nexport const dummyData = [\n {\n id: \"1\",\n name: \"a\",\n sub: [\n {\n id: \"1#1\",\n name: \"b\",\n sub_sub: [\n { id: \"1#1#1\", name: \"b-a\" },\n { id: \"1#1#2\", name: \"b-b\" },\n ]\n },\n {\n id: \"1#2\",\n name: \"c\",\n sub_sub: [\n { id: \"1#2#1\", name: \"c-a\" },\n ]\n },\n ]\n },\n {\n id: \"2\",\n name: \"d\",\n sub: [\n {\n id: \"2#1\",\n name: \"e\",\n sub_sub: [\n { id: \"1#2#1\", name: \"e-a\" },\n ]\n }\n ]\n },\n]\n```\n\nand I thought I finished to make data table using following code.\n\n```\n\n \n \n \n \n name\n sub_name\n sub_sub_name\n \n \n \n \n \n \n \n {{ item.name }}\n \n \n {{ subitem.name }}\n \n {{ sub_subitem.name }}\n \n \n \n \n \n \n\nimport { Component, Vue } from 'nuxt-property-decorator'\nimport { dummyData } from '~/store/dummy'\n\n@Component({})\nexport default class extends Vue {\n items: any = []\n\n created() {\n this.items = dummyData\n }\n\n rowSpanCalc(item: any) {\n const count = item.sub.reduce(\n (total: any, curr: any) => total + curr.sub_sub.length,\n 0\n )\n console.log(count);\n return count;\n }\n}\n\ntable {\n border-collapse: collapse !important;\n}\n.v-data-table--dense > .v-data-table__wrapper > table > tbody > tr > td {\n border-bottom: thin solid rgba(0, 0, 0, 0.12) !important;\n}\n\n```\n\nI asked question about these my issues in stackoverflow.\nand finally I thought it was completed!...... but after few days, my customer asked some error like below.\n\n```\nvue.runtime.esm.js?2b0e:619 [Vue warn]: Duplicate keys detected: '1#2#1'. This may cause an update error.\n```\n\nmy code seems like no problem. but it has some problem about v-bind:key.\nIn template, I know tag of \"v-bind:key\" can't use duplicate key.\nIf I use some \"v-bind:key\" in template, I use iterator to distinguish each \"v-bind:key\".\nThat's why I used one \"v-bind:key\" , but error occurred.\nIt ’s a very headache problem for me.\n\nHow can I fix the error when I run this code?\nCould anyone advise me?\n\n========================================\n\nTop Answer:\nIt's doing exactly what it says on the tin: `[Vue warn]: Duplicate keys detected: '1#2#1'. This may cause an update error.`\n\nYour data uses `\"1#2#1\"` as an id for multiple items.\n\nIf you correct your data to have unique id's the error will go away, like so:\n\n```\nexport const dummyData = [\n {\n id: \"1\",\n name: \"a\",\n sub: [\n {\n id: \"1#1\",\n name: \"b\",\n sub_sub: [\n { id: \"1#1#1\", name: \"b-a\" },\n { id: \"1#1#2\", name: \"b-b\" },\n ]\n },\n {\n id: \"1#2\",\n name: \"c\",\n sub_sub: [\n { id: \"1#2#1\", name: \"c-a\" },\n ]\n },\n ]\n },\n {\n id: \"2\",\n name: \"d\",\n sub: [\n {\n id: \"2#1\",\n name: \"e\",\n sub_sub: [\n // I changed \"1#2#1\" to \"1#2#2\"\n { id: \"1#2#2\", name: \"e-a\" },\n ]\n }\n ]\n },\n]\n```\n\n========================================\n\nCode:\n```text\nexport const dummyData = [\n {\n id: \"1\",\n name: \"a\",\n sub: [\n {\n id: \"1#1\",\n name: \"b\",\n sub_sub: [\n { id: \"1#1#1\", name: \"b-a\" },\n { id: \"1#1#2\", name: \"b-b\" },\n ]\n },\n {\n id: \"1#2\",\n name: \"c\",\n sub_sub: [\n { id: \"1#2#1\", name: \"c-a\" },\n ]\n },\n ]\n },\n {\n id: \"2\",\n name: \"d\",\n sub: [\n {\n id: \"2#1\",\n name: \"e\",\n sub_sub: [\n { id: \"1#2#1\", name: \"e-a\" },\n ]\n }\n ]\n },\n]\n```\n\n```text\n<template>\n <div>\n <v-simple-table dense>\n <thead>\n <tr>\n <th class=\"blue lighten-5\">name</th>\n <th class=\"blue lighten-5\">sub_name</th>\n <th class=\"blue lighten-5\">sub_sub_name</th>\n </tr>\n </thead>\n <tbody>\n <template v-for=\"item in items\">\n <template v-for=\"(subitem, iSub) in item.sub\">\n <tr v-for=\"(sub_subitem, iSub_sub) in subitem.sub_sub\" :key=\"sub_subitem.id\">\n <td v-if=\"iSub === 0 & iSub_sub === 0\" :rowspan=\"rowSpanCalc(item)\">\n {{ item.name }}\n </td>\n <td v-if=\"iSub_sub === 0\" :rowspan=\"subitem.sub_sub.length\">\n {{ subitem.name }}\n </td>\n <td>{{ sub_subitem.name }}</td>\n </tr>\n </template>\n </template>\n </tbody>\n </v-simple-table>\n </div>\n</template>\n<script lang=\"ts\">\nimport { Component, Vue } from 'nuxt-property-decorator'\nimport { dummyData } from '~/store/dummy'\n\n@Component({})\nexport default class extends Vue {\n items: any = []\n\n created() {\n this.items = dummyData\n }\n\n rowSpanCalc(item: any) {\n const count = item.sub.reduce(\n (total: any, curr: any) => total + curr.sub_sub.length,\n 0\n )\n console.log(count);\n return count;\n }\n}\n</script>\n<style lang=\"scss\" scoped>\ntable {\n border-collapse: collapse !important;\n}\n.v-data-table--dense > .v-data-table__wrapper > table > tbody > tr > td {\n border-bottom: thin solid rgba(0, 0, 0, 0.12) !important;\n}\n</style>\n```\n\n```text\nvue.runtime.esm.js?2b0e:619 [Vue warn]: Duplicate keys detected: '1#2#1'. This may cause an update error.\n```\n\n```text\n<template v -for=\"(item,item_index) in items\">\n <template v -for=\"(subitem, iSub) in item.sub\">\n <tr\n v\n -for=\"(sub_subitem, iSub_sub) in subitem.sub_sub\"\n :\n key=\"`${item_index}-${iSub_sub}-${sub_subitem.id}`\"\n >\n <td v -if=\"iSub === 0 & iSub_sub === 0\" : rowspan=\"rowSpanCalc(item)\">\n {{ item.name }}\n </td>\n <td v -if=\"iSub_sub === 0\" : rowspan=\"subitem.sub_sub.length\">\n {{ subitem.name }}\n </td>\n <td>{{ sub_subitem.name }}</td>\n </tr>\n </template>\n</template>\n```\n\n```js\nexport const dummyData = [\n {\n id: \"1\",\n name: \"a\",\n sub: [\n {\n id: \"1#1\",\n name: \"b\",\n sub_sub: [\n { id: \"1#1#1\", name: \"b-a\" },\n { id: \"1#1#2\", name: \"b-b\" },\n ]\n },\n {\n id: \"1#2\",\n name: \"c\",\n sub_sub: [\n { id: \"1#2#1\", name: \"c-a\" },\n ]\n },\n ]\n },\n {\n id: \"2\",\n name: \"d\",\n sub: [\n {\n id: \"2#1\",\n name: \"e\",\n sub_sub: [\n // I changed \"1#2#1\" to \"1#2#2\"\n { id: \"1#2#2\", name: \"e-a\" },\n ]\n }\n ]\n },\n]\n```\n\n```text\n[Vue warn]: Duplicate keys detected: '1#2#1'. This may cause an update error.\n```\n\n```text\n\"1#2#1\"\n```\n\n========================================\n\nComments:\n- Thank you for your answer! I understood why I got error. Thanks!\n- Thanks a lot! In my error reason, I was using same index as key.\n- welcome! you were using id which may be duplicate. combining all 3 will create a unique id","metadata":{"transformedAt":"2026-08-18T18:33:07.898Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":357,"estimatedTokens":1795}}857{"id":"stack-77391591","source":"stackoverflow","questionId":77391591,"title":"How to properly wrap `useFetch` to access reactivity?","tags":["typescript","vue.js","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: How to properly wrap `useFetch` to access reactivity?\nTags: typescript, vue.js, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am wrapping `useFetch()` as a composable to provide a custom baseURL and to automatically set an authentication token, but when I call the composable within a component without the `await` keyword it does not behave as expected with reactivity. Normally, I can call const `{ data, pending, status } = useFetch('...')` and the UI will update once the promise resolves and `data` is available, but with the wrapper this does not work. Seems I must always use `await` with `useCustomFetch()`\n\nAny idea why this would not work?\n\nBelow is the custom wrapper.\n\n```\nimport type { UseFetchOptions } from 'nuxt/app'\nimport { defu } from 'defu'\n\nexport async function useCustomFetch(url: string, options: UseFetchOptions = {}) {\n const config = useRuntimeConfig()\n const { data, status, getSession }: { data: any; status: any; getSession: Function } = useAuth()\n\n const headers: HeadersInit | undefined = {}\n\n // NOTE: Set 'Authorization' header\n if (data && status.value === 'authenticated') {\n const session = await getSession({ required: true })\n headers.Authorization = `Bearer ${session.accessToken}`\n }\n\n const defaults: UseFetchOptions = {\n baseURL: config.public.baseApiUrl,\n headers,\n onResponse(_ctx) {\n // EX: _ctx.response._data = new myBusinessResponse(_ctx.response._data)\n },\n onResponseError(_ctx) {\n // TODO: Send notification to Sentry\n },\n }\n\n // NOTE: Deep defaults, use unjs/defu\n const params = defu(options, defaults)\n\n return useFetch(url, params)\n}\n```\n\nIn a component, this does **not** work.\n\n```\n\nconst { data, pending, status } = useCustomFetch('/resources')\n\n```\n\n========================================\n\nCode:\n```js\nimport type { UseFetchOptions } from 'nuxt/app'\nimport { defu } from 'defu'\n\nexport async function useCustomFetch<T>(url: string, options: UseFetchOptions<T> = {}) {\n const config = useRuntimeConfig()\n const { data, status, getSession }: { data: any; status: any; getSession: Function } = useAuth()\n\n const headers: HeadersInit | undefined = {}\n\n // NOTE: Set 'Authorization' header\n if (data && status.value === 'authenticated') {\n const session = await getSession({ required: true })\n headers.Authorization = `Bearer ${session.accessToken}`\n }\n\n const defaults: UseFetchOptions<T> = {\n baseURL: config.public.baseApiUrl,\n headers,\n onResponse(_ctx) {\n // EX: _ctx.response._data = new myBusinessResponse(_ctx.response._data)\n },\n onResponseError(_ctx) {\n // TODO: Send notification to Sentry\n },\n }\n\n // NOTE: Deep defaults, use unjs/defu\n const params = defu(options, defaults)\n\n return useFetch(url, params)\n}\n```\n\n```js\n<script setup>\nconst { data, pending, status } = useCustomFetch('/resources')\n</script>\n```\n\n```text\nuseFetch()\n```\n\n```text\nawait\n```\n\n```text\n{ data, pending, status } = useFetch('...')\n```\n\n```text\ndata\n```\n\n```text\nawait\n```\n\n```text\nuseCustomFetch()\n```\n\n```text\nfunction useCustomFetch<T>(url: string, options: UseFetchOptions<T> = {}) {\n let promise = Promise.resolve<unknown>(null);\n\n if (data && status.value === 'authenticated') {\n promise = promise\n .then(() => getSession({ required: true }))\n .then(session => {\n headers.Authorization = `Bearer ${session.accessToken}`\n })\n }\n\n ...\n\n promise = promise\n .then(() => useFetch(url, params));\n Object.assign(promise, ???);\n\n return promise as ReturnType<(typeof useFetch)<T>;\n}\n```\n\n```text\nfunction useCustomFetch<T>(url: string, options: UseFetchOptions<T> = {}) {\n ...\n const defaults: UseFetchOptions<T> = {\n async onRequest(_ctx) {\n const session = await getSession({ required: true })\n _ctx.options.headers = {\n ..._ctx.options.headers,\n Authorization: `Bearer ${session.accessToken}`\n }\n },\n ...\n return useFetch(url, params);\n}\n```\n\n```text\nawait useCustomFetch(url, { lazy: true, ... })\n```\n\n```text\nuseAsyncData\n```\n\n```text\nuseFetch\n```\n\n```text\nasync\n```\n\n```text\ndata\n```\n\n```text\nuseCustomFetch\n```\n\n```text\ndata\n```\n\n```text\nuseFetch\n```\n\n```text\nawait getSession\n```\n\n```text\nawait\n```\n\n```text\ngetSession\n```\n\n```text\nsession\n```\n\n```text\nawait\n```\n\n```text\nuseFetch\n```\n\n```text\nlazy\n```\n\n========================================\n\nComments:\n- The docs show that you need to `await` on `useFetch`'s result. Did you forget to write your `await` on `useCustomFetch`?\n- `useFetch` does not require `await`\n- await is required by the fact that useFetch returns a Promise, and you must await a Promise for it's resolved value. All the doc examples also use await. By your own admission, your code doesn't work *unless* you use await. Are you consulting some other documentation?\n- `await` is not required. Try to use `useFetch` without `await` and it works. If a function returns a promise, this does not mean that it requires `await` to resolve.\n- See the usage example from Nuxt's docs\n- @yoduh This is probably because they tried to normalize the use of useAsyncData and related composables. They still return the refs immediately, which is something you'd expect from non-nuxt asynchronous use... composable. Probably not advised without await because it's not documented and I've seen at least one post before where not using await caused a problem\n- Just out of curiosity, why is it not possible to just add a single header-why do I have to spread all the headers? When I just use `options.headers.Authorization =`Bearer ${session.accessToken}` the request fails.\n- It's a safer way to do a thing like this as options.header may or may not exist, and spread correctly handles non-object values","metadata":{"transformedAt":"2026-08-18T18:33:07.898Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":229,"estimatedTokens":1424}}858{"id":"stack-77415219","source":"stackoverflow","questionId":77415219,"title":"Turn all SASS code into CSS in Nuxt project","tags":["css","vue.js","sass","nuxt.js","nuxt3.js"],"text":"Title: Turn all SASS code into CSS in Nuxt project\nTags: css, vue.js, sass, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI have a project where part of the code is written in SASS. I want to get rid of SASS and work with vanilla CSS, so I'm trying to find a programatic way to turn all my SASS parts into CSS, or at least having a way to do it programatically in each component that I'm working on. At the end of the process, I would remove all SASS dependencies and have just CSS in my code.\n\nAny hints will be appreciated, thanks in advance!\n\n**Edit**:\nThe SASS/SCSS is written in component, pages and layout .vue files inside a `` or `` tag. Inside them, there are some imports with the format\n\n```\n@import './folder/css/stuff';\n\n.head-navigation\n```\n\n**Edit 2**:\nProposed solution doesn't work due to error\n\nError: Invalid CSS after \"@import './folder/css/stuff';\": expected 1\nselector or at-rule, was \".head-navigation\"\\n\n\ncheck live example here\n\n========================================\n\nCode:\n```text\n@import './folder/css/stuff';\n\n.head-navigation\n```\n\n```text\n<style lang=\"sass\">\n```\n\n```text\n<style lang=\"scss\">\n```\n\n```js\n// convert-sass.js\nconst fs = require('fs-extra');\nconst path = require('path');\nconst sass = require('node-sass');\nconst compiler = require('vue-template-compiler');\n\nconst vueDirectory = './src'; // path to all your .vue files.\n\nfunction convertSASSinVueFiles(dir) {\n // 1. iterate over all files inside the directory with .vue extension\n fs.readdirSync(dir).forEach(file => {\n const filePath = path.join(dir, file);\n if (fs.lstatSync(filePath).isDirectory()) {\n convertSASSinVueFiles(filePath);\n } else if (path.extname(file) === '.vue') {\n convertSASSinVueComponent(filePath);\n }\n });\n}\nfunction convertSASSinVueComponent(file) {\n\n const content = fs.readFileSync(file, 'utf8');\n // Parse the vue file\n const parsedComponent = compiler.parseComponent(content);\n /* 2. Find if there is a style tag with the lang attribute as sass.\n You can modify this as per your need. */\n if (parsedComponent.styles.length > 0 && \n (parsedComponent.styles[0].lang === 'sass' ||\n parsedComponent.styles[0].lang === 'scss')) {\n const sassCode = parsedComponent.styles[0].content;\n // convert the sass code to css.\n const cssCode = sass.renderSync(\n {\n data: sassCode,\n includePaths: ['./path/to/your/partials']\n }\n ).css.toString();\n // Replace the sass content with css code.\n const updatedContent = content.\n replace(/<style.*lang=\"s[ac]ss\".*>([\\s\\S]*?)<\\/style>/, \n `<style>${cssCode}</style>`);\n fs.writeFileSync(file, updatedContent);\n }\n}\nconvertSASSinVueFiles(vueDirectory);\n```\n\n```js\nconst isSass = parsedComponent.styles[0].lang === 'sass';\nconst cssCode = sass.renderSync(\n {\n data: sassCode,\n includePaths: ['./path/to/your/partials'],\n indentedSyntax: isSass // set to true for sass syntax\n }\n ).css.toString();\n```\n\n```text\nvue\n```\n\n```text\nsass/scss\n```\n\n```text\n.vue\n```\n\n```text\nsass\n```\n\n```text\ncss\n```\n\n```text\nsass/scss\n```\n\n```text\ncss\n```\n\n```text\nfs\n```\n\n```text\nfs\n```\n\n```text\nregex\n```\n\n```text\n/<style.*lang=\"s[ac]ss\".*>([\\s\\S]*?)<\\/style>/\n```\n\n```text\nscss\n```\n\n```text\nsass\n```\n\n```text\n.scss\n```\n\n```text\n.css\n```\n\n```text\n.sass\n```\n\n```text\n.scss\n```\n\n```text\nrenderSync()\n```\n\n```text\nincludePaths\n```\n\n```text\nincludePath\n```\n\n```text\n@import\n```\n\n```text\n./src/sass\n```\n\n```text\nincludePaths\n```\n\n```text\nscss/sass\n```\n\n```text\n@import './src/sass/someDir/typography';\n```\n\n```text\nincludePaths\n```\n\n========================================\n\nComments:\n- Does the SASS import mixins and variables from other files, or is it standalone?\n- They import mixins from other files as well.\n- Could you provide more details on how the project is structured? You've tagged it `vue.js` does this mean the SASS is all in .vue template files? Or are there also standalone .scss files?\n- Why not just use Sass: Playground? You'll need to manually copy/paste the sass contents into it and then the result back into the project but, still, I doubt it will be more effort than what you invested so far in this question. If you use mixins, just go to source and place those into the playground as well, where needed.\n- @tao that approach can work if you want to convert few files. For 500+ files it is not a good approach and can be very error-prone imho\n- Thanks for your reply. Here the thing is that I have to convert .vue files, that has just a part of SASS/SCSS, being the rest html and JS. You can see a working example here replit.com/@jesus38/Nuxt-SASS#src/example.vue\n- @Joe82 I think it's working right, why not accepting the answer?\n- @nmfzone sorry, had two busy days and didn't have time to check. Will do it today\n- here's what I did so far. Changed all imports to this syntax `@import './folder/css/stuff';` (note the semicolon and the quotes) in order to make it work. Now it fails in this step: `Error: Invalid CSS after \"@import './folder/css/stuff';\": expected 1 selector or at-rule, was \".head-navigation\"\\n` I checked this issue, but in my .vue file, the indentation seems correct (see my edit in the OP)\n- @Joe82 I have edited my answer to include your requirement. Please take a look at the updated answer.\n- Thanks for the edit, unfortunately, it yields the same error than before. I will give you the bounty, but I cannot mark it as right though.\n- @Joe82 can you somehow replicate this issue or reproduce this issue please? I can help you solve this and I want to solve it. This looks solvable. It seems like there is a wrong css/scss that is written because the correct scss will be converted to css by using above script.\n- @Joe82 I have tried to replicate your issue with a brand new partial `_lists.scss` which is inside a folder. It works perfectly for me. Please see the update code demo. Also can you please add some more scss from the file where you're getting this error? I can try to replicate that as well\n- @mandy8055 sorry for the delay (last week was busy as hell). I managed to replicate the issue here, let me know if you need more info replit.com/@jesus38/Nuxt-SASS-3\n- @Joe82 Alright. Now I got your final issue. I have updated my answer. Please have a look. In the code demo I provided both type of files i.e. `.scss`(example.vue) and `.sass`(example2.vue) and included the above code which you replicated. Now if you run the convert-sass script(`node convert-sass.js`) it will convert both of them. Please let me know if you want a standalone script for `sass` and not `scss`. I provided a complete solution which would work for both:)\n- Finally got it working, just had a few issues with imports and deprecated function. Thanks for that!","metadata":{"transformedAt":"2026-08-18T18:33:07.898Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":31,"totalLines":225,"estimatedTokens":1708}}859{"id":"stack-76810996","source":"stackoverflow","questionId":76810996,"title":"How to prevent the scroll from jumping to the top of the web page on Nuxt3 reload","tags":["vue.js","nuxt.js","vue-router","nuxt3.js"],"text":"Title: How to prevent the scroll from jumping to the top of the web page on Nuxt3 reload\nTags: vue.js, nuxt.js, vue-router, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI have a problem with scrollBehavior in Nuxt.js 3. When I refresh the page (when static content is served), the scroll jumps abruptly to the top of the page. However, after serving the static content, there is an automatic scroll to the previous position (the position from which the refresh was triggered), which creates an unpleasant \"jumping\" effect on the website.\n\nHow can I prevent the scroll from returning to the top of the document when reloading Nuxt3 and keep the scroll at the same position?\n\n========================================\n\nCode:\n```js\nonMounted(() => {\n if (process.client && window) {\n window.history.scrollRestoration = 'auto';\n }\n})\n```\n\n```css\nhtml {\n scroll-behavior: smooth;\n}\n```\n\n```text\nSSR\n```\n\n```text\nnuxt.config\n```\n\n```text\nSSR\n```\n\n========================================\n\nComments:\n- Do you have a reproduction on your issue? In your case, it is harder for us to help without the reproduction. You can use stackblitz or codesanbox\n- I think that \"pages\" directory is creating such effect... You can check reproduction of my code here: stackblitz.com/edit/nuxt-starter-cgquz4?file=pages%2Findex.v‌​ue\n- Thanks a lot. You really helped me, I was struggling with this issue for two days.\n- I'm glad I could be of help. You can mark it as an answer by clicking the check icon. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:07.898Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":45,"estimatedTokens":379}}860{"id":"stack-72543755","source":"stackoverflow","questionId":72543755,"title":"Nuxt-ts, vuex error: This dependency was not found in .nuxt/store.js","tags":["javascript","nuxt.js"],"text":"Title: Nuxt-ts, vuex error: This dependency was not found in .nuxt/store.js\nTags: javascript, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nOS: Windows 10\n\n*what am I already did*\n\nDelete .nuxt and run \"yarn run dev\": **not work**\n\nDelete .nuxt and run \"npm run dev\": **not work**\n\nChange node version to 16.15.1 and 14.19.3: **not work**\n\n**Team Repository, can not recreate the project.**\n\n**I think because nuxtJS generate .nuxt/store.js with double back slash**\n\nbut I can not force nuxtJS to use forward slash\n\n```\nERROR Failed to compile with 1 errors friendly-errors 15:27:35 \n\nThis dependency was not found: friendly-errors 15:27:35 \n friendly-errors 15:27:35 \n* ..\\store\\signIn.ts in ./.nuxt/store.js\n```\n\n/.nuxt/store.js\n\n```\nimport Vue from \"vue\";\nimport Vuex from \"vuex\";\n\nVue.use(Vuex);\n\nconst VUEX_PROPERTIES = [\"state\", \"getters\", \"actions\", \"mutations\"];\n\nlet store = {};\n\n(function updateModules() {\n store = normalizeRoot(require(\"..\\\\store\\\\index.ts\"), \"store/index.ts\");\n\n // If store is an exported method = classic mode (deprecated)\n\n if (typeof store === \"function\") {\n return console.warn(\n \"Classic mode for store/ is deprecated and will be removed in Nuxt 3.\"\n );\n }\n\n // Enforce store modules\n store.modules = store.modules || {};\n\n resolveStoreModules(require(\"..\\\\store\\\\auth.ts\"), \"auth.ts\");\n resolveStoreModules(require(\"..\\\\store\\\\profile.ts\"), \"profile.ts\");\n resolveStoreModules(require(\"..\\\\store\\\\signIn.ts\"), \"signIn.ts\");\n```\n\n*I don't know why it passes all require() to error at \"..\\store\\signIn.ts\"*\n\n/store/index.js\n\n```\nexport const state = () => ({})\nexport const getters = {}\nexport const mutations = {}\nexport const actions = {}\n```\n\n/store/signIn.js\n\n```\n// /store/signIn.ts\nimport { getterTree, mutationTree, actionTree } from 'typed-vuex'\n```\n\npackage.json\n\n```\n{\n \"name\": \"nuxt-web\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt-ts\",\n \"build\": \"nuxt-ts build\",\n \"generate\": \"nuxt-ts generate\",\n \"start\": \"nuxt-ts start\",\n \"lint\": \"eslint --ext .ts,.js,.vue .\",\n \"lint:js\": \"eslint --ext \\\".js,.ts,.vue\\\" --ignore-path .gitignore .\",\n \"lintfix\": \"npm run lint:js -- --fix\"\n },\n \"dependencies\": {\n \"@nuxt/typescript-runtime\": \"^2.1.0\",\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"bootstrap\": \"^4.6.1\",\n \"bootstrap-vue\": \"^2.21.2\",\n \"core-js\": \"^3.19.3\",\n \"nuxt\": \"^2.15.8\",\n \"nuxt-property-decorator\": \"^2.9.1\",\n \"nuxt-typed-vuex\": \"^0.3.0\",\n \"nuxt-web3\": \"^0.0.8\",\n \"vue\": \"^2.6.14\",\n \"vue-class-component\": \"^7.2.6\",\n \"vue-server-renderer\": \"^2.6.14\",\n \"vue-template-compiler\": \"^2.6.14\",\n \"webpack\": \"^4.46.0\"\n },\n \"devDependencies\": {\n \"@babel/eslint-parser\": \"^7.16.3\",\n \"@nuxt/types\": \"^2.15.8\",\n \"@nuxt/typescript-build\": \"^2.1.0\",\n \"@nuxtjs/eslint-config-typescript\": \"^8.0.0\",\n \"@nuxtjs/eslint-module\": \"^3.0.2\",\n \"@nuxtjs/vercel-builder\": \"^0.21.3\",\n \"@types/vuelidate\": \"^0.7.15\",\n \"eslint\": \"^8.4.1\",\n \"eslint-plugin-nuxt\": \"^3.1.0\",\n \"eslint-plugin-vue\": \"^8.2.0\",\n \"typescript\": \"^4.6.3\",\n \"vuelidate\": \"^0.7.7\"\n }\n}\n```\n\nit's my first question, apologies if it unclear\n\n========================================\n\nCode:\n```text\nERROR Failed to compile with 1 errors friendly-errors 15:27:35 \n\nThis dependency was not found: friendly-errors 15:27:35 \n friendly-errors 15:27:35 \n* ..\\store\\signIn.ts in ./.nuxt/store.js\n```\n\n```text\nimport Vue from \"vue\";\nimport Vuex from \"vuex\";\n\nVue.use(Vuex);\n\nconst VUEX_PROPERTIES = [\"state\", \"getters\", \"actions\", \"mutations\"];\n\nlet store = {};\n\n(function updateModules() {\n store = normalizeRoot(require(\"..\\\\store\\\\index.ts\"), \"store/index.ts\");\n\n // If store is an exported method = classic mode (deprecated)\n\n if (typeof store === \"function\") {\n return console.warn(\n \"Classic mode for store/ is deprecated and will be removed in Nuxt 3.\"\n );\n }\n\n // Enforce store modules\n store.modules = store.modules || {};\n\n resolveStoreModules(require(\"..\\\\store\\\\auth.ts\"), \"auth.ts\");\n resolveStoreModules(require(\"..\\\\store\\\\profile.ts\"), \"profile.ts\");\n resolveStoreModules(require(\"..\\\\store\\\\signIn.ts\"), \"signIn.ts\");\n```\n\n```text\nexport const state = () => ({})\nexport const getters = {}\nexport const mutations = {}\nexport const actions = {}\n```\n\n```text\n// /store/signIn.ts\nimport { getterTree, mutationTree, actionTree } from 'typed-vuex'\n```\n\n```text\n{\n \"name\": \"nuxt-web\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt-ts\",\n \"build\": \"nuxt-ts build\",\n \"generate\": \"nuxt-ts generate\",\n \"start\": \"nuxt-ts start\",\n \"lint\": \"eslint --ext .ts,.js,.vue .\",\n \"lint:js\": \"eslint --ext \\\".js,.ts,.vue\\\" --ignore-path .gitignore .\",\n \"lintfix\": \"npm run lint:js -- --fix\"\n },\n \"dependencies\": {\n \"@nuxt/typescript-runtime\": \"^2.1.0\",\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"bootstrap\": \"^4.6.1\",\n \"bootstrap-vue\": \"^2.21.2\",\n \"core-js\": \"^3.19.3\",\n \"nuxt\": \"^2.15.8\",\n \"nuxt-property-decorator\": \"^2.9.1\",\n \"nuxt-typed-vuex\": \"^0.3.0\",\n \"nuxt-web3\": \"^0.0.8\",\n \"vue\": \"^2.6.14\",\n \"vue-class-component\": \"^7.2.6\",\n \"vue-server-renderer\": \"^2.6.14\",\n \"vue-template-compiler\": \"^2.6.14\",\n \"webpack\": \"^4.46.0\"\n },\n \"devDependencies\": {\n \"@babel/eslint-parser\": \"^7.16.3\",\n \"@nuxt/types\": \"^2.15.8\",\n \"@nuxt/typescript-build\": \"^2.1.0\",\n \"@nuxtjs/eslint-config-typescript\": \"^8.0.0\",\n \"@nuxtjs/eslint-module\": \"^3.0.2\",\n \"@nuxtjs/vercel-builder\": \"^0.21.3\",\n \"@types/vuelidate\": \"^0.7.15\",\n \"eslint\": \"^8.4.1\",\n \"eslint-plugin-nuxt\": \"^3.1.0\",\n \"eslint-plugin-vue\": \"^8.2.0\",\n \"typescript\": \"^4.6.3\",\n \"vuelidate\": \"^0.7.7\"\n }\n}\n```\n\n```text\n12.17.0\n```\n\n```text\n.next\n```\n\n```text\nnode_modules\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run dev\n```\n\n========================================\n\nComments:\n- Are you on a Windows machine? On MacOS, the paths in `.nuxt/store.js` are with normal slash, not backslash.\n- Also, since nuxt 2.13 if I remember well, the `@nuxt/typescript-runtime` module isn't required anymore. Only the `@nuxt/typescript-build` is necessary. So you don't actually need to use `nuxt-ts` command, the regular `nuxt` command should work. Try it :)\n- @Kapcash I'm on Windows 10 Thanks for the comment, now I use `nuxt` instead of `nuxt-ts` and it's work! but stuck in the same problem at `This dependency was not found: * ..\\store\\signIn.ts in ./.nuxt/store.js` : ( do you have any idea to fix this\n- And if you remove the `signIn.ts` file, it does compile? Honestly I have no idea why this fails :(","metadata":{"transformedAt":"2026-08-18T18:33:07.898Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":257,"estimatedTokens":1724}}861{"id":"stack-72006380","source":"stackoverflow","questionId":72006380,"title":"Square bracket notation for custom classes from Tailwind doesn't work in a Nuxt application","tags":["vue.js","nuxt.js","tailwind-css"],"text":"Title: Square bracket notation for custom classes from Tailwind doesn't work in a Nuxt application\nTags: vue.js, nuxt.js, tailwind-css\nSource: Stack Overflow\n\nQuestion:\nI have created a Nuxt application with TailwindCSS. For some reason, the square bracket notation from Tailwind doesn't work. If I have this div =>\n\n```\nsome text\n```\n\nthe h-[155px] class is ignored. If instead I use `h-24`, it works fine, the height is applied.\nI have also noticed that I haven't got an assets/css/tailwind.css directory. Is this normal ? Could it be the reason it doesn't work ?\nThis is my nuxt.config.js file =>\n\n```\nexport default {\n // Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode\n ssr: false,\n\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: 'gimm',\n htmlAttrs: {\n lang: 'en',\n },\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: '' },\n { name: 'format-detection', content: 'telephone=no' },\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n // https://go.nuxtjs.dev/eslint\n '@nuxtjs/eslint-module',\n // https://go.nuxtjs.dev/tailwindcss\n '@nuxtjs/tailwindcss',\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\n // https://go.nuxtjs.dev/axios\n '@nuxtjs/axios',\n ],\n\n // Axios module configuration: https://go.nuxtjs.dev/config-axios\n axios: {\n // Workaround to avoid enforcing hard-coded localhost:3000: https://github.com/nuxt-community/axios-module/issues/308\n baseURL: '/',\n },\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {},\n}\n```\n\nand this is my package.json =>\n\n```\n{\n \"name\": \"gimm\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint:js\": \"eslint --ext \\\".js,.vue\\\" --ignore-path .gitignore .\",\n \"lint:prettier\": \"prettier --check .\",\n \"lint\": \"yarn lint:js && yarn lint:prettier\",\n \"lintfix\": \"prettier --write --list-different . && yarn lint:js --fix\"\n },\n \"dependencies\": {\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"core-js\": \"^3.19.3\",\n \"nuxt\": \"^2.15.8\",\n \"vue\": \"^2.6.14\",\n \"vue-server-renderer\": \"^2.6.14\",\n \"vue-template-compiler\": \"^2.6.14\",\n \"webpack\": \"^4.46.0\"\n },\n \"devDependencies\": {\n \"@babel/eslint-parser\": \"^7.16.3\",\n \"@nuxtjs/eslint-config\": \"^8.0.0\",\n \"@nuxtjs/eslint-module\": \"^3.0.2\",\n \"@nuxtjs/tailwindcss\": \"^4.2.1\",\n \"eslint\": \"^8.4.1\",\n \"eslint-config-prettier\": \"^8.3.0\",\n \"eslint-plugin-nuxt\": \"^3.1.0\",\n \"eslint-plugin-vue\": \"^8.2.0\",\n \"postcss\": \"^8.4.4\",\n \"prettier\": \"^2.5.1\"\n }\n}\n```\n\n========================================\n\nCode:\n```html\n<div class=\"h-[155px] bg-red-300\">some text</div>\n```\n\n```js\nexport default {\n // Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode\n ssr: false,\n\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: 'gimm',\n htmlAttrs: {\n lang: 'en',\n },\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: '' },\n { name: 'format-detection', content: 'telephone=no' },\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n // https://go.nuxtjs.dev/eslint\n '@nuxtjs/eslint-module',\n // https://go.nuxtjs.dev/tailwindcss\n '@nuxtjs/tailwindcss',\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\n // https://go.nuxtjs.dev/axios\n '@nuxtjs/axios',\n ],\n\n // Axios module configuration: https://go.nuxtjs.dev/config-axios\n axios: {\n // Workaround to avoid enforcing hard-coded localhost:3000: https://github.com/nuxt-community/axios-module/issues/308\n baseURL: '/',\n },\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {},\n}\n```\n\n```json\n{\n \"name\": \"gimm\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint:js\": \"eslint --ext \\\".js,.vue\\\" --ignore-path .gitignore .\",\n \"lint:prettier\": \"prettier --check .\",\n \"lint\": \"yarn lint:js && yarn lint:prettier\",\n \"lintfix\": \"prettier --write --list-different . && yarn lint:js --fix\"\n },\n \"dependencies\": {\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"core-js\": \"^3.19.3\",\n \"nuxt\": \"^2.15.8\",\n \"vue\": \"^2.6.14\",\n \"vue-server-renderer\": \"^2.6.14\",\n \"vue-template-compiler\": \"^2.6.14\",\n \"webpack\": \"^4.46.0\"\n },\n \"devDependencies\": {\n \"@babel/eslint-parser\": \"^7.16.3\",\n \"@nuxtjs/eslint-config\": \"^8.0.0\",\n \"@nuxtjs/eslint-module\": \"^3.0.2\",\n \"@nuxtjs/tailwindcss\": \"^4.2.1\",\n \"eslint\": \"^8.4.1\",\n \"eslint-config-prettier\": \"^8.3.0\",\n \"eslint-plugin-nuxt\": \"^3.1.0\",\n \"eslint-plugin-vue\": \"^8.2.0\",\n \"postcss\": \"^8.4.4\",\n \"prettier\": \"^2.5.1\"\n }\n}\n```\n\n```text\nh-24\n```\n\n```text\nnode_modules\n```\n\n```text\nyarn upgrade\n```\n\n```text\npackage.json\n```\n\n```text\nassets/css/tailwind.css\n```\n\n========================================\n\nComments:\n- @Maxime your version the `@nuxtjs/tailwindcss` module that you're using is apparently using a version before the `2.2.0` of Tailwind, hence it looks like the arbitrary values are not supported as you can see on the releases page. I recommend using the latest v3 of Tailwind, as showcased in my repo. That way, you'll get the best experience and all the latest cool stuff at the same time. Tell me if you have any issues running it.","metadata":{"transformedAt":"2026-08-18T18:33:07.898Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":234,"estimatedTokens":1558}}862{"id":"stack-74178950","source":"stackoverflow","questionId":74178950,"title":"How to get Nuxt-img to work on nuxt3 generate?","tags":["vue.js","nuxt.js","vuejs3","nuxt3.js","static-site-generation"],"text":"Title: How to get Nuxt-img to work on nuxt3 generate?\nTags: vue.js, nuxt.js, vuejs3, nuxt3.js, static-site-generation\nSource: Stack Overflow\n\nQuestion:\ni am trying to use nuxt-image on NUXT3, but it seems it doesn't work with the generate command. Images work during dev, but get a 404 when using nuxt generate.\n\nin my nuxt config i have\n\n```\nmodules: [\"@nuxt/image-edge\"], \nimage: {\n dir: \"assets/images\",\n },\n```\n\nthen in my files i have\n\n```\n\n```\n\nSo i am wondering if anyone else had a problem or if this is just a compatibility issue with nuxt-image and nuxt3 generate\n\n========================================\n\nTop Answer:\nReading this part of the documentation\n\nFor static provider, if images weren't crawled during generation (unreachable modals, pages or dynamic runtime size), changing dir from static causes 404 errors.\n\nThere are other few bugs if you change `dir` to something else than `static` apparently.\n\nCan't you stick to `static`? Will probably avoid you quite some issues IMO.\n\n========================================\n\nCode:\n```text\nmodules: [\"@nuxt/image-edge\"], \nimage: {\n dir: \"assets/images\",\n },\n```\n\n```text\n<NuxtImg\n format=\"webp\"\n class=\"mobile\"\n src=\"/website/home/above-fold-illustration-mobile.png\"\n alt=\"illustration\"\n aria-hidden=\"true\"\n />\n```\n\n```text\ndir\n```\n\n```text\nstatic\n```\n\n```text\nstatic\n```\n\n```text\nmodules: ['@nuxt/image-edge'],\nimage: { dir: 'assets/img' }\n```\n\n```text\n<NuxtImg src=\"logo.png\" format=\"wepb\"/>\n```\n\n```text\n<NuxtImg src=\"/logo.png\" format=\"wepb\"/>\n```\n\n========================================\n\nComments:\n- Where do you host it? How do you try to preview the generate website?\n- so `static` is the default option. and even if i dont use dir and move my images to public this component still breaks on generate\n- Hm, right it's `public` in Nuxt3 now and not `static` anymore. Maybe update the dir to be `public` so. @Jean-PierreEngelbrecht\n- just tested it, even when setting dir to public it still doesnt work. what is odd for me is that it works in dev mode but not on static generation, so i am wondering if this is just some compatibility issue\n- The fact that it works in dev is not surprising at all since it's far easier to setup when you have an actively running dev server. Totally legit. I'm not sure if there are not some things that may be related to your issues: github.com/nuxt/image/issues?q=is%3Aissue+static+ I'm not sure that `@nuxt/image-edge` is still the way to go tho, since I saw some people successfully running their thing without the latest version.\n- so i think only image-edge supports nuxt3 at this point. v1.image.nuxtjs.org/get-started\n- Nvm, you're damn right haha.\n- Not working for me either with Nuxt3, posted a comment here github.com/nuxt/image/issues/215#issuecomment-1692573101. Will look into nuxt/image-edge.","metadata":{"transformedAt":"2026-08-18T18:33:07.898Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":91,"estimatedTokens":713}}863{"id":"stack-74135298","source":"stackoverflow","questionId":74135298,"title":"__vite_ssr_import_1__.Client is not a constructor Error","tags":["vue.js","nuxt.js","pinia","appwrite"],"text":"Title: __vite_ssr_import_1__.Client is not a constructor Error\nTags: vue.js, nuxt.js, pinia, appwrite\nSource: Stack Overflow\n\nQuestion:\nI am developing a simple app to showcase CRUD operations with Appwrite and Nuxt 3 (Release Candidate 11). The source code to the same can be found here.\n\nI am using the landing page of the app (`index.vue`) for simple redirection i.e. if the `account` exits in the `accountStore`, I want to redirect the user to `/workouts` route, else ask them to login by redirection to the `/login` route.\n\nThe problem I am facing is when I am landing on the `index.vue` page (with no user session in progress in Appwrite), I am still getting redirected to `/workouts` route, instead of the `/login` route. I presume the reason for the same is the following error that is being logged in the console.\nhttps://i.sstatic.net/gRzy6.png\n\nI need help in figuring out from where is the error message originating and how to possibly remedy it.\n\nHere is my public github repo: https://github.com/EshaanAgg/workout-buddy\n\n========================================\n\nTop Answer:\nThe Vite error “is not a constructor” means the symbol you’re trying to instantiate is undefined when evaluated by Vite’s SSR loader. That typically happens when there’s a circular import chain, so the module’s exports haven’t been fully initialized yet.\n\nIf you're using barrel (index.ts) files, try commenting out the exports and/or using more granular and direct imports instead of importing everything from the barrel files.\n\nIf you're using eslint, you could also try the eslint-plugin-import rule import/no-cycle to catch circular import chains early.\n\n========================================\n\nCode:\n```text\nindex.vue\n```\n\n```text\naccount\n```\n\n```text\naccountStore\n```\n\n```text\n/workouts\n```\n\n```text\n/login\n```\n\n```text\nindex.vue\n```\n\n```text\n/workouts\n```\n\n```text\n/login\n```\n\n```js\n{\n // ... other stuff\n ssr: false\n}\n```\n\n========================================\n\nComments:\n- Hi, do you mind sharing some of the files written down in the stacktrace that we can see in your screenshot?\n- Hey @kissu! You can check them out here\n- Quite a long shot and quite drastic solution, especially when you can disable that locally or even import some code on client-side only (locally). I don't recommend that one.\n- SSR is of course more complex for quite a decent amount of (good) reasons, but fallback'ing to an SPA is probably not the way to go.\n- Tried disabling `ssr` but still the error persists.\n- @EshaanAggarwal of course, the solution is quite unrelated to the issue.\n- @EshaanAggarwal, did you clean/rebuild after? The error went away for me 🤔\n- I did, but still the error persists.\n- Update: Performed a hard reset by deleting the local copy of the repository, and recloning it. Now in the latest commit, disabling `ssr` gets rid of the errors, but with it the error persists.","metadata":{"transformedAt":"2026-08-18T18:33:07.898Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":79,"estimatedTokens":721}}864{"id":"stack-71576750","source":"stackoverflow","questionId":71576750,"title":"Nuxtjs i18n locale is always set to 'en' on the first load of a static generated page","tags":["nuxt.js","nuxt-i18n"],"text":"Title: Nuxtjs i18n locale is always set to 'en' on the first load of a static generated page\nTags: nuxt.js, nuxt-i18n\nSource: Stack Overflow\n\nQuestion:\nI am using the Nuxt i18n module in my website for the localized content.\n\nI have it setup as follows in nuxt.config.js:\n\n```\n[\n 'nuxt-i18n',\n {\n locales: ['en', 'fr', 'ar'],\n defaultLocale: 'en',\n strategy: 'prefix',\n vueI18n: {\n fallbackLocale: 'en',\n messages: {\n en: {\n welcome: 'Welcome'\n },\n fr: {\n welcome: 'Bienvenue'\n },\n ar: {\n welcome: 'أهلا بك'\n }\n }\n }\n }\n]\n```\n\nAfter doing the following:\n\n```\nnpm run generate\nnpm run start\n```\n\nAnd clearing site data in my browser I attempt to access:\n\n```\nhttp://localhost:3000/ar/\n```\n\nThe locale gets set to 'en' and I get redirected to\n\n```\nhttp://localhost:3000/en/\n```\n\nBut now if I try again with the locale set to 'ar' the page loads with the correct locale (in this case: 'http://localhost:3000/ar/')\n\nI also tried setting the defaultLocale and fallbackLocale to 'ar' instead of 'en' and testing everything again. But I got the same result.\n\nAny suggestions or ideas on why this is happening and how to fix it are much appreciated.\nThank you in advance\n\n========================================\n\nCode:\n```text\n[\n 'nuxt-i18n',\n {\n locales: ['en', 'fr', 'ar'],\n defaultLocale: 'en',\n strategy: 'prefix',\n vueI18n: {\n fallbackLocale: 'en',\n messages: {\n en: {\n welcome: 'Welcome'\n },\n fr: {\n welcome: 'Bienvenue'\n },\n ar: {\n welcome: 'أهلا بك'\n }\n }\n }\n }\n]\n```\n\n```text\nnpm run generate\nnpm run start\n```\n\n```text\nhttp://localhost:3000/ar/\n```\n\n```text\nhttp://localhost:3000/en/\n```\n\n```text\n?lang=es\n```\n\n========================================\n\nComments:\n- Thanks, adding detectBrowserLanguage: false in nuxt.config.js worked\n- Link to the docs has changed: v8.i18n.nuxtjs.org/guide/browser-language-detection","metadata":{"transformedAt":"2026-08-18T18:33:07.898Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":110,"estimatedTokens":481}}865{"id":"stack-76760705","source":"stackoverflow","questionId":76760705,"title":"How to change tooltip background of Vuetify 3?","tags":["nuxt.js","vuetify.js"],"text":"Title: How to change tooltip background of Vuetify 3?\nTags: nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nI'm using the latest version of vuetify with Nuxt 3. I have a vuetify.js plugin:\n\n```\n`// plugins/vuetify.js\nimport { createVuetify} from \"vuetify\";\nimport * as components from \"vuetify/components\";\nimport * as directives from \"vuetify/directives\";\n\nconst myCustomLightTheme = {\n dark: false,\n colors: {\n background: '#03DAC6',\n surface: '#FFFFFF',\n primary: '#6200EE',\n 'primary-darken-1': '#3700B3',\n secondary: '#03DAC6',\n 'secondary-darken-1': '#018786',\n error: '#B00020',\n info: '#2196F3',\n success: '#4CAF50',\n warning: '#FB8C00'\n },\n};\nmyCustomLightTheme.tooltip = {\n color: 'black',\n background: 'yellow',\n};\n\nexport default defineNuxtPlugin((nuxtApp) => {\n const vuetify = createVuetify({\n // theme: {\n // defaultTheme: 'myCustomLightTheme',\n // themes: {\n // myCustomLightTheme,\n // },\n // },\n theme: {\n defaultTheme: 'dark',\n themes: {\n myCustomLightTheme\n }\n },\n ssr: true,\n components,\n directives,\n });\n\n nuxtApp.vueApp.use(vuetify);\n});`\n```\n\nAs it seems, myCustomLightTheme gets loaded but still I cannot change the background color of the tooltip. How to proceed ?\n\nI've already pasted the relevant code. I was expecting to be able to change the background color of the tooltip.\n\n========================================\n\nTop Answer:\nIf someone is looking for an answer that doesn't include changing color declarations.\n\nAdd the **content-class** to the v-tooltip, and directly change the background or text color.\n\n```\n\n```\n\nAdd CSS:\n\n```\n.custom-tooltip{\n // override styles with !important \n }\n```\n\n========================================\n\nCode:\n```text\n`// plugins/vuetify.js\nimport { createVuetify} from \"vuetify\";\nimport * as components from \"vuetify/components\";\nimport * as directives from \"vuetify/directives\";\n\nconst myCustomLightTheme = {\n dark: false,\n colors: {\n background: '#03DAC6',\n surface: '#FFFFFF',\n primary: '#6200EE',\n 'primary-darken-1': '#3700B3',\n secondary: '#03DAC6',\n 'secondary-darken-1': '#018786',\n error: '#B00020',\n info: '#2196F3',\n success: '#4CAF50',\n warning: '#FB8C00'\n },\n};\nmyCustomLightTheme.tooltip = {\n color: 'black',\n background: 'yellow',\n};\n\nexport default defineNuxtPlugin((nuxtApp) => {\n const vuetify = createVuetify({\n // theme: {\n // defaultTheme: 'myCustomLightTheme',\n // themes: {\n // myCustomLightTheme,\n // },\n // },\n theme: {\n defaultTheme: 'dark',\n themes: {\n myCustomLightTheme\n }\n },\n ssr: true,\n components,\n directives,\n });\n\n nuxtApp.vueApp.use(vuetify);\n});`\n```\n\n```js\nconst myCustomLightTheme = {\n dark: false,\n colors: {\n 'surface-variant': '#ffff00',\n 'on-surface-variant': '#ffffff',\n ....\n },\n};\n```\n\n```css\n.v-tooltip.v-overlay > .v-overlay__content {\n background: rgba(var(--v-theme-surface-variant),1);\n }\n```\n\n```text\n--v-theme-surface-variant\n```\n\n```text\n--v-theme-on-surface-variant\n```\n\n```text\n<v-tooltip activator=\"parent\" location=\"bottom\" content-class=\"custom-tooltip\">\n<v-tooltip>\n```\n\n```text\n.custom-tooltip{\n // override styles with !important \n }\n```\n\n========================================\n\nComments:\n- Thanks a lot, I had to change the colors to rgba or hex and then they worked. However, for my use case I want to set the background color white-ish, so I'm using 'surface-variant': 'rgba(255, 255, 255, 1)'. However, the background in the back is black and as such the tooltip appears as gray and not white. Any ideas how to change it? Is there some documentation for this ? I haven't found it !\n- Oh, you'll have to override the CSS for that, have a look at the updated answer\n- Warning: if you define `'on-surface-variant'` in a Vuetify custom theme, it will change the color in more components than just VTooltip.","metadata":{"transformedAt":"2026-08-18T18:33:07.899Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":173,"estimatedTokens":966}}866{"id":"stack-73085392","source":"stackoverflow","questionId":73085392,"title":"Nuxt avoid import of client-side script for server-side rendering","tags":["vue.js","nuxt.js"],"text":"Title: Nuxt avoid import of client-side script for server-side rendering\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn my nuxt.js application, I have a script that imports an NPM package which is only compatible with browser contexts (it references `document`, `location`, `window`, etc.)\n\nIs there a way to exclude this from SSR?\n\n```\nimport thing from \"@vendor/thing\"; // causes `document not defined` error\nexport default showThing(){\n if (process.client) {\n thing();\n }\n}\n```\n\nI can use the method with `process.client` but this file is still imported in my components.\n\n========================================\n\nCode:\n```js\nimport thing from \"@vendor/thing\"; // causes `document not defined` error\nexport default showThing(){\n if (process.client) {\n thing();\n }\n}\n```\n\n```text\ndocument\n```\n\n```text\nlocation\n```\n\n```text\nwindow\n```\n\n```text\nprocess.client\n```\n\n```js\nexport default showThing(){\n if (process.client) {\n const thing = await import('@vendor/thing')\n thing()\n }\n}\n```\n\n========================================\n\nComments:\n- Also, if your package could be used locally, do that rather than loading it globally. As explained here: stackoverflow.com/a/67751550/8816585\n- i think there would be problems after the build.\n- @payam_sbr why would it? Should be all good.","metadata":{"transformedAt":"2026-08-18T18:33:07.899Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":63,"estimatedTokens":326}}867{"id":"stack-72239511","source":"stackoverflow","questionId":72239511,"title":"Build error with Nuxt 2.15.7 - Can't resolve a CSS @font-face URL","tags":["vue.js","fonts","nuxt.js","tailwind-css","postcss"],"text":"Title: Build error with Nuxt 2.15.7 - Can't resolve a CSS @font-face URL\nTags: vue.js, fonts, nuxt.js, tailwind-css, postcss\nSource: Stack Overflow\n\nQuestion:\nI am trying to build my project but there is an error during build process. I entered this command:\n\n```\nyarn build\n```\n\nthen I saw this:\n\n```\nERROR in ./assets/css/main.css (./node_modules/@nuxt/postcss8/node_modules/css-loader/dist/cjs.js??ref--3-oneOf-1-1!./node_modules/@nuxt/postcss8/node_modules/postcss-loader/dist/cjs.js??ref--3-oneOf-1-2!./assets/css/main.css)\nModule build failed (from ./node_modules/@nuxt/postcss8/node_modules/css-loader/dist/cjs.js):\nError: Can't resolve '~/static/fonts/farsi/eot/iranyekanwebregular.eot' in '/Users/mohammadamin/WebstormProjects/test/assets/css'\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/Resolver.js:209:21\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/Resolver.js:285:5\n at eval (eval at create (/Users/mohammadamin/WebstormProjects/test/node_modules/tapable/lib/HookCodeFactory.js:33:10), :15:1)\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js:44:7\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/Resolver.js:285:5\n at eval (eval at create (/Users/mohammadamin/WebstormProjects/test/node_modules/tapable/lib/HookCodeFactory.js:33:10), :15:1)\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/Resolver.js:285:5\n at eval (eval at create (/Users/mohammadamin/WebstormProjects/test/node_modules/tapable/lib/HookCodeFactory.js:33:10), :27:1)\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js:67:43\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/Resolver.js:285:5\n at eval (eval at create (/Users/mohammadamin/WebstormProjects/test/node_modules/tapable/lib/HookCodeFactory.js:33:10), :672:1)\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/AliasPlugin.js:67:43\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/Resolver.js:285:5\n at eval (eval at create (/Users/mohammadamin/WebstormProjects/test/node_modules/tapable/lib/HookCodeFactory.js:33:10), :15:1)\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js:44:7\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/Resolver.js:285:5\n @ ./assets/css/main.css 4:14-217\n @ ./.nuxt/App.js\n @ ./.nuxt/index.js\n @ ./.nuxt/client.js\n @ multi ./node_modules/@nuxt/components/lib/installComponents.js ./.nuxt/client.js\n```\n\nI must mention that the project build successfully on windows 10 but when I enter the build command on MacBook Air M1 I got this error. and I had to replace node-sass with sass because node-sass not compatible with M1\n\nI tried different ways like replacing ~assets/fonts with ~/static/fonts or just /font/... but they all fail.\n\nThis is my package.json:\n\n```\n{\n \"name\": \"test\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"@nuxt/postcss8\": \"^1.1.3\",\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/i18n\": \"^7.2.0\",\n \"cookie-universal-nuxt\": \"^2.1.5\",\n \"core-js\": \"^3.15.1\",\n \"jalali-moment\": \"^3.3.11\",\n \"nuxt\": \"^2.15.7\",\n \"v-mask\": \"^2.3.0\",\n \"vue-js-modal\": \"^2.0.1\",\n \"vue-toasted\": \"^1.1.28\",\n \"vue2-touch-events\": \"^3.2.2\",\n \"vuelidate\": \"^0.7.6\"\n },\n \"devDependencies\": {\n \"@nuxtjs/color-mode\": \"^2.1.1\",\n \"@nuxtjs/pwa\": \"^3.3.5\",\n \"@nuxtjs/tailwindcss\": \"^4.2.1\",\n \"autoprefixer\": \"^10.4.7\",\n \"sass\": \"~1.32.6\",\n \"sass-loader\": \"10.1.1\",\n \"tailwindcss-dir\": \"^4.0.0\"\n }\n}\n```\n\nThis is my nuxt.config.js:\n\n```\nimport i18nOptions from './plugins/i18n/options.js'\n\nexport default {\n // Target: https://go.nuxtjs.dev/config-target\n target: 'server',\n\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: 'test',\n htmlAttrs: {\n type: 'text/html; charset=utf-8'\n },\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { itemprop: 'name', content: 'test' },\n { property: 'og:type', content: 'website' },\n { property: 'og:site_name', content: 'test.ir' },\n { hid: 'description', name: 'description', content: '' },\n { name: 'theme-color', content: '#0048C5' },\n { name: 'format-detection', content: 'telephone=no' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\n '@/assets/css/main.css',\n ],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [\n '~/plugins/i18n/i18n.js',\n '~/plugins/hybridLink.js',\n '~plugins/vue-js-modal.js',\n '~plugins/vue2-touch-events.js',\n '~/plugins/vuelidate.js',\n '~/plugins/englishDigit.js',\n '~/plugins/decimalPlaces.js',\n '~/plugins/preventLeadingZeroes.js',\n { src: '~/plugins/toasted.js', mode: 'client' },\n { src: '~/plugins/vueMask.js', mode: 'client' },\n ],\n\n router: {\n middleware: ['i18n']\n },\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n '@nuxt/postcss8',\n '@nuxtjs/tailwindcss',\n '@nuxtjs/color-mode',\n '@nuxtjs/pwa'\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\n ['@nuxtjs/i18n', i18nOptions],\n '@nuxtjs/axios',\n 'cookie-universal-nuxt'\n ],\n\n colorMode: {\n preference: 'dark', // default value of $colorMode.preference\n fallback: '', // fallback value if not system preference found\n hid: 'nuxt-color-mode-script',\n globalName: '__NUXT_COLOR_MODE__',\n componentName: 'ColorScheme',\n classSuffix: '',\n storageKey: 'Theme'\n },\n\n loading: {\n color: '#0048C5',\n height: '4px',\n rtl: true,\n throttle: 0\n },\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {\n postcss: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n },\n },\n\n pwa: {\n manifest: {\n name: 'تیکاطب تفسیر آنلاین آزمایش',\n short_name: 'تیکاطب',\n lang: 'fa',\n display: 'standalone',\n theme_color: '#0048C5',\n background_color: '#ffffff',\n },\n icon: {\n fileName: 'testLogo.png',\n sizes: [64, 120, 144, 152, 192, 384, 512]\n }\n }\n}\n```\n\nand this is main.css:\n\n```\n@font-face {\n font-family: iranyekan;\n font-style: normal;\n font-weight: normal;\n src: url('~/static/fonts/farsi/eot/iranyekanwebregular.eot');\n src: url('~/static/fonts/farsi/eot/iranyekanwebregular.eot?#iefix') format('embedded-opentype'), /* IE6-8 */\n url('~/static/fonts/farsi/woff/iranyekanwebregular.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/\n url('~/static/fonts/farsi/woff2/iranyekanwebregular.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/\n url('~/static/fonts/farsi/ttf/iranyekanwebregular.ttf') format('truetype');\n}\n\n@font-face {\n font-family: iranyekan;\n font-style: normal;\n font-weight: 500;\n src: url('~/static/fonts/farsi/eot/iranyekanwebmedium.eot');\n src: url('~/static/fonts/farsi/eot/iranyekanwebmedium.eot?#iefix') format('embedded-opentype'), /* IE6-8 */\n url('~/static/fonts/farsi/woff/iranyekanwebmedium.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/\n url('~/static/fonts/farsi/woff2/iranyekanwebmedium.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/\n url('~/static/fonts/farsi/ttf/iranyekanwebmedium.ttf') format('truetype');\n}\n\n@font-face {\n font-family: iranyekan;\n font-style: normal;\n font-weight: bold;\n src: url('~/static/fonts/farsi/eot/iranyekanwebbold.eot');\n src: url('~/static/fonts/farsi/eot/iranyekanwebbold.eot?#iefix') format('embedded-opentype'), /* IE6-8 */\n url('~/static/fonts/farsi/woff/iranyekanwebbold.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/\n url('~/static/fonts/farsi/woff2/iranyekanwebbold.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/\n url('~/static/fonts/farsi/ttf/iranyekanwebbold.ttf') format('truetype');\n}\n\n@font-face {\n font-family: iranyekan;\n font-style: normal;\n font-weight: 800;\n src: url('~/static/fonts/farsi/eot/iranyekanwebextrabold.eot');\n src: url('~/static/fonts/farsi/eot/iranyekanwebextrabold.eot?#iefix') format('embedded-opentype'), /* IE6-8 */\n url('~/static/fonts/farsi/woff/iranyekanwebextrabold.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/\n url('~/static/fonts/farsi/woff2/iranyekanwebextrabold.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/\n url('~/static/fonts/farsi/ttf/iranyekanwebextrabold.ttf') format('truetype');\n}\n\n.page-enter-active,\n.page-leave-active {\n transition: all 250ms ease-out;\n}\n\n.page-enter,\n.page-leave-active {\n opacity: 0;\n transform-origin: 50% 50%;\n}\n\n@tailwind base;\n\n@layer base {\n html {\n font-family: iranyekan, serif !important;\n }\n\n input::-webkit-outer-spin-button,\n input::-webkit-inner-spin-button {\n -webkit-appearance: none;\n margin: 0;\n }\n\n input[type=number] {\n -moz-appearance: textfield;\n }\n}\n\n@tailwind components;\n\n@layer components {\n .text-title {\n @apply text-gray-dark dark:text-white\n }\n\n .hero-card {\n background: radial-gradient(circle farthest-side, #0e74b3 1%, #0048C5 75%);\n }\n\n .card-box {\n @apply bg-white dark:bg-black-800 rounded-10\n }\n\n .hero-button, .hero-button-reverse, .service-button {\n background-image: linear-gradient(to right, #044DCC, #257FE1);\n z-index: 1;\n @apply relative transition-all duration-300\n }\n\n .hero-button-reverse {\n background-image: linear-gradient(to right, #257FE1, #044DCC);\n }\n\n .service-button {\n background-image: linear-gradient(to bottom right, #257FE1, #0048C5);\n }\n\n .hero-button::before, .hero-button-reverse::before, .service-button::before {\n content: \"\";\n background: linear-gradient(to right, #FF6B00, #FF974B);\n z-index: -1;\n @apply absolute inset-0 transition-all duration-300 opacity-0 rounded-12\n }\n\n .hero-button:hover {\n @apply translate-x-[20px]\n }\n\n .hero-button-reverse:hover {\n @apply translate-x-[-20px]\n }\n\n .service-button:hover {\n @apply translate-y-[-8px]\n }\n\n .hero-button:hover::before, .hero-button-reverse:hover::before, .service-button:hover::before {\n @apply opacity-100\n }\n\n .custom-input {\n @apply relative\n }\n\n .custom-input label {\n @apply absolute top-[-12px] rtl:right-[30px] ltr:left-[30px] text-title z-20 bg-white dark:bg-black-800 px-[4px] text-[16px]\n }\n\n .custom-input div {\n @apply bg-transparent border border-[0.6px] rounded-5 w-full\n }\n\n .custom-input div input {\n @apply bg-transparent text-title px-16 py-[13px] text-[14px] w-full outline-none\n }\n\n .red-dot {\n @apply bg-red w-[6px] h-[6px] rounded-full min-w-[6px]\n }\n\n .custom-radio {\n @apply flex items-center;\n }\n\n .custom-radio input[type=\"radio\"]:focus {\n @apply outline-none rounded-full;\n }\n\n .custom-radio input[type=\"radio\"] {\n @apply cursor-pointer w-16 h-16 min-w-[16px] relative appearance-none rounded-full mx-8;\n }\n\n .custom-radio input[type=\"radio\"]::before {\n content: '';\n border: 1px solid #7580A0;\n @apply absolute inset-0 rounded-full;\n\n }\n\n .custom-radio input[type=\"radio\"]:focus::before {\n @apply shadow-none;\n }\n\n .custom-radio input[type=\"radio\"]:checked::before {\n border: 5px solid;\n @apply border-[#1F2434] dark:border-[#ffffff];\n }\n\n .custom-radio label {\n @layer text-title;\n @apply text-[14px] mb-0 align-middle text-center self-center cursor-pointer select-none;\n }\n\n .btn-primary {\n @apply flex items-center justify-center bg-primary-dark rounded-5 w-full text-white font-bold text-[16px] py-[10px] transition-all duration-200 hover:bg-[#FF6B00]\n }\n\n .btn-secondary {\n @apply flex items-center justify-center bg-gray-dark rounded-5 w-full text-white font-bold text-[16px] py-[10px] transition-all duration-200 hover:bg-gray-light\n }\n}\n\n@tailwind utilities;\n\n@layer utilities {\n .dir-rtl {\n direction: rtl !important;\n }\n\n .dir-ltr {\n direction: ltr !important;\n }\n}\n```\n\n**Please give me a hint. Thanks!**\n\n========================================\n\nCode:\n```text\nyarn build\n```\n\n```text\nERROR in ./assets/css/main.css (./node_modules/@nuxt/postcss8/node_modules/css-loader/dist/cjs.js??ref--3-oneOf-1-1!./node_modules/@nuxt/postcss8/node_modules/postcss-loader/dist/cjs.js??ref--3-oneOf-1-2!./assets/css/main.css)\nModule build failed (from ./node_modules/@nuxt/postcss8/node_modules/css-loader/dist/cjs.js):\nError: Can't resolve '~/static/fonts/farsi/eot/iranyekanwebregular.eot' in '/Users/mohammadamin/WebstormProjects/test/assets/css'\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/Resolver.js:209:21\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/Resolver.js:285:5\n at eval (eval at create (/Users/mohammadamin/WebstormProjects/test/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:15:1)\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js:44:7\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/Resolver.js:285:5\n at eval (eval at create (/Users/mohammadamin/WebstormProjects/test/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:15:1)\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/Resolver.js:285:5\n at eval (eval at create (/Users/mohammadamin/WebstormProjects/test/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:27:1)\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js:67:43\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/Resolver.js:285:5\n at eval (eval at create (/Users/mohammadamin/WebstormProjects/test/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:672:1)\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/AliasPlugin.js:67:43\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/Resolver.js:285:5\n at eval (eval at create (/Users/mohammadamin/WebstormProjects/test/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:15:1)\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js:44:7\n at /Users/mohammadamin/WebstormProjects/test/node_modules/enhanced-resolve/lib/Resolver.js:285:5\n @ ./assets/css/main.css 4:14-217\n @ ./.nuxt/App.js\n @ ./.nuxt/index.js\n @ ./.nuxt/client.js\n @ multi ./node_modules/@nuxt/components/lib/installComponents.js ./.nuxt/client.js\n```\n\n```text\n{\n \"name\": \"test\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"@nuxt/postcss8\": \"^1.1.3\",\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/i18n\": \"^7.2.0\",\n \"cookie-universal-nuxt\": \"^2.1.5\",\n \"core-js\": \"^3.15.1\",\n \"jalali-moment\": \"^3.3.11\",\n \"nuxt\": \"^2.15.7\",\n \"v-mask\": \"^2.3.0\",\n \"vue-js-modal\": \"^2.0.1\",\n \"vue-toasted\": \"^1.1.28\",\n \"vue2-touch-events\": \"^3.2.2\",\n \"vuelidate\": \"^0.7.6\"\n },\n \"devDependencies\": {\n \"@nuxtjs/color-mode\": \"^2.1.1\",\n \"@nuxtjs/pwa\": \"^3.3.5\",\n \"@nuxtjs/tailwindcss\": \"^4.2.1\",\n \"autoprefixer\": \"^10.4.7\",\n \"sass\": \"~1.32.6\",\n \"sass-loader\": \"10.1.1\",\n \"tailwindcss-dir\": \"^4.0.0\"\n }\n}\n```\n\n```text\nimport i18nOptions from './plugins/i18n/options.js'\n\nexport default {\n // Target: https://go.nuxtjs.dev/config-target\n target: 'server',\n\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: 'test',\n htmlAttrs: {\n type: 'text/html; charset=utf-8'\n },\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { itemprop: 'name', content: 'test' },\n { property: 'og:type', content: 'website' },\n { property: 'og:site_name', content: 'test.ir' },\n { hid: 'description', name: 'description', content: '' },\n { name: 'theme-color', content: '#0048C5' },\n { name: 'format-detection', content: 'telephone=no' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\n '@/assets/css/main.css',\n ],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [\n '~/plugins/i18n/i18n.js',\n '~/plugins/hybridLink.js',\n '~plugins/vue-js-modal.js',\n '~plugins/vue2-touch-events.js',\n '~/plugins/vuelidate.js',\n '~/plugins/englishDigit.js',\n '~/plugins/decimalPlaces.js',\n '~/plugins/preventLeadingZeroes.js',\n { src: '~/plugins/toasted.js', mode: 'client' },\n { src: '~/plugins/vueMask.js', mode: 'client' },\n ],\n\n router: {\n middleware: ['i18n']\n },\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n '@nuxt/postcss8',\n '@nuxtjs/tailwindcss',\n '@nuxtjs/color-mode',\n '@nuxtjs/pwa'\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\n ['@nuxtjs/i18n', i18nOptions],\n '@nuxtjs/axios',\n 'cookie-universal-nuxt'\n ],\n\n colorMode: {\n preference: 'dark', // default value of $colorMode.preference\n fallback: '', // fallback value if not system preference found\n hid: 'nuxt-color-mode-script',\n globalName: '__NUXT_COLOR_MODE__',\n componentName: 'ColorScheme',\n classSuffix: '',\n storageKey: 'Theme'\n },\n\n loading: {\n color: '#0048C5',\n height: '4px',\n rtl: true,\n throttle: 0\n },\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {\n postcss: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n },\n },\n\n pwa: {\n manifest: {\n name: 'تیکاطب تفسیر آنلاین آزمایش',\n short_name: 'تیکاطب',\n lang: 'fa',\n display: 'standalone',\n theme_color: '#0048C5',\n background_color: '#ffffff',\n },\n icon: {\n fileName: 'testLogo.png',\n sizes: [64, 120, 144, 152, 192, 384, 512]\n }\n }\n}\n```\n\n```text\n@font-face {\n font-family: iranyekan;\n font-style: normal;\n font-weight: normal;\n src: url('~/static/fonts/farsi/eot/iranyekanwebregular.eot');\n src: url('~/static/fonts/farsi/eot/iranyekanwebregular.eot?#iefix') format('embedded-opentype'), /* IE6-8 */\n url('~/static/fonts/farsi/woff/iranyekanwebregular.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/\n url('~/static/fonts/farsi/woff2/iranyekanwebregular.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/\n url('~/static/fonts/farsi/ttf/iranyekanwebregular.ttf') format('truetype');\n}\n\n@font-face {\n font-family: iranyekan;\n font-style: normal;\n font-weight: 500;\n src: url('~/static/fonts/farsi/eot/iranyekanwebmedium.eot');\n src: url('~/static/fonts/farsi/eot/iranyekanwebmedium.eot?#iefix') format('embedded-opentype'), /* IE6-8 */\n url('~/static/fonts/farsi/woff/iranyekanwebmedium.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/\n url('~/static/fonts/farsi/woff2/iranyekanwebmedium.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/\n url('~/static/fonts/farsi/ttf/iranyekanwebmedium.ttf') format('truetype');\n}\n\n@font-face {\n font-family: iranyekan;\n font-style: normal;\n font-weight: bold;\n src: url('~/static/fonts/farsi/eot/iranyekanwebbold.eot');\n src: url('~/static/fonts/farsi/eot/iranyekanwebbold.eot?#iefix') format('embedded-opentype'), /* IE6-8 */\n url('~/static/fonts/farsi/woff/iranyekanwebbold.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/\n url('~/static/fonts/farsi/woff2/iranyekanwebbold.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/\n url('~/static/fonts/farsi/ttf/iranyekanwebbold.ttf') format('truetype');\n}\n\n@font-face {\n font-family: iranyekan;\n font-style: normal;\n font-weight: 800;\n src: url('~/static/fonts/farsi/eot/iranyekanwebextrabold.eot');\n src: url('~/static/fonts/farsi/eot/iranyekanwebextrabold.eot?#iefix') format('embedded-opentype'), /* IE6-8 */\n url('~/static/fonts/farsi/woff/iranyekanwebextrabold.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/\n url('~/static/fonts/farsi/woff2/iranyekanwebextrabold.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/\n url('~/static/fonts/farsi/ttf/iranyekanwebextrabold.ttf') format('truetype');\n}\n\n.page-enter-active,\n.page-leave-active {\n transition: all 250ms ease-out;\n}\n\n.page-enter,\n.page-leave-active {\n opacity: 0;\n transform-origin: 50% 50%;\n}\n\n@tailwind base;\n\n@layer base {\n html {\n font-family: iranyekan, serif !important;\n }\n\n input::-webkit-outer-spin-button,\n input::-webkit-inner-spin-button {\n -webkit-appearance: none;\n margin: 0;\n }\n\n input[type=number] {\n -moz-appearance: textfield;\n }\n}\n\n@tailwind components;\n\n@layer components {\n .text-title {\n @apply text-gray-dark dark:text-white\n }\n\n .hero-card {\n background: radial-gradient(circle farthest-side, #0e74b3 1%, #0048C5 75%);\n }\n\n .card-box {\n @apply bg-white dark:bg-black-800 rounded-10\n }\n\n .hero-button, .hero-button-reverse, .service-button {\n background-image: linear-gradient(to right, #044DCC, #257FE1);\n z-index: 1;\n @apply relative transition-all duration-300\n }\n\n .hero-button-reverse {\n background-image: linear-gradient(to right, #257FE1, #044DCC);\n }\n\n .service-button {\n background-image: linear-gradient(to bottom right, #257FE1, #0048C5);\n }\n\n .hero-button::before, .hero-button-reverse::before, .service-button::before {\n content: \"\";\n background: linear-gradient(to right, #FF6B00, #FF974B);\n z-index: -1;\n @apply absolute inset-0 transition-all duration-300 opacity-0 rounded-12\n }\n\n .hero-button:hover {\n @apply translate-x-[20px]\n }\n\n .hero-button-reverse:hover {\n @apply translate-x-[-20px]\n }\n\n .service-button:hover {\n @apply translate-y-[-8px]\n }\n\n .hero-button:hover::before, .hero-button-reverse:hover::before, .service-button:hover::before {\n @apply opacity-100\n }\n\n .custom-input {\n @apply relative\n }\n\n .custom-input label {\n @apply absolute top-[-12px] rtl:right-[30px] ltr:left-[30px] text-title z-20 bg-white dark:bg-black-800 px-[4px] text-[16px]\n }\n\n .custom-input div {\n @apply bg-transparent border border-[0.6px] rounded-5 w-full\n }\n\n .custom-input div input {\n @apply bg-transparent text-title px-16 py-[13px] text-[14px] w-full outline-none\n }\n\n .red-dot {\n @apply bg-red w-[6px] h-[6px] rounded-full min-w-[6px]\n }\n\n .custom-radio {\n @apply flex items-center;\n }\n\n .custom-radio input[type=\"radio\"]:focus {\n @apply outline-none rounded-full;\n }\n\n .custom-radio input[type=\"radio\"] {\n @apply cursor-pointer w-16 h-16 min-w-[16px] relative appearance-none rounded-full mx-8;\n }\n\n .custom-radio input[type=\"radio\"]::before {\n content: '';\n border: 1px solid #7580A0;\n @apply absolute inset-0 rounded-full;\n\n }\n\n .custom-radio input[type=\"radio\"]:focus::before {\n @apply shadow-none;\n }\n\n .custom-radio input[type=\"radio\"]:checked::before {\n border: 5px solid;\n @apply border-[#1F2434] dark:border-[#ffffff];\n }\n\n .custom-radio label {\n @layer text-title;\n @apply text-[14px] mb-0 align-middle text-center self-center cursor-pointer select-none;\n }\n\n .btn-primary {\n @apply flex items-center justify-center bg-primary-dark rounded-5 w-full text-white font-bold text-[16px] py-[10px] transition-all duration-200 hover:bg-[#FF6B00]\n }\n\n .btn-secondary {\n @apply flex items-center justify-center bg-gray-dark rounded-5 w-full text-white font-bold text-[16px] py-[10px] transition-all duration-200 hover:bg-gray-light\n }\n}\n\n@tailwind utilities;\n\n@layer utilities {\n .dir-rtl {\n direction: rtl !important;\n }\n\n .dir-ltr {\n direction: ltr !important;\n }\n}\n```\n\n========================================\n\nComments:\n- Could you also please the place where you use the `font-face` + your `nuxt.config.js` file?\n- The `Error: Can't resolve '~/static/fonts/farsi/eot/iranyekanwebregular.eot' in '/Users/mohammadamin/WebstormProjects/TicaTeb/assets/css'` indicates that you may have an incorrect path regarding your file.\n- I use font-face in main.css.\n- nuxt.config.js added to my question.\n- What about my second comment? Mind sharing the CSS file too?\n- No problem. I added to the question.\n- node-sass is the old and inefficient version anyway.\n- Yeah. I agree with you and now I change it to sass.\n- But why it can not resolve a CSS @font-face URL !?","metadata":{"transformedAt":"2026-08-18T18:33:07.899Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":800,"estimatedTokens":6120}}868{"id":"stack-74143553","source":"stackoverflow","questionId":74143553,"title":"Nuxt3 Pass data from app.vue to a layout or page","tags":["vue.js","nuxt.js","vuejs3","nuxt3.js","vue-props"],"text":"Title: Nuxt3 Pass data from app.vue to a layout or page\nTags: vue.js, nuxt.js, vuejs3, nuxt3.js, vue-props\nSource: Stack Overflow\n\nQuestion:\nIn app.vue I have\n\n```\n\n \n \n \n \n \n \n \n\nimport { AppSetup } from './utils/app';\nimport { ITheme } from './utils/theme';\nAppSetup()\nconst theme = useState('theme.current')\n\n```\n\nThis is what I see in the Vue devtools\nhttps://i.sstatic.net/a1ghM.png\n\nAnd Even that the `` is filled with the `theme` value. If I try to:\n\n```\n\n \n \n \n \n \n \n \n\nimport { AppSetup } from './utils/app';\nimport { ITheme } from './utils/theme';\nAppSetup()\nconst theme = useState('theme.current')\n\n```\n\nThen the `theme` property is not visible from the `layouts/default.vue` (there's only that one) or the `pages/index.vue`\n\nHow can I access to that prop? If not, what's the easier way? I tried in `pages/index.vue` to add the same code\n\n```\n\nimport { AppSetup } from '../utils/app';\nimport { ITheme } from '../utils/theme';\nAppSetup()\nconst theme = useState('theme.current')\n\n```\n\nAnd this works but feels like kinda repetitive (and this doesn't work in the `layouts/default.vue`\n\nThis is my `layouts/default.vue`\n\n```\n\n \n \n \n \n \n\nexport default {\n layout: 'default'\n}\n\n```\n\nAnd this is what I see in the devtools (the value exist)\nhttps://i.sstatic.net/1E4z4.png\n\nAnd this is my `pages/index.vue`\n\n```\n\n \n \n\n### Welcome to Nuxt3 for {{ brand }}\n\n \n\n```\n\nAnd this is what I see in the devtools (the value exists)\nhttps://i.sstatic.net/ELBGJ.png\n\n========================================\n\nCode:\n```html\n<template>\n <Html :class=\"theme\">\n <Body>\n <NuxtLayout>\n <NuxtPage/>\n </NuxtLayout>\n </Body>\n </Html>\n</template>\n\n<script lang=\"ts\" setup>\nimport { AppSetup } from './utils/app';\nimport { ITheme } from './utils/theme';\nAppSetup()\nconst theme = useState<ITheme>('theme.current')\n</script>\n```\n\n```html\n<template>\n <Html :class=\"theme\">\n <Body>\n <NuxtLayout :theme=\"theme\">\n <NuxtPage :theme=\"theme\" />\n </NuxtLayout>\n </Body>\n </Html>\n</template>\n\n<script lang=\"ts\" setup>\nimport { AppSetup } from './utils/app';\nimport { ITheme } from './utils/theme';\nAppSetup()\nconst theme = useState<ITheme>('theme.current')\n</script>\n```\n\n```html\n<script lang=\"ts\" setup>\nimport { AppSetup } from '../utils/app';\nimport { ITheme } from '../utils/theme';\nAppSetup()\nconst theme = useState<ITheme>('theme.current')\n</script>\n```\n\n```html\n<template>\n <div>\n <Header />\n <slot />\n <Footer />\n </div>\n</template>\n\n<script>\nexport default {\n layout: 'default'\n}\n</script>\n```\n\n```html\n<template>\n <main>\n <h1>Welcome to <span class=\"text-gradient\">Nuxt3</span> for {{ brand }}</h1>\n </main>\n</template>\n```\n\n```text\n<Html :class=\"theme\">\n```\n\n```text\ntheme\n```\n\n```text\ntheme\n```\n\n```text\nlayouts/default.vue\n```\n\n```text\npages/index.vue\n```\n\n```text\npages/index.vue\n```\n\n```text\nlayouts/default.vue\n```\n\n```text\nlayouts/default.vue\n```\n\n```text\npages/index.vue\n```\n\n```html\n<script setup>\nconst props = defineProps({\n theme: String\n})\n</script>\n```\n\n```text\nindex.vue\n```\n\n========================================\n\nComments:\n- You're using `layout` or `layouts`? Should be the second one. Double check with your Vue devtools to see if you have what you expect there. Because it should work well so far. Double check what your have in your `theme` variable too.\n- oh, that was a typo. Yes is in `layouts/default.vue`, `theme` has a value ( it fills the `html[class]` but in child components/pages is not visible\n- What do you see in your Vue devtools? What is inside that theme? Is it supposed to be a global token in the same way as Tailwind? If so, it's even probably wiser to just have it as a global state in your app since it will be used everywhere. Either with Pinia or even with `provide/inject`'s pattern. Having it passed one by one will be cumbersome and quite time consuming.\n- Updated the question with an screenshot of what I see in the devtools selecting the app\n- `'bar'` is indeed in the `prop`. What about the other places? Does it appear in the devtools? Do you have it as a prop? Did you used `defineProps` there?\n- Updated the answer of what I see selecting the layout or the index page. Also tried to install pinia (this prop think is my plan b like as you said would be too repetitive but i'm just doing a POC) but I get this error `npm --save-dev install pinia npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: undefined@undefined npm ERR! Found: vue@3.2.41` any idea?\n- You have it as you can see. Now use, `defineProps` to receive it as a prop as explained in Vue's doc. Not sure about the NPM issue since it's NPM eh. Give a try to `npm i pinia -f`. Otherwise try to see if there is some sneaky package in your `package.json`. Or you could give yarn/pnpm a try to have a proper error (npm is quite bad at that as you can see).\n- thank you very much @kissu I successfully was able to instal pinia using yarn so I will your suggestion. I guess I'll leave this question open for now\n- So far, everything works great. You have Pinia, you have your state passed down properly. Everything is working well tbh. I should probably post an answer haha.\n- Yes but the question is about the Props, if I have the time I'll try to fix the code and provide an answer :) thanks again","metadata":{"transformedAt":"2026-08-18T18:33:07.899Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":231,"estimatedTokens":1328}}869{"id":"stack-70074265","source":"stackoverflow","questionId":70074265,"title":"Uncaught TypeError: Cannot set properties of undefined (setting 'isSubcon')","tags":["javascript","firebase","vue.js","nuxt.js","vuetify.js"],"text":"Title: Uncaught TypeError: Cannot set properties of undefined (setting 'isSubcon')\nTags: javascript, firebase, vue.js, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nneed some help here.\n\nI want my navigation drawer to display different contents based on the user types/roles of those who logged in.\n\nBut I encounter this error (\"Uncaught TypeError: Cannot set properties of undefined (setting 'isSubcon'\"). and my navigation drawer not displaying anything.\n\nmy `template`\n\n```\n\n //content of drawer if user that logged in is a \"Subcon\"\n\n //content of drawer if user that logged in is a \"WPC\"\n\n //content of drawer if user that logged in is a \"BWG\"\n\n```\n\nmy `script`\n\n```\ndata: () => ({\n isSubcon: false,\n isWPC: false,\n isBWG: false,\n}),\n\n// I think below is where the problem occurs.\ncreated() {\n firebase\n .auth()\n .onAuthStateChanged((userAuth) => {\n if (userAuth) {\n firebase\n .auth()\n .currentUser.getIdTokenResult()\n .then(function ({\n claims,\n }) {\n if (claims.customer) {\n this.isSubcon = true; //HERE WHERE THE PROBLEM OCCURS (i think)\n } else if (claims.admin) {\n this.isWPC =true; //THIS ALSO\n } else if (claims.subscriber) {\n this.isBWG = true; //AND THIS ALSO\n }\n }\n )\n }\n });\n },\n```\n\nI'm using Firebase Custom Claims to log in and Nuxt (mode: SPA) with Vuetify for the UI. So how can I remove the error, so that I can display the content to my nav drawer?\n\nThank you in advance :))\n\n========================================\n\nCode:\n```text\n<v-list v-if=\"isSubcon\">\n //content of drawer if user that logged in is a \"Subcon\"\n</v-list>\n\n<v-list v-if=\"isWPC\">\n //content of drawer if user that logged in is a \"WPC\"\n</v-list>\n\n<v-list v-if=\"isBWG\">\n //content of drawer if user that logged in is a \"BWG\"\n</v-list>\n```\n\n```text\ndata: () => ({\n isSubcon: false,\n isWPC: false,\n isBWG: false,\n}),\n\n// I think below is where the problem occurs.\ncreated() {\n firebase\n .auth()\n .onAuthStateChanged((userAuth) => {\n if (userAuth) {\n firebase\n .auth()\n .currentUser.getIdTokenResult()\n .then(function ({\n claims,\n }) {\n if (claims.customer) {\n this.isSubcon = true; //HERE WHERE THE PROBLEM OCCURS (i think)\n } else if (claims.admin) {\n this.isWPC =true; //THIS ALSO\n } else if (claims.subscriber) {\n this.isBWG = true; //AND THIS ALSO\n }\n }\n )\n }\n });\n },\n```\n\n```text\ntemplate\n```\n\n```text\nscript\n```\n\n```js\nmyObject.created();\n```\n\n```js\ncreated() {\n let that = this;\n firebase\n ...\n .then(function ({ claims }) {\n if (claims.customer) {\n that.isSubcon = true; //HERE WHERE THE PROBLEM OCCURS (i think)\n } else if (claims.admin) {\n that.isWPC =true; //THIS ALSO\n } else if (claims.subscriber) {\n that.isBWG = true; //AND THIS ALSO\n }\n })\n}\n```\n\n```text\nthis\n```\n\n```text\ndata: () => ({ ... })\n```\n\n```text\ncreated()\n```\n\n========================================\n\nComments:\n- Does this answer your question? Why is 'this' undefined inside class method when using promises?\n- Supposedly but I'm not sure how to really implement it in my code haha. I put `var that = this;` above `if (claims.customer)` and changed `this.isSubcon = true;` to `that.isSubcon = true;` but it still pop out the same error. maybe you can show me in codes how to solve it, please?\n- oh I also do `.then(this.isSubcon = true;)` and remove the if-else statement below it just to test, it actually works. (so by doing that one is actually related to article that you gave). But how to do it inside my if-else statement and turn my `v-if` from `false` to `true`.","metadata":{"transformedAt":"2026-08-18T18:33:07.899Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":159,"estimatedTokens":988}}870{"id":"stack-71195369","source":"stackoverflow","questionId":71195369,"title":"Maintain grid system across `default.vue` and `index.vue` in vuetify","tags":["css","vue.js","nuxt.js","vuetify.js","css-grid"],"text":"Title: Maintain grid system across `default.vue` and `index.vue` in vuetify\nTags: css, vue.js, nuxt.js, vuetify.js, css-grid\nSource: Stack Overflow\n\nQuestion:\nI am very new to vue, this probably is very basic question. I want a page with 3-col layout, where two columns should be in `default.vue` and the one column should be in a page, say `index.vue`. I have created everything in `default.vue` and it works fine but I can not maintain that when I move the content to `index.vue` file. Here is overview of what I have:\n\n```\n\n \n \n \n \n \n Navigation\n \n \n \n \n \n \n \n \n Card 1\n Card 2\n Card 3\n \n \n \n \n \n \n\n```\n\nHere, if I move the whole div including `col-8` to `index.vue` then `CompanyCard` moves to left near the `Navigation` and the main div goes below that. On the other had, if I just keep the line `` in `default.vue` and move the content (2 rows inside this) to `index.vue`. The `CompanyCard` remains at right, as it should but the middle column is blank and the content is below that. How do I maintain that 3-col format across `default.vue` and `index.vue` ?\n\nI am using `Nuxt` with `Vuetify`.\n\nThank you!\n\n========================================\n\nCode:\n```text\n<html>\n <body> \n <div class=\"row\">\n <div class=\"col-2\">\n <div class=\"row\">\n <div class=\"col\">\n Navigation\n </div>\n </div>\n </div>\n <div class=\"col-8\"> <!-- I need this div in index.vue -->\n <div class=\"row\">\n <div class=\"col\"><WelcomeText></WelcomeText></div>\n </div>\n <div class=\"row\">\n <div class=\"col\">Card 1</div>\n <div class=\"col\">Card 2</div>\n <div class=\"col\">Card 3</div>\n </div>\n </div>\n <div class=\"col-2\">\n <CompanyCard></CompanyCard>\n </div>\n </div>\n</body>\n</html>\n```\n\n```text\ndefault.vue\n```\n\n```text\nindex.vue\n```\n\n```text\ndefault.vue\n```\n\n```text\nindex.vue\n```\n\n```text\ncol-8\n```\n\n```text\nindex.vue\n```\n\n```text\nCompanyCard\n```\n\n```text\nNavigation\n```\n\n```text\n<div class=\"col-8\">\n```\n\n```text\ndefault.vue\n```\n\n```text\nindex.vue\n```\n\n```text\nCompanyCard\n```\n\n```text\ndefault.vue\n```\n\n```text\nindex.vue\n```\n\n```text\nNuxt\n```\n\n```text\nVuetify\n```\n\n```html\n<template>\n <div class=\"row\">\n <div class=\"col-2\">\n <div class=\"row\">\n <div class=\"col\"> Navigation </div>\n </div>\n </div>\n <div class=\"col-8\">\n <!-- I need this div in index.vue -->\n <Nuxt />\n <div class=\"row\">\n <div class=\"col\">Card 1</div>\n <div class=\"col\">Card 2</div>\n <div class=\"col\">Card 3</div>\n </div>\n </div>\n <div class=\"col-2\">\n <CompanyCard></CompanyCard>\n </div>\n </div>\n</template>\n```\n\n```html\n<template>\n <div class=\"row\">\n <div class=\"col\"><WelcomeText></WelcomeText></div>\n </div>\n</template>\n```\n\n```text\nNuxt\n```\n\n```text\n<Nuxt />\n```\n\n```text\ndefualt.vue\n```\n\n```text\ndefault.vue\n```\n\n```text\nindex.vue\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.899Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":24,"totalLines":188,"estimatedTokens":744}}871{"id":"stack-70175458","source":"stackoverflow","questionId":70175458,"title":"How to set scope(or role) of nuxt $auth.user?","tags":["vue.js","oauth-2.0","nuxt.js"],"text":"Title: How to set scope(or role) of nuxt $auth.user?\nTags: vue.js, oauth-2.0, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using nuxt-auth with google oauth2 config, here is my `nuxt.config.js` config:\n\n```\nauth: {\n scopeKey: 'scope',\n strategies: {\n google: {\n client_id: process.env.GOOGLE_KEY,\n codeChallengeMethod: '',\n scope: ['profile', 'email'],\n responseType: 'token id_token'\n }\n },\n redirect: {\n login: '/login',\n logout: '/logout',\n home: '/',\n callback: '/welcome'\n }\n},\nrouter: {\n middleware: ['auth']\n},\n```\n\nI use this code to login\n\n```\nthis.$auth.loginWith('google')\n```\n\nI want to setup a role for user (visit app database) after successful login, so I added this code to my **welcome.vue** (oauth2 callback page)\n\n```\n\nexport default {\n mounted () {\n const user = this.$auth.user\n user['scope'] = 'some_role_from_db'\n this.$auth.setUser(user)\n }\n}\n\n```\n\nbut this code is never called, because application is immediately redirected to the page that user has selected before visiting login page (**welcome.vue** html markup is shown for 1 sec).\n\nWhat is the correct way to set some attributes to this.$auth.user immediately after login? Is there some easy way to set role to user after OAUTH2 authentication?\n\n========================================\n\nTop Answer:\nuser roles must came from server and it wrong to define it from client side ,\nbut if that is importent you can do it like that :\n\n```\nthis.$auth.loginWith('google').then(() => {\n const user = this.$auth.user\n user['scope'] = 'some_role_from_db'\n this.$auth.setUser(user)\n})\n```\n\n========================================\n\nCode:\n```js\nauth: {\n scopeKey: 'scope',\n strategies: {\n google: {\n client_id: process.env.GOOGLE_KEY,\n codeChallengeMethod: '',\n scope: ['profile', 'email'],\n responseType: 'token id_token'\n }\n },\n redirect: {\n login: '/login',\n logout: '/logout',\n home: '/',\n callback: '/welcome'\n }\n},\nrouter: {\n middleware: ['auth']\n},\n```\n\n```js\nthis.$auth.loginWith('google')\n```\n\n```html\n<script>\nexport default {\n mounted () {\n const user = this.$auth.user\n user['scope'] = 'some_role_from_db'\n this.$auth.setUser(user)\n }\n}\n</script>\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nrewriteRedirects: false\n```\n\n```text\n<script>\nexport default {\n mounted () {\n const user = this.$auth.user\n user['scope'] = 'some_role_from_db'\n this.$auth.setUser(user)\n }\n}\n</script>\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nhome\n```\n\n```text\nthis.$auth.loginWith('google').then(() => {\n const user = this.$auth.user\n user['scope'] = 'some_role_from_db'\n this.$auth.setUser(user)\n})\n```\n\n========================================\n\nComments:\n- What causes redirection in your app ? Is it automatic or manual redirection to last page ? @BogdanTimofeev\n- @Batuhan it is automatic redirect to the page user has selected before logging in, I am using 'auth' middleware, edited the post\n- i.e I go to localhost:3000/apps page, it redirects me to localhost:3000/login, I log in with Google, it redirects me to localhost:3000/welcome and then immediately back again to localhost:3000/apps - but now this page is shown because I am authorized\n- I have tried this, but then() callback is never executed because page changes after I select my google account\n- 'some_role_from_db' should come from server, it is constant just for example\n- ok then get it with your user object\n- user object comes from Google, It has no information about roles in my particular application, roles should be stored in my app database\n- How do you set scope from server?","metadata":{"transformedAt":"2026-08-18T18:33:07.899Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":157,"estimatedTokens":897}}872{"id":"stack-69544212","source":"stackoverflow","questionId":69544212,"title":"How to configure production URL for Firebase callable function in nuxt app?","tags":["firebase","google-cloud-functions","nuxt.js","nuxtjs2"],"text":"Title: How to configure production URL for Firebase callable function in nuxt app?\nTags: firebase, google-cloud-functions, nuxt.js, nuxtjs2\nSource: Stack Overflow\n\nQuestion:\nI have a `nuxt` app uploaded to Firebase (served as cloud function). I have also a callable function that I'm trying to call from the app. The problem is that it tries to call `localhost` url instead of the production one.\n\nMy Firebase setup in `nuxt.config.js` looks like this:\n\n```\nmodule.exports = {\n env: {\n functionsURL: process.env.NUXT_ENV_FUNCTIONS === 'local' ? \"http://localhost:5001/turniejomat/us-central1\" : 'https://us-central1-turniejomat.cloudfunctions.net', // I would expect this to be applied\n },\n modules: [\n [\n '@nuxtjs/firebase',\n {\n config: {\n // app config\n },\n services: {\n functions: {\n location: 'us-central1',\n emulatorPort: 5001,\n }\n }\n }\n ]\n ],\n}\n```\n\nThe firebase.nuxt.org documentation mentions only emulator configuration, but not production.\n\nI'm calling the function like this:\n\n```\nconst signUp = await this.$fire.functions.httpsCallable(\"signup\")(configObject)\n```\n\nHow do I make the function to use proper url in production?\n\n**EDIT:**\n\nThis is `package.json` setting:\n\n```\n\"scripts\": {\n \"dev\": \"SET \\\"NUXT_ENV_FUNCTIONS=local\\\" & nuxt\",\n \"build\": \"SET \\\"NUXT_ENV_FUNCTIONS=fire\\\" & nuxt build\",\n }\n```\n\n**EDIT 2:**\n\nApparently the `env.functionsURL` is applied properly, as the app code uses this variable directly for other purposes and it works correctly! It is the `callable functions` only that for some reason don't receive the relevant production url to be called. At the same time the only places in the code where 5001 port appears are:\n\n- `nuxt.config.js / env` setting\n\n- `nuxt.config.js / modules / services / functions / emulatorPort` setting\n\n- `service.functions.js` module in `nuxt/firebase` folder which is added automatically (by firebase.nuxtjs I guess?).\n\nThe module looks like this:\n\n```\nexport default async function (session) {\n await import('firebase/functions')\n const functionsService = session.functions('us-central1')\n functionsService.useFunctionsEmulator('http://localhost:5001')\n return functionsService\n}\n```\n\nSo maybe for some reason the `callable function` thinks it should still use emulator settings? How could I prevent it?\n\nThe only place where the module is called is the `nuxt/firebase/index.js`, like this:\n\n```\nif (process.server) {\n servicePromises = [\n authService(session, firebase, ctx, inject),\n firestoreService(session, firebase, ctx, inject),\n functionsService(session, firebase, ctx, inject),\n ]\n }\n\n if (process.client) {\n servicePromises = [\n authService(session, firebase, ctx, inject),\n firestoreService(session, firebase, ctx, inject),\n functionsService(session, firebase, ctx, inject),\n ]\n }\n```\n\nWhich seems that indeed regardless of the environment the same settings are indeed applied by the Firebase's native code. I could modify the `functionsService` code, but it does not seem like an optimal solution as Firebase might overwrite it at some point, like during build or update. Or it could have been that these 'native' files were generated only at the beginning and did not update despite potential changes made in the config (which was incorrect, but now is correct).\n\nHow could I enforce changes to these Firebase's files distinguishing prod and dev environments and make them safely persist? Probably `nuxt.config.js / modules / services / functions /` should be configured differently, but how?\n\n========================================\n\nTop Answer:\nUse the `publicRuntimeConfig` in `nuxt.config.js`, in order to configure the environment:\n\n```\nexport default {\n publicRuntimeConfig: {\n baseURL: process.env.BASE_URL || 'https://us-central1-turniejomat.cloudfunctions.net'\n }\n}\n```\n\nSubsequently the `dev` script would be:\n\n```\n\"dev\": \"SET \\\"BASE_URL=http://localhost:5001/turniejomat/us-central1\\\" & nuxt\"\n```\n\nAlways substitute production with development values, not the other way around.\n\n========================================\n\nCode:\n```js\nmodule.exports = {\n env: {\n functionsURL: process.env.NUXT_ENV_FUNCTIONS === 'local' ? \"http://localhost:5001/turniejomat/us-central1\" : 'https://us-central1-turniejomat.cloudfunctions.net', // I would expect this to be applied\n },\n modules: [\n [\n '@nuxtjs/firebase',\n {\n config: {\n // app config\n },\n services: {\n functions: {\n location: 'us-central1',\n emulatorPort: 5001,\n }\n }\n }\n ]\n ],\n}\n```\n\n```js\nconst signUp = await this.$fire.functions.httpsCallable(\"signup\")(configObject)\n```\n\n```text\n\"scripts\": {\n \"dev\": \"SET \\\"NUXT_ENV_FUNCTIONS=local\\\" & nuxt\",\n \"build\": \"SET \\\"NUXT_ENV_FUNCTIONS=fire\\\" & nuxt build\",\n }\n```\n\n```text\nexport default async function (session) {\n await import('firebase/functions')\n const functionsService = session.functions('us-central1')\n functionsService.useFunctionsEmulator('http://localhost:5001')\n return functionsService\n}\n```\n\n```text\nif (process.server) {\n servicePromises = [\n authService(session, firebase, ctx, inject),\n firestoreService(session, firebase, ctx, inject),\n functionsService(session, firebase, ctx, inject),\n ]\n }\n\n if (process.client) {\n servicePromises = [\n authService(session, firebase, ctx, inject),\n firestoreService(session, firebase, ctx, inject),\n functionsService(session, firebase, ctx, inject),\n ]\n }\n```\n\n```text\nnuxt\n```\n\n```text\nlocalhost\n```\n\n```text\nnuxt.config.js\n```\n\n```text\npackage.json\n```\n\n```text\nenv.functionsURL\n```\n\n```text\ncallable functions\n```\n\n```text\nnuxt.config.js / env\n```\n\n```text\nnuxt.config.js / modules / services / functions / emulatorPort\n```\n\n```text\nservice.functions.js\n```\n\n```text\nnuxt/firebase\n```\n\n```text\ncallable function\n```\n\n```text\nnuxt/firebase/index.js\n```\n\n```text\nfunctionsService\n```\n\n```text\nnuxt.config.js / modules / services / functions /\n```\n\n```text\nfunctions: {\n location: 'us-central1',\n emulatorPort: process.env.NUXT_ENV_FUNCTIONS === 'local' ? 5001 : undefined, \n}\n```\n\n```text\nfunctions.emulatorPort\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nundefined\n```\n\n```text\nexport default {\n publicRuntimeConfig: {\n baseURL: process.env.BASE_URL || 'https://us-central1-turniejomat.cloudfunctions.net'\n }\n}\n```\n\n```text\n\"dev\": \"SET \\\"BASE_URL=http://localhost:5001/turniejomat/us-central1\\\" & nuxt\"\n```\n\n```text\npublicRuntimeConfig\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ndev\n```\n\n```text\nconfig: {\n // REQUIRED: Official config for firebase.initializeApp(config):\n apiKey: '<apiKey>',\n authDomain: '<authDomain>',\n projectId: '<projectId>',\n storageBucket: '<storageBucket>',\n messagingSenderId: '<messagingSenderId>',\n appId: '<appId>',\n measurementId: '<measurementId>'\n}\n```\n\n```text\nservices: {\n auth: true,\n firestore: true,\n functions: true,\n storage: true,\n database: true,\n messaging: true,\n performance: true,\n analytics: true,\n remoteConfig: true\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nhttps://console.firebase.google.com/project/<your-project-id>/overview\n```\n\n```text\nNODE_ENV\n```\n\n========================================\n\nComments:\n- Can't you do the actual setup into a Nuxt plugin and interpolate the URL there somehow?\n- This is my first app in Nuxt and first using Firebase. I don't know how would I transform nuxt settings into a plugin and how would that help me with the problem. I don't see a plugin-config mentioned in the docs. I expected that either I have some error in the setup or some value is missing. I am using Firebase's SDK to call the function, so I expect it must get the url from somewhere and I would expect that to be `env.functionsURL` setting. But it does not work. So either it's not the right place or Firebase thinks that prod is 'local'. However, the build script sets this variable to \"fire\".\n- Why make a conditional here? Add your variable directly here. Then, locally in your `.env` you can set localhost, while on production you could set the real URL.\n- Ok, I did some further tests and hard set the the `env.functionsURL` in `nuxt.config.js` to production value only. Still the localhost was applied for the SDK callable function (I don't know from where as it aws the ONLY place in my project where I had the localhost specified). HOWEVER, in the app code itself I do use the `env.functionsURL` and it is set properly, because some other code uses it ant it works! Is it possible that for the callable funct it is necessary to use some CLI command like firebase functions:config:set myCallableFunction.runtime_api_url=\"function/url\"?\n- Not sure how you can use `baseURL` since it's configuration is directly done in `nuxt.config.js`' `module` key and not a plugin.\n- What do you mean? It doesn't matter how you call the variable and `$config` is know application-wide.\n- `publicRuntimeConfig` variables cannot be directly used in `nuxt.config.js` keys. Those are aimed towards places with Nuxt context.\n- This is directly copied from the documentation, just click the link above. You could as well use `.env`\n- It doesn't say anything regarding my previous comment. But yeah, using `process.env` is a viable solution.\n- @MartinZeitler Unfortunatelly it didn't work. Trying configurations I even hard set the `env.functionsURL` in `nuxt.config.js` to production value only. Still the `localhost` was applied for the SDK callable function. HOWEVER, in the app code itself I do use the `env.functionsURL` and it is set properly! Is it possible that for the callable funct it is necessary to use some CLI command like `firebase functions:config:set myCallableFunction.runtime_api_url=\"https://function/url\"`? I have set such config for the app function, but I dont want to break something running this for callable funct.\n- @kissu I have updated the question with relevant info. Maybe it will help formulate an answer?\n- @MartinZeitler I have updated the question with relevant info. Maybe it will help formulate an answer?\n- I have the `config` and `services` defined in the module section of `nuxt.config.js` which is shown in my snippet. I have seen the documentation, but it lacks information that I need. The firebase.nuxtjs docs show only the settings that I do have already (setting up emulator host and port), which work incorrectly (they seem to apply emulator settings also in production). I have updated my question with additional information which maybe will help formulate a solution?\n- Does the edit helped?\n- Not really. I found a solution myself - I wrote an anwer already. The `emulatorPort` needed to be defined conditionally. But as you were in the right ballpark and the bounty will expire I will grant you the bounty so it doesnt go to waste :), but I will not accept the answer. Please consider upvoting my question. :)","metadata":{"transformedAt":"2026-08-18T18:33:07.899Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":33,"totalLines":343,"estimatedTokens":2748}}873{"id":"stack-69811607","source":"stackoverflow","questionId":69811607,"title":"Vue-konva running into error: Must use import to load ES Module","tags":["javascript","node.js","vue.js","nuxt.js","konvajs"],"text":"Title: Vue-konva running into error: Must use import to load ES Module\nTags: javascript, node.js, vue.js, nuxt.js, konvajs\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement the `Vue-konva` into my application by following the documentation here. But I am running into the following error:\n\n```\nMust use import to load ES Module: /Users/myName/projects/projectName/node_modules/konva/lib/index-node.js require() of ES modules is not supported. \nrequire() of /Users/myName/projects/projectName/node_modules/konva/lib/index-node.js from /Users/myName/projects/projectName/node_modules/vue-konva/umd/vue-konva.js is an ES module file as it is a .js file whose nearest parent package.json \ncontains \"type\": \"module\" which defines all .js files in that package scope as ES modules. Instead rename index-node.js to end in .cjs, change the requiring code to use import(), or remove \"type\": \"module\" from /Users/myName/projects/projectName/node_modules/konva/package.json.\n```\n\nI did the following steps:\n\n- Install `npm install vue-konva konva --save` and `npm install canvas --save`.\n\n- Added the code in my `Vue` app from the documentation.\n\n- When I restart the application I get the error.\n\nFollowing things I tried for work-around:\n\n- I am using `node version v14.16.0`\n\n- I added the following in my `package.json` file:\n\n```\n\"ssr\": false,\n\"type\":\"module\",\n```\n\n- Remove `node-modules` folder and create again with `npm-install`.\n\nI feel like I am doing everything that has been mentioned in the documentation but still not sure why I am getting the error. Can someone please help me with this issue?\n\nHere is the complete code from the application:\n\n```\n\n \n \n \n \n \n\nimport Vue from 'vue'\nimport VueKonva from 'vue-konva'\n\nVue.use(VueKonva)\n\nexport default {\n data () {\n return {\n configKonva: {\n width: 200,\n height: 200\n },\n configCircle: {\n x: 100,\n y: 100,\n radius: 70,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 4\n }\n }\n }\n}\n\nbody {\n margin: 0;\n padding: 0;\n}\n\n```\n\n** **UPDATED** **\nI tried to like this and got the error, `client.js:227 TypeError: Vue.use is not a function`\n\n```\n\n \n \n \n \n \n\nexport default {\n data () {\n return {\n configKonva: {\n width: 200,\n height: 200\n },\n configCircle: {\n x: 100,\n y: 100,\n radius: 70,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 4\n }\n }\n },\n async mounted () {\n if (process.browser) {\n const Vue = await import('vue')\n const VueKonva = await import(\"vue-konva\")\n Vue.use(VueKonva)\n console.log('HELLO FROM MOUNTED')\n }\n }\n}\n\n```\n\n========================================\n\nCode:\n```text\nMust use import to load ES Module: /Users/myName/projects/projectName/node_modules/konva/lib/index-node.js require() of ES modules is not supported. \nrequire() of /Users/myName/projects/projectName/node_modules/konva/lib/index-node.js from /Users/myName/projects/projectName/node_modules/vue-konva/umd/vue-konva.js is an ES module file as it is a .js file whose nearest parent package.json \ncontains \"type\": \"module\" which defines all .js files in that package scope as ES modules. Instead rename index-node.js to end in .cjs, change the requiring code to use import(), or remove \"type\": \"module\" from /Users/myName/projects/projectName/node_modules/konva/package.json.\n```\n\n```text\n\"ssr\": false,\n\"type\":\"module\",\n```\n\n```html\n<template>\n <v-stage :config=\"configKonva\">\n <v-layer>\n <v-circle :config=\"configCircle\" />\n </v-layer>\n </v-stage>\n</template>\n\n<script>\nimport Vue from 'vue'\nimport VueKonva from 'vue-konva'\n\nVue.use(VueKonva)\n\nexport default {\n data () {\n return {\n configKonva: {\n width: 200,\n height: 200\n },\n configCircle: {\n x: 100,\n y: 100,\n radius: 70,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 4\n }\n }\n }\n}\n</script>\n\n<style>\nbody {\n margin: 0;\n padding: 0;\n}\n</style>\n```\n\n```html\n<template>\n <v-stage :config=\"configKonva\">\n <v-layer>\n <v-circle :config=\"configCircle\" />\n </v-layer>\n </v-stage>\n</template>\n\n<script>\nexport default {\n data () {\n return {\n configKonva: {\n width: 200,\n height: 200\n },\n configCircle: {\n x: 100,\n y: 100,\n radius: 70,\n fill: 'red',\n stroke: 'black',\n strokeWidth: 4\n }\n }\n },\n async mounted () {\n if (process.browser) {\n const Vue = await import('vue')\n const VueKonva = await import(\"vue-konva\")\n Vue.use(VueKonva)\n console.log('HELLO FROM MOUNTED')\n }\n }\n}\n</script>\n```\n\n```text\nVue-konva\n```\n\n```text\nnpm install vue-konva konva --save\n```\n\n```text\nnpm install canvas --save\n```\n\n```text\nVue\n```\n\n```text\nnode version v14.16.0\n```\n\n```text\npackage.json\n```\n\n```text\nnode-modules\n```\n\n```text\nnpm-install\n```\n\n```text\nclient.js:227 TypeError: Vue.use is not a function\n```\n\n```html\n<script>\nimport Vue from 'vue'\n\nexport default {\n async mounted () {\n if (process.browser) {\n const VueKonva = await import('vue-konva')\n Vue.use(VueKonva)\n console.log('HELLO FROM MOUNTED')\n }\n }\n}\n</script>\n```\n\n========================================\n\nComments:\n- Not sure what is `\"ssr\": false,` but did you tried setting up the Nuxt plugin as `mode: 'client'`? nuxtjs.org/docs/configuration-glossary/…\n- If you want to use it locally, you could maybe wrap it into a `` or maybe load it only on the client: stackoverflow.com/a/69572014/8816585 (if this specific package does not support SSR)\n- Also, did you tried this one? github.com/konvajs/vue-konva/issues/9\n- @kissu Thanks a lot for your response. `SSR` is something I was just trying to see if it would work. In one of the answers, it was mentioned so I added it. I should add `mode` in `nuxt.config` right but I am not using the `CDN` rather the `npm package` so I have not added `mode:client`. I tried adding this as well but it's not working for me. I even tried adding `` that's also not working.\n- `ssr: false` is for `nuxt.config.js` actually. If you want to have an SPA only Nuxt project. Not sure what is `mode` or even `mode:client` for you. And yeah, I'm not talking about the CDN. Your issue seems to be connected to this question btw: github.com/konvajs/vue-konva/issues/163 Maybe give it a bump!\n- @kissu Thanks a lot for the response. I have added an comment within it. I am not understanding why I am getting this issue but this I get only when I use the `Vue-Konva`. Normally, I do not get this.\n- I mean, this one is about Konva so yeah, seems legit.\n- @kissu Still unable to find the resolution. I am still getting the error. Any help would be really appreiciated.\n- Did you tried the same as yesterday (with browser-ui) with this package? It may help taking the same approach IMO.\n- @kissu I tried even that but it did not work and ran into various other issues. I have updated my code. I am trying out a few libraries to see which will suffice my need but I am unable to configure them. Looking forward to your response.","metadata":{"transformedAt":"2026-08-18T18:33:07.900Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":278,"estimatedTokens":1736}}874{"id":"stack-69517717","source":"stackoverflow","questionId":69517717,"title":"Questions about the /_nuxt/ javascript files locally","tags":["vue.js","nuxt.js","server-side-rendering"],"text":"Title: Questions about the /_nuxt/ javascript files locally\nTags: vue.js, nuxt.js, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nI have some questions about the javascript files that SSR nuxt apps create.\n\nWhere does nuxt place these files locally? This file `/_nuxt/pages/index.js` appears to be dynamic -- does the nuxt.config.js build this file and the others from scratch on each page load? Is nuxt config using code splitting to determine what JS and CSS is necessary for each page?\n\n```\n\n```\n\n========================================\n\nCode:\n```html\n<script src=\"/_nuxt/runtime.js\" defer></script>\n<script src=\"/_nuxt/pages/index.js\" defer></script>\n<script src=\"/_nuxt/commons/app.js\" defer></script>\n<script src=\"/_nuxt/vendors/app.js\" defer></script>\n<script src=\"/_nuxt/app.js\" defer></script>\n```\n\n```text\n/_nuxt/pages/index.js\n```\n\n```text\n.nuxt\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.900Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":31,"estimatedTokens":218}}875{"id":"stack-69493240","source":"stackoverflow","questionId":69493240,"title":"Apollo pagination with vuex","tags":["vue.js","graphql","nuxt.js"],"text":"Title: Apollo pagination with vuex\nTags: vue.js, graphql, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get vuetify's pagination component to work with the nuxtjs@apollo module.\n\nBut I'm having a hard time getting it to work with my vuex store.\n\nI'll skip over most of the code as its a lot of boilerplate.\n\nFirst of all in order to populate my initial state I send a graphql query to my back end and commit these to my state.\n\n```\nconst client = context.app.apolloProvider.defaultClient\n\nconst response = await client.query({\n query: productsGQL,\n variables: {\n first: 5,\n page: 1\n }\n})\n\ncommit('setProducts', response.data.products.data)\ncommit('setPagination', response.data.products.paginatorInfo)\ncommit('setPage', response.data.products.paginatorInfo.currentPage)\n```\n\nthis works fine, products, pagination and page are all set with initial data.\n\nNow, I have 2 components a `CardComponent` that contains all of the products like so\n\n```\n\nexport default {\n name: 'CardComponent',\n\n computed: {\n products() {\n return this.$store.getters.getProducts\n }\n }\n}\n\n```\n\nAnd a `PaginationComponent`:\n\n```\n\n \n \n \n\nexport default {\n name: 'PaginationComponent',\n\n data() {\n return {\n total_pages: Math.ceil(this.$store.getters.getPagination.total / this.$store.getters.getPagination.perPage)\n }\n },\n\n computed: {\n page: {\n get() {\n return this.$store.getters.getPage\n },\n set(value) {\n return this.$store.commit('setPage', value)\n }\n }\n }\n}\n\n```\n\n`Page` Initial value is 1, when I click on the second page the `Page` variable is updated to 2, this is also than reflected in my state.\n\nThe thing I'm unsure about is: how do I `requery` the database? the page is being updated but the products displayed are still the same, and I'm not sure how to go about this.\n\nIf you some more code from the store I'll show it here.\n\n========================================\n\nCode:\n```js\nconst client = context.app.apolloProvider.defaultClient\n\nconst response = await client.query({\n query: productsGQL,\n variables: {\n first: 5,\n page: 1\n }\n})\n\ncommit('setProducts', response.data.products.data)\ncommit('setPagination', response.data.products.paginatorInfo)\ncommit('setPage', response.data.products.paginatorInfo.currentPage)\n```\n\n```html\n<script>\nexport default {\n name: 'CardComponent',\n\n computed: {\n products() {\n return this.$store.getters.getProducts\n }\n }\n}\n</script>\n```\n\n```html\n<template>\n <div>\n <v-pagination\n v-model='page'\n circle\n :length='total_pages'\n />\n </div>\n</template>\n\n<script>\nexport default {\n name: 'PaginationComponent',\n\n data() {\n return {\n total_pages: Math.ceil(this.$store.getters.getPagination.total / this.$store.getters.getPagination.perPage)\n }\n },\n\n computed: {\n page: {\n get() {\n return this.$store.getters.getPage\n },\n set(value) {\n return this.$store.commit('setPage', value)\n }\n }\n }\n}\n</script>\n```\n\n```text\nCardComponent\n```\n\n```text\nPaginationComponent\n```\n\n```text\nPage\n```\n\n```text\nPage\n```\n\n```text\nrequery\n```\n\n```text\nrefresh()\n```\n\n========================================\n\nComments:\n- If your state is okay (double check your devtools, both Vue and Apollo ones) and the only thing missing, is another call to the database (double check your network tab), you could probably use the `refresh()` method as shown here: apollo.vuejs.org/api/smart-query.html#refresh\n- Hey, sorry for the late reply. but yes it was indeed the `refresh()` method that needed to be called again. Thanks for the answer","metadata":{"transformedAt":"2026-08-18T18:33:07.900Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":181,"estimatedTokens":885}}876{"id":"stack-76600621","source":"stackoverflow","questionId":76600621,"title":"Nuxt build on production failed: SyntaxError: Invalid or unexpected token","tags":["amazon-web-services","nuxt.js"],"text":"Title: Nuxt build on production failed: SyntaxError: Invalid or unexpected token\nTags: amazon-web-services, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIm breaking my head over this, i've been searching for hours and trying everything, from downgrading nuxt to tracking back in my older commits to see what changed.\n\nI get the following build error on AWS codebuild:\n\n```\n> nuxt build\n--\n165 | \n166 | /application/dotoo-web/node_modules/@nuxt/utils/node_modules/consola/dist/shared/consola.4bbae468.cjs:473\n167 | if (codePoint >= 0x3_00 && codePoint (/application/dotoo-web/node_modules/@nuxt/utils/node_modules/consola/dist/index.cjs:5:15)\n179 | at Module._compile (internal/modules/cjs/loader.js:778:30)\n180 | at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)\n181 | npm ERR! code ELIFECYCLE\n182 | npm ERR! errno 1\n183 | npm ERR! dotoo-web@2.36.0 build: `nuxt build`\n184 | npm ERR! Exit status 1\n```\n\nIm using Nuxt 2.17.0 and i'm pushing to a aws codebuild pipeline that was build by a third party for us. It seems it's still on Node 10 according to this line in the build log: `Status: Downloaded newer image for node:10-alpine`\n\nDoes anybody have a clue?\n\n========================================\n\nCode:\n```text\n> nuxt build\n--\n165 | \n166 | /application/dotoo-web/node_modules/@nuxt/utils/node_modules/consola/dist/shared/consola.4bbae468.cjs:473\n167 | if (codePoint >= 0x3_00 && codePoint <= 0x3_6F) {\n168 | ^^^\n169 | \n170 | SyntaxError: Invalid or unexpected token\n171 | at Module._compile (internal/modules/cjs/loader.js:723:23)\n172 | at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)\n173 | at Module.load (internal/modules/cjs/loader.js:653:32)\n174 | at tryModuleLoad (internal/modules/cjs/loader.js:593:12)\n175 | at Function.Module._load (internal/modules/cjs/loader.js:585:3)\n176 | at Module.require (internal/modules/cjs/loader.js:692:17)\n177 | at require (internal/modules/cjs/helpers.js:25:18)\n178 | at Object.<anonymous> (/application/dotoo-web/node_modules/@nuxt/utils/node_modules/consola/dist/index.cjs:5:15)\n179 | at Module._compile (internal/modules/cjs/loader.js:778:30)\n180 | at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)\n181 | npm ERR! code ELIFECYCLE\n182 | npm ERR! errno 1\n183 | npm ERR! dotoo-web@2.36.0 build: `nuxt build`\n184 | npm ERR! Exit status 1\n```\n\n```text\nStatus: Downloaded newer image for node:10-alpine\n```\n\n```text\n167 | if (codePoint >= 0x3_00 && codePoint <= 0x3_6F) {\n```\n\n```text\n0x3_00\n```\n\n```text\n_\n```\n\n```text\n0x300\n```\n\n```text\nnode:10-alpine\n```\n\n```text\nnode:12-alpine\n```\n\n```text\nnode:14-alpine\n```\n\n========================================\n\nComments:\n- Thanks! I updated to node `16.17.0` and it worked!","metadata":{"transformedAt":"2026-08-18T18:33:07.900Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":91,"estimatedTokens":683}}877{"id":"stack-74824374","source":"stackoverflow","questionId":74824374,"title":"How do i store custom object in prisma schema?","tags":["javascript","nuxt.js","prisma"],"text":"Title: How do i store custom object in prisma schema?\nTags: javascript, nuxt.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI have a model called \"Setup\"\n\n```\nmodel Setup {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n\n userId String? @unique @db.ObjectId\n user User? @relation(fields: [userId], references: [id])\n\n contract String[]\n legal String[]\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n```\n\nIn this model i want to store an array like\n\n```\nconst contractData = {\n id: '729a4839f3dapob44zt2b4b1',\n name: 'Example Name',\n text: 'Example Text'\n}\n```\n\nso in my above model \"Setup\" i want to store the contractData\n\n```\nprisma.setup.create({\n data: {\n userId: '6399bc74426f71f2da6e316c',\n personal: [],\n contract: contractData,\n legal: []\n }\n })\n```\n\nUnfortunately, this not work.\n\nHow can i define an Object for contract and store this in my database?\n\n========================================\n\nTop Answer:\nthis is old,\n\nquick answer is, it will be best to create a new model for your contractData object and then link to the parent using Prisma's relation.\n\nJSON would be extremely difficult to parse, and you can't just manufacture a data type like \"object\".\n\nLastly, [] is used to indicate a many relationship when suffixed to another model name, not to be confused with the List you have in Js or Ts\n\n========================================\n\nCode:\n```text\nmodel Setup {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n\n userId String? @unique @db.ObjectId\n user User? @relation(fields: [userId], references: [id])\n\n contract String[]\n legal String[]\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n```\n\n```text\nconst contractData = {\n id: '729a4839f3dapob44zt2b4b1',\n name: 'Example Name',\n text: 'Example Text'\n}\n```\n\n```text\nprisma.setup.create({\n data: {\n userId: '6399bc74426f71f2da6e316c',\n personal: [],\n contract: contractData,\n legal: []\n }\n })\n```\n\n```text\nmodel Setup {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n\n userId String? @unique @db.ObjectId\n user User? @relation(fields: [userId], references: [id])\n\n contract Json[]\n legal String[]\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n```\n\n```text\nJson\n```\n\n```text\nprisma.setup.create\n```\n\n```text\nSetup\n```\n\n```text\ncontract\n```\n\n```text\nmodel Setup {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n\n userId String? @unique @db.ObjectId\n user User? @relation(fields: [userId], references: [id])\n\n contract Object[]\n legal String[]\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n```\n\n```text\nprisma.setup.create({\n data: {\n userId: '6399bc74426f71f2da6e316c',\n personal: [],\n contract: [contractData],\n legal: []\n }\n})\n```\n\n```text\ncontract\n```\n\n```text\n[contractData]\n```\n\n========================================\n\nComments:\n- It is not possible to change the type in schema.prisma to Object[].. i receive the following error message: error: Type \"Object\" is neither a built-in type, nor refers to another model, custom type, or enum. --> schema.prisma:150.. should i install any extentions?\n- What do you mean this is old and how does that help answer the question? And isn't [] also used for lists in Prisma?\n- I believe the first paragraph answered that, and I also said having [ ] behind a model name, doesn't make it a list, it defines it's relationship. What you are describing is [ ] behind a data type like string[] which is a prisma list. So again the easiest way to store multiple Objects instead of JSON directly on the DB, will be to create a separate model","metadata":{"transformedAt":"2026-08-18T18:33:07.900Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":168,"estimatedTokens":919}}878{"id":"stack-69469218","source":"stackoverflow","questionId":69469218,"title":"Nuxt is throwing the error 'unknown action type' when I try to dispatch action from vuex store","tags":["javascript","vue.js","nuxt.js","vuex"],"text":"Title: Nuxt is throwing the error 'unknown action type' when I try to dispatch action from vuex store\nTags: javascript, vue.js, nuxt.js, vuex\nSource: Stack Overflow\n\nQuestion:\nI want to fetch some data from a firebase backend using an action to store it in vuex state. Currently I'm just working with some dummy data. Reading the data from the store in my index.vue works but as soon as I'm trying to get the action in index.vue I get the error that it is an unknown action type.\n\nstore/artikels.js\n\n```\nexport const state = () => ({\nartikel: [\n {\n id: \"1\",\n titel: \"Hallo\",\n untertitel: \"Servas\"\n },\n {\n id: \"2\",\n titel: \"Was\",\n untertitel: \"Wos\"\n },\n {\n id: \"3\",\n titel: \"Geht\",\n untertitel: \"Wüst\"\n }\n ]\n\n})\n\nexport const actions = () => ({\n fetchArtikel() {\n console.log('fetch data from firebase')\n }\n})\n\nexport const getters = () => ({\n artikel: (state) => {\n return state.artikel\n }\n})\n```\n\nthis is index.vue\n\n```\n \nimport { mapActions } from 'vuex'\n\nexport default {\n name: 'App',\ncomputed: {\n artikel() {\n return this.$store.state.artikels.artikel\n }\n},\nasync created() {\n await this.$store.dispatch('artikels/fetchArtikel')\n}\n\n```\n\nI've already tried to put the store in store/index.js without the namespace and also tried to dispatch it via mapActions and async fetch:\n\n```\nimport mapActions from 'vuex'\n\nmethods: {\n ...mapActions(['artikels/fetchArtikels'])\n}\n```\n\nor:\n\n```\nasync fetch({store}) {\n await store.dispatch('artikels/fetchArtikels')\n}\n```\n\nSo far, no luck. Can someone help me out? Thanks in advance!\n\n========================================\n\nCode:\n```text\nexport const state = () => ({\nartikel: [\n {\n id: \"1\",\n titel: \"Hallo\",\n untertitel: \"Servas\"\n },\n {\n id: \"2\",\n titel: \"Was\",\n untertitel: \"Wos\"\n },\n {\n id: \"3\",\n titel: \"Geht\",\n untertitel: \"Wüst\"\n }\n ]\n\n})\n\nexport const actions = () => ({\n fetchArtikel() {\n console.log('fetch data from firebase')\n }\n})\n\nexport const getters = () => ({\n artikel: (state) => {\n return state.artikel\n }\n})\n```\n\n```text\n<script> \nimport { mapActions } from 'vuex'\n\nexport default {\n name: 'App',\ncomputed: {\n artikel() {\n return this.$store.state.artikels.artikel\n }\n},\nasync created() {\n await this.$store.dispatch('artikels/fetchArtikel')\n}\n</script>\n```\n\n```text\nimport mapActions from 'vuex'\n\nmethods: {\n ...mapActions(['artikels/fetchArtikels'])\n}\n```\n\n```text\nasync fetch({store}) {\n await store.dispatch('artikels/fetchArtikels')\n}\n```\n\n```js\n// store/artikels.js\nexport const actions = () => ({/*...*/}) // ❌ function\nexport const getters = () => ({/*...*/}) // ❌ function\n\nexport const actions = {/*...*/} // ✅ object\nexport const getters = {/*...*/} // ✅ object\n```\n\n```text\nactions\n```\n\n```text\ngetters\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.900Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":168,"estimatedTokens":698}}879{"id":"stack-73221261","source":"stackoverflow","questionId":73221261,"title":"How to use router link in vuetify?","tags":["vue.js","nuxt.js","vuetify.js"],"text":"Title: How to use router link in vuetify?\nTags: vue.js, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\ni am designing a login form using vuetify, i want to make one option 'forgot password', where after clicking 'forgot password' it should redirect to forgot password page, i tried using router-link,nuxt-link, tag, and vuejs events(@click)and in function i called this.$router.push('forgotPassword'). but nothing works. please help me.\n\nthese are the following options i tried.\n\n```\n\n Forgot Password?\n Forgot Password?\n Forgot Password? \n Forgot Password\n\nchangeRouter(){\n this.$router.push({path: \"/forgotPassword\"});\n }\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n<v-col cols=\"6\">\n <div @click=\"changeRouter()\">Forgot Password?</div>\n <a href=\"../forgotPassword\">Forgot Password?</a>\n <v-list-item :to=\"{path: '/forgotPassword'}\">Forgot Password?</v-list-item> \n <router-link :to=\"{ path:'/forgotPassword', name: 'forgotPassword' }\">Forgot Password</router-link>\n</v-col>\n</template>\n<script>\nchangeRouter(){\n this.$router.push({path: \"/forgotPassword\"});\n }\n</script>\n```\n\n========================================\n\nComments:\n- Can you tell us more about your setup? Or what error you get? Besides, check the manual of Nuxt on how to use the router: nuxtjs.org/docs/features/file-system-routing/#nested-routes And finally, first try to just use nuxt-link with a simple route in to like so: Link\n- Hi @crslp i am not getting any error, the forgot password option is disabled, when i am clicking it nothing is happening. And my setup is not complex, simple setup i have done\n- If `changeRouter()` does not work - it means there is something wrong with your VueRouter's config. Check it.\n- First off, double check the route in your Vue devtools, make sure that it's there. Then, use a simple `button` with a `@click=\"$router.push({ name: 'forget-password-name-or-whatever' })\"`. Also, what do you mean by `the forgot password option is disabled`? Do you have a minimal reproducible example for that one?","metadata":{"transformedAt":"2026-08-18T18:33:07.900Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":48,"estimatedTokens":514}}880{"id":"stack-72981557","source":"stackoverflow","questionId":72981557,"title":"Unable to ignore folders in nuxtjs","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Unable to ignore folders in nuxtjs\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a problem with **nuxt ignore** to exclude some folders from being watched especially during development. I have searched the internet and the solutions don't seem to work for me.\n\nMy `.nuxtignore` file\n\n```\n.idea/\n```\n\nAnd the ignore property in `nuxt.config.js`\n\n```\nignore: [\n '**/*.test.*',\n 'node_modules/*',\n '**/.idea/*',\n '**/.nuxt/*',\n '**/.*ignore',\n],\n```\n\nI have also tried using the options independently, initially tried `.idea/*` in both files, still doesn't work, I get output like this in console:\n\n```\n↻ Updated .idea/workspace.xml 16:36:04\n\n✔ Client\n Compiled successfully in 7.20s\n\nNo issues found.\n```\n\nIs there anything am missing here?\n\n========================================\n\nTop Answer:\n*Note: my response below is for Nuxt3/vite so not specific to the original question, but sharing anyway as this was one of the results that came up in my search for trying to resolve the problem I had*\n\nNone of the other answers here worked for me. What finally did was adding an `ignore` array as per the docs to the nuxt.config.ts file. I was getting typescript errors when using some of the other solutions here.\n\nFor reference currently running\nNuxi 3.0.0-rc.12\n\nNuxt 3.0.0-rc.12 with Nitro 0.6.1\n\n```\n// nuxt.config.ts:\n...\nignore: [\n \"path/to/ignore/**\"\n],\n...\n```\n\n========================================\n\nCode:\n```text\n.idea/\n```\n\n```text\nignore: [\n '**/*.test.*',\n 'node_modules/*',\n '**/.idea/*',\n '**/.nuxt/*',\n '**/.*ignore',\n],\n```\n\n```text\n↻ Updated .idea/workspace.xml 16:36:04\n\n✔ Client\n Compiled successfully in 7.20s\n\nNo issues found.\n```\n\n```text\n.nuxtignore\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n.idea/*\n```\n\n```js\nexport default {\n watchers: {\n webpack: {\n ignored: /(pages)/,\n },\n },\n}\n```\n\n```text\npages\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n// nuxt.config.ts:\n...\nignore: [\n \"path/to/ignore/**\"\n],\n...\n```\n\n```text\nignore\n```\n\n========================================\n\nComments:\n- Hi, did you tried that one? github.com/nuxt/nuxt.js/issues/6326#issuecomment-1009037909\n- Hi, I had given up on this since none of the solutions worked until today when I checked this question again through notifications, this solution might actually work, I just implemented it and still testing to see if it will really work, once its all good, will mark this as accepted, and thanks btw\n- @lulliezy sounds perfect! Keep me updated if you have any success.\n- The answer was targeting Webpack (for Nuxt2 mostly), you're using Vite in your case so it's a different configuration indeed. Still, don't use an RC version, use the stable `v3.0` version.\n- Indeed, just haven't gotten around to the upgrade. Will be launching the site soon though so that'll be one of the housekeeping items to sort. Thanks 👍🏼\n- Ignore also targets builds, I don't think this is the same that the OP is asking for.","metadata":{"transformedAt":"2026-08-18T18:33:07.900Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":137,"estimatedTokens":770}}881{"id":"stack-73295610","source":"stackoverflow","questionId":73295610,"title":"Nuxt 3 firebase plugins erros Component auth has not been registered yet","tags":["javascript","firebase","firebase-authentication","nuxt.js","nuxt3.js"],"text":"Title: Nuxt 3 firebase plugins erros Component auth has not been registered yet\nTags: javascript, firebase, firebase-authentication, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nIn my project under plugins dir I have a single plugins called `firebase.ts` and it's look like this\n\n```\nimport { defineNuxtPlugin } from \"#app\";\nimport { firebaseConfig } from \"@/firebaseConfig\";\nimport { initializeApp } from \"firebase/app\";\nimport { getAuth } from \"firebase/auth\";\n\nexport default defineNuxtPlugin((nuxtApp) => {\n // Initialize Firebase\n const firebaseApp = initializeApp(firebaseConfig);\n const firebaseAuthInstance = getAuth(firebaseApp);\n})\n```\n\nWhenever I run my project it's give this kind of error. But if I make the plugin client only i mean `firebase.client.ts` then it work just fine. But I want to get this pluin both in client and server side. How to achive that?\n\n```\n[h3] [unhandled] H3Error: Component auth has not been registered yet\n at createError (file:///home/riyad/Desktop/nuxt-test/node_modules/h3/dist/index.mjs:238:15)\n at Server.nodeHandler (file:///home/riyad/Desktop/nuxt-test/node_modules/h3/dist/index.mjs:428:21) {\n statusCode: 500,\n fatal: false,\n unhandled: true,\n statusMessage: 'Internal Server Error'\n}\n[nuxt] [request error] Component auth has not been registered yet\n at createError (./node_modules/h3/dist/index.mjs:238:15) \n at Server.nodeHandler (./node_modules/h3/dist/index.mjs:428:21)\n```\n\n========================================\n\nTop Answer:\nAfter many attempts, I was able to solve the issue. Here is the code on the directory /plugins/plugins.ts:\n\n```\nimport { getAuth } from \"@firebase/auth\";\nimport { initializeApp } from \"firebase/app\";\nimport { firebaseConfig } from \"./firebase/firebaseConfig\";\n\nconst authInstance = () => {\n const app = initializeApp(firebaseConfig);\n const auth = getAuth(app);\n return auth\n};\n\nexport default defineNuxtPlugin(() => {\n return {\n provide: {\n authInstance,\n },\n };\n});\n```\n\nIt appears that the initializeApp Function was not called correctly. But if you call the initializeApp and getAuth on a new function it returns The Auth Object correctly.\n\n========================================\n\nCode:\n```js\nimport { defineNuxtPlugin } from \"#app\";\nimport { firebaseConfig } from \"@/firebaseConfig\";\nimport { initializeApp } from \"firebase/app\";\nimport { getAuth } from \"firebase/auth\";\n\nexport default defineNuxtPlugin((nuxtApp) => {\n // Initialize Firebase\n const firebaseApp = initializeApp(firebaseConfig);\n const firebaseAuthInstance = getAuth(firebaseApp);\n})\n```\n\n```text\n[h3] [unhandled] H3Error: Component auth has not been registered yet\n at createError (file:///home/riyad/Desktop/nuxt-test/node_modules/h3/dist/index.mjs:238:15)\n at Server.nodeHandler (file:///home/riyad/Desktop/nuxt-test/node_modules/h3/dist/index.mjs:428:21) {\n statusCode: 500,\n fatal: false,\n unhandled: true,\n statusMessage: 'Internal Server Error'\n}\n[nuxt] [request error] Component auth has not been registered yet\n at createError (./node_modules/h3/dist/index.mjs:238:15) \n at Server.nodeHandler (./node_modules/h3/dist/index.mjs:428:21)\n```\n\n```text\nfirebase.ts\n```\n\n```text\nfirebase.client.ts\n```\n\n```js\nimport { defineNuxtPlugin } from '#app'\nimport { initializeApp, getApps } from 'firebase/app'\nimport { connectFirestoreEmulator as connectFirestoreEmulatorServer, getFirestore as getFirestoreServer } from 'firebase/firestore/lite'\n\nimport { connectAuthEmulator, getAuth } from \"firebase/auth\"\nimport { connectDatabaseEmulator, getDatabase } from \"firebase/database\"\nimport { connectFirestoreEmulator, getFirestore } from \"firebase/firestore\"\nimport { connectFunctionsEmulator, getFunctions } from \"firebase/functions\"\nimport { connectStorageEmulator, getStorage } from \"firebase/storage\"\n\nexport default defineNuxtPlugin((nuxtApp) => {\n\n const firebaseConfig = { ...useRuntimeConfig().public.firebaseConfig }\n\n if (!getApps().length) initializeApp(firebaseConfig)\n\n // Code bellow allows to work with local emulators you can delete it if you work without emulators\n if(!process.dev) return\n\n const firestoreHost = getFirestoreServer().toJSON()['settings'].host\n\n if(firestoreHost !== 'localhost:8080') {\n connectFirestoreEmulatorServer(getFirestoreServer(), 'localhost', 8080)\n }\n\n if (process.client) {\n connectAuthEmulator(getAuth(), \"http://localhost:9099\")\n connectFirestoreEmulator(getFirestore(), \"localhost\", 8080)\n connectDatabaseEmulator(getDatabase(), \"localhost\", 9000)\n connectStorageEmulator(getStorage(), \"localhost\", 9199)\n connectFunctionsEmulator(getFunctions(), \"localhost\", 5001)\n }\n \n})\n```\n\n```js\n<template>\n <div>\n <button @click=\"signIn\">Sign In</button>\n <p>{{ data.test.title }}</p>\n <p>User email: {{userEmail}}</p>\n </div>\n</template>\n\n<script setup lang=\"ts\">\nimport { getAuth, OAuthProvider, signInWithPopup } from 'firebase/auth';\nimport { doc, getDoc, getFirestore } from 'firebase/firestore/lite';\n\nconst data = reactive({ test: null })\nconst userEmail = ref('')\n\nconst result = await getDoc(doc(getFirestore(), 'test/test'))\nif (result.exists()) data.test = result.data()\n\n// Here example how you can run code only on client.\n// There is `process.server` too.\nif (process.client) {\n const userCredentials = await signInWithPopup(getAuth(), new OAuthProvider('google.com'))\n if (userCredentials.user) userEmail.value = userCredentials.user.email\n}\n\nasync function signIn() {\n const userCredentials = await signInWithPopup(getAuth(), new OAuthProvider('google.com'))\n if (userCredentials.user) userEmail.value = userCredentials.user.email\n}\n</script>\n```\n\n```text\n/lite\n```\n\n```text\n'firebase/firestore/lite'\n```\n\n```text\nsignIn\n```\n\n```text\nif (process.client)\n```\n\n```text\nonMounted()\n```\n\n```text\nimport { getAuth } from \"@firebase/auth\";\nimport { initializeApp } from \"firebase/app\";\nimport { firebaseConfig } from \"./firebase/firebaseConfig\";\n\nconst authInstance = () => {\n const app = initializeApp(firebaseConfig);\n const auth = getAuth(app);\n return auth\n};\n\nexport default defineNuxtPlugin(() => {\n return {\n provide: {\n authInstance,\n },\n };\n});\n```\n\n========================================\n\nComments:\n- Did you gave a try to those: github.com/nuxt/framework/… ?\n- Yes, I have read those discussions. All of them use `firebase.client.ts` type solution, I mean render plugin only in client side.\n- The module is maybe just not supporting SSR due to it's implementation.\n- Think its a bit more subtle than that. Here you are \"providing\" a function that will initialise the app and return the auth instance when it is called (as opposed to when the nuxt app loads). As a result, you're probably only calling $authInstance() from client side code so it works.\n- Your answer just saved a life.","metadata":{"transformedAt":"2026-08-18T18:33:07.900Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":219,"estimatedTokens":1703}}882{"id":"stack-75771755","source":"stackoverflow","questionId":75771755,"title":"pnpm install --shamefully-hoist causes build fail on Netlify","tags":["nuxt.js","netlify","nuxt3.js","pnpm"],"text":"Title: pnpm install --shamefully-hoist causes build fail on Netlify\nTags: nuxt.js, netlify, nuxt3.js, pnpm\nSource: Stack Overflow\n\nQuestion:\nWhile trying to build out my Nuxt 3 app on Netlify, I run into this error:\n\n```\n12:30:30 PM: 1. Build command from Netlify app \n12:30:30 PM: ────────────────────────────────────────────────────────────────\n12:30:30 PM: \n12:30:30 PM: $ npm run build\n12:30:31 PM: > build\n12:30:31 PM: > nuxt build\n12:30:31 PM: [log] Nuxi 3.0.0\n12:30:31 PM: [log] Nuxt 3.0.0 with Nitro 1.0.0\n12:30:31 PM: [info] [nuxt:tailwindcss] Using default Tailwind CSS file from runtime/tailwind.css\n12:30:32 PM: [error] [vite]: Rollup failed to resolve import \"vue\" from \"node_modules/.pnpm/nuxt@3.0.0/node_modules/nuxt/dist/app/entry.mjs\".\n12:30:32 PM: This is most likely unintended because it can break your application at runtime.\n12:30:32 PM: If you do want to externalize this module explicitly add it to\n12:30:32 PM: `build.rollupOptions.external\n```\n\nSeems like the issue is from using `pnpm install --shamefully-hoist` instead of `npm`.\n\nSOLVED:\n\nhttps://stackoverflow.com/a/75771756/4100000\n\n========================================\n\nCode:\n```text\n12:30:30 PM: 1. Build command from Netlify app \n12:30:30 PM: ────────────────────────────────────────────────────────────────\n12:30:30 PM: \n12:30:30 PM: $ npm run build\n12:30:31 PM: > build\n12:30:31 PM: > nuxt build\n12:30:31 PM: [log] Nuxi 3.0.0\n12:30:31 PM: [log] Nuxt 3.0.0 with Nitro 1.0.0\n12:30:31 PM: [info] [nuxt:tailwindcss] Using default Tailwind CSS file from runtime/tailwind.css\n12:30:32 PM: [error] [vite]: Rollup failed to resolve import \"vue\" from \"node_modules/.pnpm/nuxt@3.0.0/node_modules/nuxt/dist/app/entry.mjs\".\n12:30:32 PM: This is most likely unintended because it can break your application at runtime.\n12:30:32 PM: If you do want to externalize this module explicitly add it to\n12:30:32 PM: `build.rollupOptions.external\n```\n\n```text\npnpm install --shamefully-hoist\n```\n\n```text\nnpm\n```\n\n```text\nPNPM_FLAGS=--shamefully-hoist\n```\n\n```text\npnpm build\n```\n\n```text\nnpm run build\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.900Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":67,"estimatedTokens":527}}883{"id":"stack-73206341","source":"stackoverflow","questionId":73206341,"title":"How to access environment variables in a composable in Nuxt3?","tags":["vue.js","nuxt.js","nuxt3.js"],"text":"Title: How to access environment variables in a composable in Nuxt3?\nTags: vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nIn my nuxt 3 App, for data fetching I wanna set a baseURL for all my API calls. As I get this baseURL from enviroment variable. How to set the the baseURL?\n\nI warp the `useFetch` with composables, but then I can't get the baseURL as `useRuntimeConfig()` is not accessable there.\n\n```\n// My composables function\nconst baseURL = \"how to get baseURL from process.env\";\n\nexport const myFetch = async (url: string) => {\n const options = {\n baseURL: baseURL,\n };\n\n return await useFetch(url, options);\n}\n```\n\n========================================\n\nCode:\n```js\n// My composables function\nconst baseURL = \"how to get baseURL from process.env\";\n\nexport const myFetch = async (url: string) => {\n const options = {\n baseURL: baseURL,\n };\n\n return await useFetch(url, options);\n}\n```\n\n```text\nuseFetch\n```\n\n```text\nuseRuntimeConfig()\n```\n\n```js\nexport default () => {\n const config = useRuntimeConfig()\n\n console.log(config)\n}\n```\n\n========================================\n\nComments:\n- Here is a comment that may be relevant in your case: github.com/nuxt/framework/discussions/… Otherwise, the rest of the discussion is also interesting.\n- Thanks a lot. It working. I just have to declear the `useRuntimeConfig()` inside my composable function\n- Posted an answer!\n- anyone know how to do this in Nuxt 2?\n- @v3nt if I'm not mistaken, there are no composable in Nuxt2.\n- there are is you use composition api 👍\n- Yeah I would also be interested in how I can use this with nuxt 2.17, nuxt-bridge and the composition-api\n- @Merc stackoverflow.com/a/67705541/8816585\n- Thanks for the link. It does not really cover how I can use useRuntimeConfig in my vuex store though. I tried but I get errors all the time...\n- @Merc you should rather be using Pinia anyway. Feel free to post a brand new question.\n- I am moving away from vuex anyway. Instead of Pinia I use composables now to manage (shared) states. I have an older project where we still work with vuex but I needed to overhaul the project and update and now my nuxt.config includes `runtimeConfig` AND `env`. The latter to still have access to my env variables in a vuex store module. I wanted to get rid of that. Maybe someday I will remove the vuex store completely.","metadata":{"transformedAt":"2026-08-18T18:33:07.900Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":68,"estimatedTokens":590}}884{"id":"stack-68703380","source":"stackoverflow","questionId":68703380,"title":"Vue.js/NuxtJS - how to create components with a default design customizable by a JSON configuration file","tags":["javascript","css","json","vue.js","nuxt.js"],"text":"Title: Vue.js/NuxtJS - how to create components with a default design customizable by a JSON configuration file\nTags: javascript, css, json, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm developing a NuxtJS website and the pages/components can have either a generic design by default, either one that is customizable by client, and will be specified in the url.\n\nSomething alone the lines of:\n\n`http://localhost:3000/registration` - For a generic page\n\n`http://localhost:3000/client-name/registration` - Client specific page\n\nTo achieve that goal, I have a JSON configuration file per client (say `client-name.json`) that has this structure.\n\n```\n{\n \"some_configuration_property\": {},\n \"another_configuration_property\": {},\n \"design\": {\n \"logoUrl\": \"/assets/client-name/logo.png\",\n \"backgroundColor\": \"#000000\",\n \"primaryColor\": \"#ffffff\",\n \"secondaryColor\": \"#ffff00\"\n },\n}\n```\n\nTo start things, I implemented the routing system and I can successfully read each client's configuration based on the current route (inside the `` tag of the Vue file of that route), inside the setup method (I use @nuxt/composition-api).\n\nThe problem that I'm facing now is to figure out how to pass these \"design variables\" into the `` tag of my Vue file, which uses SCSS. The behaviour that I wanted to implement was to have a default design for a specific component/page, but that could be overridden by these \"design variables\" specific to each client.\n\nThe first thing that came to my mind was to use CSS variables, that\nwould allow me to create variables with a default values but that I\nwould be able to override inside the styles. I created a sample component for test and it worked with CSS properties and the v-deep pseudo element. However, this means that I would have to create a class for each client in the customized component and that's what I'd like to avoid. I first thought to this approach because it would give me a lot of flexibility about how I choose to use these design colors inside the styles.\n\nExample:\n\n```\n// From the customizable component\n.my-button {\n color: (--button-color, teal);\n}\n\n// Styling from a parent component/view\n// Had to create a selector with a style like for superior specificity though, not so clean\nv::deep {\n div {\n &.my-button {\n --button-color: purple;\n }\n }\n}\n```\n\nI've seen the `/deep/` selector or `::v-deep` pseudo selector but I don't think it's a very clean solution since it would be used a lot in the codebase. Styling component from parents would make the code hardly maintainable.\n\nAnother approach could be to pass a variable, `classArray` for instance, inside the setup method to dynamically bind CSS classes on the DOM elements. Although, it would be way too cumbersome to create a CSS class per client with the associated styles.\n\nLike this:\n\n```\n\n \n\nimport { defineComponent } from '@nuxtjs/composition-api'\n\nexport default defineComponent({\n name: 'MyPage',\n setup() {\n const clientName = 'someClientName';\n const classArray = [clientName]\n return { classArray };\n },\n})\n\n.someClientName {\n // some custom styles\n}\n\n```\n\nWhat would be your approach in this situation?\n\nThanks for help!\n\n========================================\n\nCode:\n```text\n{\n \"some_configuration_property\": {},\n \"another_configuration_property\": {},\n \"design\": {\n \"logoUrl\": \"/assets/client-name/logo.png\",\n \"backgroundColor\": \"#000000\",\n \"primaryColor\": \"#ffffff\",\n \"secondaryColor\": \"#ffff00\"\n },\n}\n```\n\n```text\n// From the customizable component\n.my-button {\n color: (--button-color, teal);\n}\n\n// Styling from a parent component/view\n// Had to create a selector with a style like <div> for superior specificity though, not so clean\nv::deep {\n div {\n &.my-button {\n --button-color: purple;\n }\n }\n}\n```\n\n```text\n<template>\n <my-button :class=\"classArray\"></my-button>\n</template>\n\n<script lang=\"ts\">\nimport { defineComponent } from '@nuxtjs/composition-api'\n\nexport default defineComponent({\n name: 'MyPage',\n setup() {\n const clientName = 'someClientName';\n const classArray = [clientName]\n return { classArray };\n },\n})\n</script>\n\n<style lang=\"scss\" scoped>\n.someClientName {\n // some custom styles\n}\n</style>\n```\n\n```text\nhttp://localhost:3000/registration\n```\n\n```text\nhttp://localhost:3000/client-name/registration\n```\n\n```text\nclient-name.json\n```\n\n```text\n<script>\n```\n\n```text\n<style>\n```\n\n```text\n/deep/\n```\n\n```text\n::v-deep\n```\n\n```text\nclassArray\n```\n\n```text\n// theme.scss\n$primaryColor: #abc;\n// $buttonColor: $primaryColor\n\n@function primaryColor() {\n @return #{var(--primary-color, $primaryColor)}\n}\n\n@function buttonColor() {\n @return #{var(--button-color, primaryColor())}\n}\n```\n\n```text\n// From the customizable component\n.my-button {\n color: buttonColor();\n}\n```\n\n```text\nconst config = await loadClientConfig();\ndocument.documentElement.style.setProperty(--primary-color, config.design.primaryColor)\n```\n\n```text\nprimaryColor()\n```\n\n```text\n$primaryColor\n```\n\n========================================\n\nComments:\n- I'm not sure if I the problem with CSS vars parent/child. But you'll loose SASS features this way (color manipulation, etc). The most hassle-free way is stackoverflow.com/questions/62370457/… .\n- I already use nuxt-style-resources to have globally defined Sass variables! But that doesn't explain how I could create generic code for each client, I would have to create specific styles in each page or component right? Or do you have another approach in mind?\n- Yes, I meant that this needs to compile the app per client, which is probably not what you was hoping for but likely the only option that doesn't use CSS vars. Can you clarify the problem with CSS vars? You can define them dynamically on config load with `setProperty`, then they can be used with SASS function e.g. `primaryColor()` that generates something like `var(--primary-color, $defaultPrimaryColor)`.\n- I made CSS properties work together with v-deep! But the problem is still that I'd have to create a class for each client in the customized component and that's what I'd like to avoid. Are you talking about this setProperty though ? developer.mozilla.org/en-US/docs/Web/CSS/…\n- Edited my answer to add CSS vars working code\n- Deep selectors look cumbersome and doesn't make use of SASS for theming. Yes, that's what I meant. What I suggest is to still use SASS, only that you need to use functions like primaryColor() instead of using variables like $primaryColor directly. And --primary-color, etc are defined for the whole document at runtime with setProperty.\n- Would you mind sharing an example so it's easier to understand? `setProperty` is used to define inline styles on an element, isn't it better to define those CSS properties in a global SCSS file on the `:root` attribute?\n- I don't understand how you would customize a component for a specific client with your solution. OK, you're using SASS function to return `var(--primary-color, $defaultPrimaryColor)`, but if `--primary-color` is defined on the document, that doesn't solve my problem because it can't be specific to a URL as I explained in my answer. On the contrary, I want to be able to override `--primary-color` from the a parent component `style` tag.\n- Please, clarify why you need to do this per component. The question seems to refer to global client theme. Any way, a variable can be defined on any element in DOM as it's cascading like other styles.\n- *isn't it better to define those CSS properties in a global SCSS file on the :root attribute?* - it is, but you don't have these properties at build time. Unless you want to rebuild SCSS on the fly per page, which is not a good idea in production, vars need to be set dynamically as soon as they are available, i.e. when a config is loaded.\n- I didn't understand your solution correctly, now I get it, thanks for sharing your perspective!","metadata":{"transformedAt":"2026-08-18T18:33:07.900Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":224,"estimatedTokens":1968}}885{"id":"stack-68575241","source":"stackoverflow","questionId":68575241,"title":"How to use owl carousel in Nuxt?","tags":["javascript","vue.js","plugins","nuxt.js"],"text":"Title: How to use owl carousel in Nuxt?\nTags: javascript, vue.js, plugins, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI want to make script work on every page without that these page need loaded;\nI have owl caroussel script on my static folder, and i already put it in nuxt.config.js, here how i put it:\n\n```\nhead: {\n title: 'title',\n htmlAttrs: {\n lang: 'en'\n },\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: '' },\n { name: 'format-detection', content: 'telephone=no' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ],\n script: [{\n src: process.env.BASE_URL_ROOT + \"/jquery-3.3.1.min.js\",\n type: \"text/javascript\"\n },\n {\n src: process.env.BASE_URL_ROOT + \"/owl.carousel.min.js\",\n type: \"text/javascript\"\n },\n {\n src: process.env.BASE_URL_ROOT + \"/main-script.js\",\n type: \"text/javascript\"\n }\n ]\n},\n```\n\nAnd there is the script on my main-script.js:\n\n```\n$(document).ready(function() {\n\n$('.owl-menu').owlCarousel({\n loop: true,\n responsiveClass: true,\n center: true,\n items: 6,\n nav: true,\n dots: false,\n autoWidth: true,\n responsive: {\n 600: {\n items: 6,\n nav: true,\n autoWidth: true,\n center: true,\n loop: true\n },\n }\n})\n\n$('.owl-video').owlCarousel({\n loop: true,\n center: true,\n items: 3,\n margin: 10,\n nav: true,\n dots: true,\n responsive: {\n 600: {\n items: 3,\n margin: 12,\n },\n },\n navContainer: \"#nav-conte\",\n navText: [\n '**',\n '**'\n ]\n})\n})\n```\n\nThe caroussel work well on the page if the page is loaded, but if it come from nuxt navigation, the caroussel script not work anymore.\n\nSolution that i used is MutationObserver that look at the change on the DOM; on my `main-script.js`:\n\n```\nMutationObserver = window.MutationObserver || window.WebKitMutationObserver;\n\nvar observer = new MutationObserver(function(mutations, observer) {\n // my owl caroussel script\n});\n\nobserver.observe(document, {\n subtree: true,\n attributes: true\n});\n```\n\n========================================\n\nTop Answer:\n```\nMutationObserver = window.MutationObserver || window.WebKitMutationObserver;\n\nvar observer = new MutationObserver(function(mutations, observer) {\n // your owl caroussel script\n \n $('.owl-menu').owlCarousel({\n loop: true,\n responsiveClass: true,\n center: true,\n items: 6,\n nav: true,\n dots: false,\n autoWidth: true,\n responsive: {\n 600: {\n items: 6,\n nav: true,\n autoWidth: true,\n center: true,\n loop: true\n },\n }\n})\n\n$('.owl-video').owlCarousel({\n loop: true,\n center: true,\n items: 3,\n margin: 10,\n nav: true,\n dots: true,\n responsive: {\n 600: {\n items: 3,\n margin: 12,\n },\n },\n navContainer: \"#nav-conte\",\n navText: [\n '**',\n '**'\n ]\n})\n\n});\n\nobserver.observe(document, {\n subtree: true,\n attributes: true\n});\n```\n\n**This worked for me. You can try.** enter link description here\n\n========================================\n\nCode:\n```text\nhead: {\n title: 'title',\n htmlAttrs: {\n lang: 'en'\n },\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: '' },\n { name: 'format-detection', content: 'telephone=no' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ],\n script: [{\n src: process.env.BASE_URL_ROOT + \"/jquery-3.3.1.min.js\",\n type: \"text/javascript\"\n },\n {\n src: process.env.BASE_URL_ROOT + \"/owl.carousel.min.js\",\n type: \"text/javascript\"\n },\n {\n src: process.env.BASE_URL_ROOT + \"/main-script.js\",\n type: \"text/javascript\"\n }\n ]\n},\n```\n\n```text\n$(document).ready(function() {\n\n$('.owl-menu').owlCarousel({\n loop: true,\n responsiveClass: true,\n center: true,\n items: 6,\n nav: true,\n dots: false,\n autoWidth: true,\n responsive: {\n 600: {\n items: 6,\n nav: true,\n autoWidth: true,\n center: true,\n loop: true\n },\n }\n})\n\n$('.owl-video').owlCarousel({\n loop: true,\n center: true,\n items: 3,\n margin: 10,\n nav: true,\n dots: true,\n responsive: {\n 600: {\n items: 3,\n margin: 12,\n },\n },\n navContainer: \"#nav-conte\",\n navText: [\n '<i class=\"far fa-arrow-alt-circle-left\" aria-hidden=\"true\" style=\"color: rgba(0,0,0,0.67843);\"></i>',\n '<i class=\"far fa-arrow-alt-circle-right\" aria-hidden=\"true\" style=\"color: rgba(0,0,0,0.67843);\"></i>'\n ]\n})\n})\n```\n\n```text\nMutationObserver = window.MutationObserver || window.WebKitMutationObserver;\n\nvar observer = new MutationObserver(function(mutations, observer) {\n // my owl caroussel script\n});\n\nobserver.observe(document, {\n subtree: true,\n attributes: true\n});\n```\n\n```text\nmain-script.js\n```\n\n```text\nrefs\n```\n\n```text\nquerySelector\n```\n\n```text\nowl carousel\n```\n\n```text\nMutationObserver = window.MutationObserver || window.WebKitMutationObserver;\n\nvar observer = new MutationObserver(function(mutations, observer) {\n // your owl caroussel script\n \n $('.owl-menu').owlCarousel({\n loop: true,\n responsiveClass: true,\n center: true,\n items: 6,\n nav: true,\n dots: false,\n autoWidth: true,\n responsive: {\n 600: {\n items: 6,\n nav: true,\n autoWidth: true,\n center: true,\n loop: true\n },\n }\n})\n\n$('.owl-video').owlCarousel({\n loop: true,\n center: true,\n items: 3,\n margin: 10,\n nav: true,\n dots: true,\n responsive: {\n 600: {\n items: 3,\n margin: 12,\n },\n },\n navContainer: \"#nav-conte\",\n navText: [\n '<i class=\"far fa-arrow-alt-circle-left\" aria-hidden=\"true\" style=\"color: rgba(0,0,0,0.67843);\"></i>',\n '<i class=\"far fa-arrow-alt-circle-right\" aria-hidden=\"true\" style=\"color: rgba(0,0,0,0.67843);\"></i>'\n ]\n})\n\n\n\n});\n\nobserver.observe(document, {\n subtree: true,\n attributes: true\n});\n```\n\n========================================\n\nComments:\n- I used MutationObserver for look at DOM change, cause vue doesn't load the page but change the DOM, so i think it's the near way i can do, i'll look at other way\n- @MichelGisenaël Vue has it's own reactivity system, no need to use a `MutationObserver`. The framework has plenty to offer and you should be able to choose a package that can be used the \"Vue-way\".\n- VanillaJS, jQuery + watching the whole thing deeply. Hm, can't recommend that when working with Vue tbh.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:07.900Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":329,"estimatedTokens":1715}}886{"id":"stack-69034541","source":"stackoverflow","questionId":69034541,"title":"Nuxt await async + vuex","tags":["vue.js","nuxt.js"],"text":"Title: Nuxt await async + vuex\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIm using nuxt and vuex. In vuex im getting data:\n\n```\nactions: {\n get_posts(ctx) {\n axios.get(\"http://vengdef.com/wp-json/wp/v2/posts\").then(post => {\n let posts = post.data;\n\n if (!posts.length) return;\n\n let medias_list = \"\";\n posts.forEach(md => {\n medias_list += md.featured_media + \",\"\n });\n medias_list = medias_list.slice(0, -1);\n\n let author_list = \"\";\n posts.forEach(md => {\n author_list += md.author + \",\"\n });\n author_list = author_list.slice(0, -1);\n\n axios.all([\n axios.get(\"http://vengdef.com/wp-json/wp/v2/media?include=\" + medias_list),\n axios.get(\"http://vengdef.com/wp-json/wp/v2/users?include=\" + author_list),\n axios.get(\"http://vengdef.com/wp-json/wp/v2/categories\"),\n ]).then(axios.spread((medias, authors, categories) => {\n\n ctx.commit(\"set_postlist\", {medias, authors, categories} );\n\n })).catch((err) => {\n console.log(err)\n });\n\n })\n }\n },\n```\n\nIn vuex state i have dynamic postlist from exaple below.\nHow i can use it in Nuxt?\n\nIn nuxt i know async fetch and asyncData.\n\n```\nasync fetch () {\n this.$store.dispatch(\"posts/get_posts\");\n}\n```\n\nThats not working.\n\nHow i can say to nuxt, wait loading page, before vuex actions loading all data?\n\n========================================\n\nTop Answer:\n### Misread the actual question, hence the update\n\nWith Nuxt, you can either use `asyncData()`, the syntax will change a bit tho and the render will be totally blocked until all the calls are done.\n\nOr use a combo of `fetch()` and some skeletons to make a smooth transition (aka not blocking the render), or a loader with the `$fetchState.pending` helper.\n\nMore info can be found here: https://nuxtjs.org/docs/2.x/features/data-fetching#the-fetch-hook\n\n### Older (irrelevant) answer\n\nIf you want to pass a param to your Vuex action, you can call it like this\n\n```\nasync fetch () {\n await this.$store.dispatch('posts/get_posts', variableHere)\n}\n```\n\nIn Vuex, access it like\n\n```\nget_posts(ctx, variableHere) {\n```\n\nThat you can then use down below.\n\nPS: try to use `async/await` everywhere.\n\nPS2: also, you can destructure the context directly with something like this\n\n```\nget_posts({ commit }, variableHere) {\n ...\n commit('set_postlist', {medias, authors, categories})\n}\n```\n\n========================================\n\nCode:\n```js\nactions: {\n get_posts(ctx) {\n axios.get(\"http://vengdef.com/wp-json/wp/v2/posts\").then(post => {\n let posts = post.data;\n\n\n if (!posts.length) return;\n\n let medias_list = \"\";\n posts.forEach(md => {\n medias_list += md.featured_media + \",\"\n });\n medias_list = medias_list.slice(0, -1);\n\n\n let author_list = \"\";\n posts.forEach(md => {\n author_list += md.author + \",\"\n });\n author_list = author_list.slice(0, -1);\n\n\n axios.all([\n axios.get(\"http://vengdef.com/wp-json/wp/v2/media?include=\" + medias_list),\n axios.get(\"http://vengdef.com/wp-json/wp/v2/users?include=\" + author_list),\n axios.get(\"http://vengdef.com/wp-json/wp/v2/categories\"),\n ]).then(axios.spread((medias, authors, categories) => {\n\n ctx.commit(\"set_postlist\", {medias, authors, categories} );\n\n })).catch((err) => {\n console.log(err)\n });\n\n\n })\n }\n },\n```\n\n```js\nasync fetch () {\n this.$store.dispatch(\"posts/get_posts\");\n}\n```\n\n```text\nget_posts(ctx) {\n return axios.get(...\n // ...\n```\n\n```text\nasync fetch () {\n await this.$store.dispatch(\"posts/get_posts\");\n}\n```\n\n```text\nctx.commit(\"set_postlist\", {medias, authors, categories} );\n```\n\n```text\nreturn Promise.resolve({ medias, authors, categories })\n```\n\n```text\nasync fetch () {\n this.posts = await this.$store.dispatch(\"posts/get_posts\");\n // now you can use posts in template \n}\n```\n\n```text\nreturn\n```\n\n```js\nasync fetch () {\n await this.$store.dispatch('posts/get_posts', variableHere)\n}\n```\n\n```js\nget_posts(ctx, variableHere) {\n```\n\n```js\nget_posts({ commit }, variableHere) {\n ...\n commit('set_postlist', {medias, authors, categories})\n}\n```\n\n```text\nasyncData()\n```\n\n```text\nfetch()\n```\n\n```text\n$fetchState.pending\n```\n\n```text\nasync/await\n```\n\n========================================\n\nComments:\n- await this.$store.dispatch(\"posts/get_posts\"); Maybe will be enough\n- Thats not why i need, read post. I need to say nuxt wait, before vuex fetching data. And load page only after vuex, i dont need to pass data in vuex\n- @ЕвгенийВенеград if you want to have `fetch()` and something blocking, you need to export your fetching logic to a `middleware`. This should work fine.","metadata":{"transformedAt":"2026-08-18T18:33:07.900Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":219,"estimatedTokens":1161}}887{"id":"stack-68819814","source":"stackoverflow","questionId":68819814,"title":"Remove query item from router","tags":["javascript","vue.js","vuejs2","nuxt.js","vue-router"],"text":"Title: Remove query item from router\nTags: javascript, vue.js, vuejs2, nuxt.js, vue-router\nSource: Stack Overflow\n\nQuestion:\nI'm using `replace` in vue to add `query` to the current url .\nand i assigned `undefined` if the value is not there.\n\n```\nthis.$router.replace({\n name: \"admin-frs\",\n query: {\n limit: this.pageSize,\n page: this.currentPage,\n sort: this.sortbyapi || undefined,\n language: this.sortbyapiLang || undefined,\n },\n})\n```\n\nthis makes the query item disappear from the URL when the query data is getting updated which is fine.\n\nit does not remove it from the query object.\n\nany idea if there's a better approach than this?\n\nplus is it possible to get the query as it is from the route? like `&limit=10...etc`\n\n========================================\n\nCode:\n```js\nthis.$router.replace({\n name: \"admin-frs\",\n query: {\n limit: this.pageSize,\n page: this.currentPage,\n sort: this.sortbyapi || undefined,\n language: this.sortbyapiLang || undefined,\n },\n})\n```\n\n```text\nreplace\n```\n\n```text\nquery\n```\n\n```text\nundefined\n```\n\n```text\n&limit=10...etc\n```\n\n```text\nlet query = $router.query;\n```\n\n```text\n// remove the limit\nif (!this.pageSize) delete query.limit;\n```\n\n```text\nlet query = {};\nif (this.pageSize) query.limit = this.pageSize;\nif (this.currentPage) query.page = this.currentPage;\n// etc for the other properties\n// query will now only have props for those selected above\n```\n\n```text\n$router.replace({ name: \"admin-frs\", query });\n```\n\n```text\nlet params = [];\nfor (let key in query)\n params.push(`${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`);\nconst queryString = params.join(\"&\");\n```\n\n```text\nrouter.replace\n```\n\n========================================\n\nComments:\n- I'm not sure what you're looking for here. Something like this? `/admin-frs?limit=3&page=1&sort=asc&language=fr` Remove what from the query object, also what does it mean?\n- Can you clarify: \"...and I assigned undefined\" if the value is not there. Assigned undefined to what? What value is not there? Then \"...it does not remove it from the query object\" What does not remove what?\n- @kissu lets say if `this.sortbyapi` is empty the `sort` in the `query` object` should disappear from the url and from the object\n- @danh I mean look at the assigned values in `query` object .. if one of them is empty i wanted to remove the key from the query. instead of returning `undefined` . my English is bad sorry I m trying my best to explain my problem.\n- I got your \"problem\". Let me try to see if I can find a *pretty* solution to this.\n- Nevermind, I did not get it. `undefined` is working fine, it is removing the query itself from the URL if it's falsy. This is working great as is from the looks of this video: i.imgur.com/tR2LSpy.mp4\n- @kissu yes this trick works for the url only .. but try to console log the `query` object. then key is still there as undefined. this is not what I'm aiming for only. the answer from @danh handled it pretty well\n- Oh, so the question was more about how to remove a key-value pair in an object if the value is falsy. Hence, with something like `pickBy` by lodash: lodash.com/docs/4.17.15#pickBy Or in a hand-made way like the given answer. The router was pretty useless in the story.\n- Not even sure why OP is asking this since it's already the default behavior and nothing needs to be done on top of it.\n- @kissu, I think that's what the OP needed to understand: that the router api doesn't concern itself with the manipulation of the query data, it just wants an object, and it's up to the caller and standard js to do the work.","metadata":{"transformedAt":"2026-08-18T18:33:07.901Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":104,"estimatedTokens":899}}888{"id":"stack-68847519","source":"stackoverflow","questionId":68847519,"title":"NuxtJS and Firebase Web SDK Beta v9: How to add realtime listener to firestore?","tags":["javascript","firebase","google-cloud-firestore","nuxt.js"],"text":"Title: NuxtJS and Firebase Web SDK Beta v9: How to add realtime listener to firestore?\nTags: javascript, firebase, google-cloud-firestore, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using the new Firebase Web SDK v9 (beta 8) with NuxtJS2. I have a child component that allows a user to edit his post data. This updates a document in Firestsore with the new post changes. However, my question is...how do I get have my parent component get realtime updates of this new data?\n\nLet me explain:\n\nI have the following example components structure in the app:\n\n```\n\n \n\n```\n\n`PostCardDetail.vue` script section where I am doing the data fetch:\n\n```\nimport { doc, getDoc } from 'firebase/firestore'\nimport { mapGetters } from 'vuex'\nimport { db } from '~/plugins/firebase'\nexport default {\n name: 'PostCardDetail',\n data() {\n return {\n post: {}\n }\n },\n async fetch() {\n const docRef = doc(db, 'posts', this.$route.params.postId)\n const docSnap = await getDoc(docRef)\n this.post = docSnap.data()\n },\n mounted () {\n // I believe I will need to mount the realtime listener here?\n },\n}\n\n```\n\nThe `PostEdit.vue` script section where I am doing the data editing:\n\n```\neditPost() {\n const postRef = doc(db, 'posts', this.post.id)\n await updateDoc(postRef, {\n ...editedPost,\n updatedAt: serverTimestamp()\n })\n console.log('updated!')\n this.$store.dispatch('edit', false)\n alert('Post successfully updated!')\n}\n```\n\nI am able to successfully edit the data, but to view the latest changes, I need to manually refresh the browser. How can I get automatic real time update with firestore after post is edited by user? I assume this listener will be in the mounted() hook property of `PostCardDetail`?\n\nMy attempt:\n\n```\nmounted() {\n // eslint-disable-next-line no-unused-vars\n const unsub = onSnapshot(\n doc(db, 'posts', this.$route.params.postId),\n (snapshot) => {\n this.post = snapshot.data()\n }\n )\n }\n```\n\nThis SEEMS to work OK, but feels a bit clunky. Is this the recommended way to approach this with NuxtJS?\n\n========================================\n\nCode:\n```text\n<PostCardDetail>\n <PostEdit />\n</PostCardDetail>\n```\n\n```text\nimport { doc, getDoc } from 'firebase/firestore'\nimport { mapGetters } from 'vuex'\nimport { db } from '~/plugins/firebase'\nexport default {\n name: 'PostCardDetail',\n data() {\n return {\n post: {}\n }\n },\n async fetch() {\n const docRef = doc(db, 'posts', this.$route.params.postId)\n const docSnap = await getDoc(docRef)\n this.post = docSnap.data()\n },\n mounted () {\n // I believe I will need to mount the realtime listener here?\n },\n}\n</script>\n```\n\n```text\neditPost() {\n const postRef = doc(db, 'posts', this.post.id)\n await updateDoc(postRef, {\n ...editedPost,\n updatedAt: serverTimestamp()\n })\n console.log('updated!')\n this.$store.dispatch('edit', false)\n alert('Post successfully updated!')\n}\n```\n\n```text\nmounted() {\n // eslint-disable-next-line no-unused-vars\n const unsub = onSnapshot(\n doc(db, 'posts', this.$route.params.postId),\n (snapshot) => {\n this.post = snapshot.data()\n }\n )\n }\n```\n\n```text\nPostCardDetail.vue\n```\n\n```text\nPostEdit.vue\n```\n\n```text\nPostCardDetail\n```\n\n```js\ncreated() {\n const unsub = onSnapshot(\n doc(db, 'posts', this.$route.params.postId),\n (snapshot) => {\n this.post = snapshot.data()\n }\n )\n}\n```\n\n```text\ncreated()\n```\n\n```text\nunsub\n```\n\n========================================\n\nComments:\n- Thanks. Don't I have to unsubscribe from it to save bandwidth if the component is no longer needed? For example, on page navigation away , should I unsubscribe somewhere?\n- @redshift yes you should.","metadata":{"transformedAt":"2026-08-18T18:33:07.901Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":168,"estimatedTokens":922}}889{"id":"stack-68523196","source":"stackoverflow","questionId":68523196,"title":"Environment variables not working on Vercel with Nuxt","tags":["javascript","amazon-web-services","vue.js","deployment","nuxt.js"],"text":"Title: Environment variables not working on Vercel with Nuxt\nTags: javascript, amazon-web-services, vue.js, deployment, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have issues accessing my environment variables deployed on Vercel.\n\nWhile testing the site on my laptop's `localhost`, it works perfectly, but it doesn't work once deployed to Vercel.\n\nI am trying to access the environment variables in my `components` and `plugins` directories, and I am accessing it using\n\n```\ncomputed: {\n config() {\n return{\n bucketName: process.env.AWS_BUCKET_NAME,\n dirName: process.env.AWS_DIR_NAME_1,\n region: process.env.AWS_REGION_1,\n accessKeyId: process.env.AWS_ID,\n secretAccessKey: process.env.AWS_SECRET,\n }\n }\n},\n```\n\nAll options were selected when adding my environment variables and they are exposed too\n\nhttps://i.sstatic.net/0JtFH.png\nhttps://i.sstatic.net/0RCPW.png\n\nPlease, what could be the issue?\n\nBased on the suggestion below, here is what I have tried\n\nin `nuxt.config.js`\n\n```\nprivateRuntimeConfig: {\n bucketName: process.env.AWS_BUCKET_NAME,\n dirName: process.env.AWS_DIR_NAME_1,\n region: process.env.AWS_REGION_1,\n accessKeyId: process.env.AWS_ID,\n secretAccessKey: process.env.AWS_SECRET,\n},\n```\n\nand in the plugin\n\n```\nimport Vue from 'vue'\nimport S3 from \"aws-s3\";\n\nexport default ({ $config: { bucketName, dirName, region, accessKeyId, secretAccessKey } }) => {\n Vue.mixin({\n methods:{\n async uploadToS3(file) {\n const config = {\n bucketName,\n dirName,\n region,\n accessKeyId,\n secretAccessKey,\n }\n console.log(bucketName, dirName, region, accessKeyId, secretAccessKey);\n\n const S3Client = new S3(config)\n let uploadedData = S3Client.uploadFile(file, this.getRandomName(30))\n return uploadedData\n }\n }\n })\n}\n```\n\nas I `console.log` the values, I do get `undefined`\n\nundefined undefined undefined undefined undefined\n\n========================================\n\nCode:\n```js\ncomputed: {\n config() {\n return{\n bucketName: process.env.AWS_BUCKET_NAME,\n dirName: process.env.AWS_DIR_NAME_1,\n region: process.env.AWS_REGION_1,\n accessKeyId: process.env.AWS_ID,\n secretAccessKey: process.env.AWS_SECRET,\n }\n }\n},\n```\n\n```js\nprivateRuntimeConfig: {\n bucketName: process.env.AWS_BUCKET_NAME,\n dirName: process.env.AWS_DIR_NAME_1,\n region: process.env.AWS_REGION_1,\n accessKeyId: process.env.AWS_ID,\n secretAccessKey: process.env.AWS_SECRET,\n},\n```\n\n```js\nimport Vue from 'vue'\nimport S3 from \"aws-s3\";\n\nexport default ({ $config: { bucketName, dirName, region, accessKeyId, secretAccessKey } }) => {\n Vue.mixin({\n methods:{\n async uploadToS3(file) {\n const config = {\n bucketName,\n dirName,\n region,\n accessKeyId,\n secretAccessKey,\n }\n console.log(bucketName, dirName, region, accessKeyId, secretAccessKey);\n\n const S3Client = new S3(config)\n let uploadedData = S3Client.uploadFile(file, this.getRandomName(30))\n return uploadedData\n }\n }\n })\n}\n```\n\n```text\nlocalhost\n```\n\n```text\ncomponents\n```\n\n```text\nplugins\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nconsole.log\n```\n\n```text\nundefined\n```\n\n```text\n.env\n```\n\n========================================\n\nComments:\n- thanks again for replying, I tried what you recommended but I get undefined, I have updated the question with what I have tried and the result\n- @OpeyemiOdedeyi I've talked about `publicRuntimeConfig` and not `privateRuntimeConfig` for a reason. Private is only to be used on the server (pure node.js functions, `nuxtServerInit` and alike). For your variables, you need to put them in the public variant. Because those will be available on the client, but you can only pass \"public\" env variables to the client. At the end of the day, those variables are not that secret because they are probably meant to be used by a frontend. For some variables that REALLY need to be private, you need a backend middleware or alike to hide those.","metadata":{"transformedAt":"2026-08-18T18:33:07.901Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":164,"estimatedTokens":986}}890{"id":"stack-68114979","source":"stackoverflow","questionId":68114979,"title":"Dynamically generate sitemap using @nuxtjs/sitemap","tags":["vue.js","nuxt.js","sitemap"],"text":"Title: Dynamically generate sitemap using @nuxtjs/sitemap\nTags: vue.js, nuxt.js, sitemap\nSource: Stack Overflow\n\nQuestion:\nI am using @nuxtjs/sitemap as my sitemap generator, some of the routes are given by ajax.\n\nI need it to have latest api data whenever someone visit /sitemap.xml, is it possible to do it with this library?\n\nMy config here in nuxt.config.js:\n\n```\n{\n sitemap: {\n defaults: {\n lastmod: new Date(),\n },\n routes: async () => {\n const { data } = await axios.get(\n 'https://jsonplaceholder.typicode.com/posts'\n )\n return data.map((post) => `/posts/${post.id}`)\n },\n\n cacheTime: 1,\n },\n}\n```\n\nWhen I activate my server and visit /sitemap.xml,\n\nit shows the latest routes with correct lastmod,\n\nbut after that it won't update again,\n\nhow can I do that?\n\n========================================\n\nCode:\n```js\n{\n sitemap: {\n defaults: {\n lastmod: new Date(),\n },\n routes: async () => {\n const { data } = await axios.get(\n 'https://jsonplaceholder.typicode.com/posts'\n )\n return data.map((post) => `/posts/${post.id}`)\n },\n\n cacheTime: 1,\n },\n}\n```\n\n```text\ntarget: static\n```\n\n```text\nyarn generate && yarn start\n```\n\n```text\ntarget: server\n```\n\n```text\nyarn build && yarn start\n```\n\n```text\ncacheTime\n```\n\n========================================\n\nComments:\n- Mr.kissu I think I figured it out. It happened because I stupidly set default: { lastmod: new Date() }, in my case I should wrap lastmod into axios call\n- e.g., return data.map((post) => ({ url: `/posts/${post.id}`, lastmod: new Date(), }))\n- Thank a lot, the `yarn generate`, instead of `yarn build` was crucial for me.","metadata":{"transformedAt":"2026-08-18T18:33:07.901Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":84,"estimatedTokens":411}}891{"id":"stack-69778906","source":"stackoverflow","questionId":69778906,"title":"Can't get data from api with axios in Nuxt components","tags":["vue.js","axios","nuxt.js","laravel-api","asyncdata"],"text":"Title: Can't get data from api with axios in Nuxt components\nTags: vue.js, axios, nuxt.js, laravel-api, asyncdata\nSource: Stack Overflow\n\nQuestion:\n```\n\n \n {{ data }}\n\n \n\nexport default {\n data () {\n return {\n data: ''\n }\n },\n async asyncData({$axios}) {\n const res = await $axios.get('/v1/posts')\n .catch( error => {\n console.log(\"response error\", error)\n return false\n })\n return {\n data: res\n }\n },\n}\n\n```\n\nAt first, I tried to get the data with the above code, it worked in pages/post.vue but not in components/post.vue.\nThen, I realized that I can't use asyncData in the nuxt components and changed the code as follows.\n\n```\n\n \n {{ data }}\n\n \n\nexport default {\n data () {\n return {\n data: ''\n }\n },\n mounted () {\n this.asyncData()\n },\n asyncData() {\n await axios.get('/v1/posts')\n .then(res => {\n this.data = res.data\n })\n },\n}\n\n```\n\nThen, I got a syntax error \"Unexpected reserved word 'await'\".\nHow can I get data via api in Nuxt components?\n\n===================================\n\nI read https://nuxtjs.org/docs/features/data-fetching#accessing-the-fetch-state and changed the code as below.\n\n```\n\nexport default {\n data () {\n return {\n data: ''\n }\n },\n async fetch() {\n this.data = await fetch('/v1/posts')\n .then(res => res.json())\n },\n}\n\n```\n\nAnd now, I'm stacking with another error 'Error in fetch(): SyntaxError: Unexpected token < in JSON at position 0'.\n\n========================================\n\nTop Answer:\nGlad that found a solution to your issue.\n\nYou can even use `this.$axios.$get` directly if you don't want to have to write `.data` afterwards.\n\n========================================\n\nCode:\n```html\n<template>\n <div id=\"post\">\n <p>{{ data }}</p>\n </div>\n</template>\n\n<script>\nexport default {\n data () {\n return {\n data: ''\n }\n },\n async asyncData({$axios}) {\n const res = await $axios.get('/v1/posts')\n .catch( error => {\n console.log(\"response error\", error)\n return false\n })\n return {\n data: res\n }\n },\n}\n</script>\n```\n\n```html\n<template>\n <div id=\"post\">\n <p>{{ data }}</p>\n </div>\n</template>\n\n<script>\nexport default {\n data () {\n return {\n data: ''\n }\n },\n mounted () {\n this.asyncData()\n },\n asyncData() {\n await axios.get('/v1/posts')\n .then(res => {\n this.data = res.data\n })\n },\n}\n</script>\n```\n\n```html\n<script>\nexport default {\n data () {\n return {\n data: ''\n }\n },\n async fetch() {\n this.data = await fetch('/v1/posts')\n .then(res => res.json())\n },\n}\n</script>\n```\n\n```html\n<script>\nexport default {\n data () {\n return {\n data: '',\n }\n },\n async fetch() {\n const res = await this.$axios.get('/v1/posts')\n this.data = res.data\n },\n}\n</script>\n```\n\n```text\nthis.$axios.$get\n```\n\n```text\n.data\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.901Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":190,"estimatedTokens":692}}892{"id":"stack-69223519","source":"stackoverflow","questionId":69223519,"title":"NuxtJS HighCharts Series data only updates once","tags":["nuxt.js"],"text":"Title: NuxtJS HighCharts Series data only updates once\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am currently using **nuxt-highcharts: 1.0.8** and **nuxt: 2.11.0**\n\nI have a basic series data below where I want it to update continuously using setInterval. My update is more on adding a single candle only then that single additional candle will always update. But after adding the first time, my chart will not change anymore.\n\n**(Not Working Properly)**\n\n```\n\n \n \n time: {{ time }}\n Click Here\n \n\nconst data = [\n [1318607760000, 421.07, 421.49, 420.7, 421.46],\n [1318607820000, 421.4601, 421.71, 421.36, 421.69],\n [1318607880000, 421.69, 421.94, 421.663, 421.94],\n [1318607940000, 421.94, 422, 421.8241, 422]\n];\n\nexport default {\n data() {\n return {\n time: 1318607940000,\n open: 421.94,\n high: 422,\n low: 421.8241,\n close: 422,\n chartOptions: {\n credits: { enabled: false },\n chart: {\n pinchType: \"xy\",\n zoomBySingleTouch: true,\n panning: { enabled: true, type: \"xy\" }\n },\n title: {\n text: \"BTC / USD\"\n },\n rangeSelector: {\n buttons: [\n {\n type: \"hour\",\n count: 1,\n text: \"1h\"\n },\n {\n type: \"hour\",\n count: 2,\n text: \"2h\"\n },\n {\n type: \"hour\",\n count: 4,\n text: \"4h\"\n },\n {\n type: \"hour\",\n count: 6,\n text: \"6h\"\n },\n {\n type: \"hour\",\n count: 12,\n text: \"12h\"\n },\n {\n type: \"day\",\n count: 1,\n text: \"1d\"\n }\n ],\n selected: 5,\n inputEnabled: false\n },\n navigator: { enabled: false },\n series: [\n {\n type: \"candlestick\",\n data,\n tooltip: {\n valueDecimals: 2\n },\n upColor: \"#3fbf4a\",\n upLineColor: \"#3fbf4a\",\n color: \"#e81010\"\n // pointStart: 1631631295000, // need 3 0s on the end from a UNIX timestamp\n // pointInterval: 4000 // The interval between data\n }\n ],\n time: { timezone: \"Asia/Singapore\" }\n }\n };\n },\n mounted() {\n const _this = this;\n setInterval(function() {\n _this.time += 60000;\n _this.open += 1;\n _this.high += 1;\n _this.low += 1;\n _this.close += 1;\n _this.updateChart([\n _this.time,\n _this.open,\n _this.high,\n _this.low,\n _this.close\n ]);\n }, 5000);\n },\n methods: {\n updateChart(number) {\n this.chartOptions.series = [\n {\n type: \"candlestick\",\n data: data.concat([number]),\n tooltip: {\n valueDecimals: 2\n },\n upColor: \"#3fbf4a\",\n upLineColor: \"#3fbf4a\",\n color: \"#e81010\"\n }\n ];\n }\n }\n};\n\n```\n\nI have another example but this is working where the chart always updates and the data is very much simpler.\n\n(**Working Example**)\n\n```\n\n \n \n time: {{ time }}\n Click Here\n \n\nconst data = [1, 2, 3, 4];\n\nexport default {\n data() {\n return {\n time: 1318607940000,\n open: 421.94,\n high: 422,\n low: 421.8241,\n close: 422,\n chartOptions: {\n credits: { enabled: false },\n chart: {\n pinchType: \"xy\",\n zoomBySingleTouch: true,\n panning: { enabled: true, type: \"xy\" }\n },\n title: {\n text: \"BTC / USD\"\n },\n rangeSelector: {\n buttons: [\n {\n type: \"hour\",\n count: 1,\n text: \"1h\"\n },\n {\n type: \"hour\",\n count: 2,\n text: \"2h\"\n },\n {\n type: \"hour\",\n count: 4,\n text: \"4h\"\n },\n {\n type: \"hour\",\n count: 6,\n text: \"6h\"\n },\n {\n type: \"hour\",\n count: 12,\n text: \"12h\"\n },\n {\n type: \"day\",\n count: 1,\n text: \"1d\"\n }\n ],\n selected: 5,\n inputEnabled: false\n },\n navigator: { enabled: false },\n series: [\n {\n type: \"candlestick\",\n data,\n tooltip: {\n valueDecimals: 2\n },\n upColor: \"#3fbf4a\",\n upLineColor: \"#3fbf4a\",\n color: \"#e81010\"\n }\n ],\n time: { timezone: \"Asia/Singapore\" }\n }\n };\n },\n mounted() {\n const _this = this;\n setInterval(function() {\n _this.open += 300;\n _this.updateChart(_this.open);\n }, 3000);\n },\n methods: {\n updateChart(number) {\n this.chartOptions.series = [\n {\n type: \"candlestick\",\n data: data.concat(number),\n tooltip: {\n valueDecimals: 2\n },\n upColor: \"#3fbf4a\",\n upLineColor: \"#3fbf4a\",\n color: \"#e81010\"\n }\n ];\n }\n }\n};\n\n```\n\nMy real goal is to continuously add candles for every interval but I want to get past this challenge first. But the end goal for this practice is to create a stock market data graph. I hope you can assist me, I have been trying for hours\n\n**You may replicate with my repository** is: https://github.com/infrastructure-playground/vuejs. Kindly setup w/ the steps below then visit localhost:3000/charts :\n\n```\n$ git clone -b feat/highcharts https://github.com/infrastructure-playground/vuejs.git\n$ cd vuejs\n$ npm install\n$ npm run dev\n```\n\n========================================\n\nCode:\n```html\n<template>\n <div>\n <highstock\n :options=\"chartOptions\"\n :update=\"['options.title', 'options.series']\"\n />\n time: {{ time }}\n <button @click=\"updateChart\">Click Here</button>\n </div>\n</template>\n\n<script>\nconst data = [\n [1318607760000, 421.07, 421.49, 420.7, 421.46],\n [1318607820000, 421.4601, 421.71, 421.36, 421.69],\n [1318607880000, 421.69, 421.94, 421.663, 421.94],\n [1318607940000, 421.94, 422, 421.8241, 422]\n];\n\nexport default {\n data() {\n return {\n time: 1318607940000,\n open: 421.94,\n high: 422,\n low: 421.8241,\n close: 422,\n chartOptions: {\n credits: { enabled: false },\n chart: {\n pinchType: \"xy\",\n zoomBySingleTouch: true,\n panning: { enabled: true, type: \"xy\" }\n },\n title: {\n text: \"BTC / USD\"\n },\n rangeSelector: {\n buttons: [\n {\n type: \"hour\",\n count: 1,\n text: \"1h\"\n },\n {\n type: \"hour\",\n count: 2,\n text: \"2h\"\n },\n {\n type: \"hour\",\n count: 4,\n text: \"4h\"\n },\n {\n type: \"hour\",\n count: 6,\n text: \"6h\"\n },\n {\n type: \"hour\",\n count: 12,\n text: \"12h\"\n },\n {\n type: \"day\",\n count: 1,\n text: \"1d\"\n }\n ],\n selected: 5,\n inputEnabled: false\n },\n navigator: { enabled: false },\n series: [\n {\n type: \"candlestick\",\n data,\n tooltip: {\n valueDecimals: 2\n },\n upColor: \"#3fbf4a\",\n upLineColor: \"#3fbf4a\",\n color: \"#e81010\"\n // pointStart: 1631631295000, // need 3 0s on the end from a UNIX timestamp\n // pointInterval: 4000 // The interval between data\n }\n ],\n time: { timezone: \"Asia/Singapore\" }\n }\n };\n },\n mounted() {\n const _this = this;\n setInterval(function() {\n _this.time += 60000;\n _this.open += 1;\n _this.high += 1;\n _this.low += 1;\n _this.close += 1;\n _this.updateChart([\n _this.time,\n _this.open,\n _this.high,\n _this.low,\n _this.close\n ]);\n }, 5000);\n },\n methods: {\n updateChart(number) {\n this.chartOptions.series = [\n {\n type: \"candlestick\",\n data: data.concat([number]),\n tooltip: {\n valueDecimals: 2\n },\n upColor: \"#3fbf4a\",\n upLineColor: \"#3fbf4a\",\n color: \"#e81010\"\n }\n ];\n }\n }\n};\n</script>\n```\n\n```html\n<template>\n <div>\n <highstock\n :options=\"chartOptions\"\n :update=\"['options.title', 'options.series']\"\n />\n time: {{ time }}\n <button @click=\"updateChart\">Click Here</button>\n </div>\n</template>\n\n<script>\nconst data = [1, 2, 3, 4];\n\nexport default {\n data() {\n return {\n time: 1318607940000,\n open: 421.94,\n high: 422,\n low: 421.8241,\n close: 422,\n chartOptions: {\n credits: { enabled: false },\n chart: {\n pinchType: \"xy\",\n zoomBySingleTouch: true,\n panning: { enabled: true, type: \"xy\" }\n },\n title: {\n text: \"BTC / USD\"\n },\n rangeSelector: {\n buttons: [\n {\n type: \"hour\",\n count: 1,\n text: \"1h\"\n },\n {\n type: \"hour\",\n count: 2,\n text: \"2h\"\n },\n {\n type: \"hour\",\n count: 4,\n text: \"4h\"\n },\n {\n type: \"hour\",\n count: 6,\n text: \"6h\"\n },\n {\n type: \"hour\",\n count: 12,\n text: \"12h\"\n },\n {\n type: \"day\",\n count: 1,\n text: \"1d\"\n }\n ],\n selected: 5,\n inputEnabled: false\n },\n navigator: { enabled: false },\n series: [\n {\n type: \"candlestick\",\n data,\n tooltip: {\n valueDecimals: 2\n },\n upColor: \"#3fbf4a\",\n upLineColor: \"#3fbf4a\",\n color: \"#e81010\"\n }\n ],\n time: { timezone: \"Asia/Singapore\" }\n }\n };\n },\n mounted() {\n const _this = this;\n setInterval(function() {\n _this.open += 300;\n _this.updateChart(_this.open);\n }, 3000);\n },\n methods: {\n updateChart(number) {\n this.chartOptions.series = [\n {\n type: \"candlestick\",\n data: data.concat(number),\n tooltip: {\n valueDecimals: 2\n },\n upColor: \"#3fbf4a\",\n upLineColor: \"#3fbf4a\",\n color: \"#e81010\"\n }\n ];\n }\n }\n};\n</script>\n\n<style lang=\"scss\" scoped></style>\n```\n\n```text\n$ git clone -b feat/highcharts https://github.com/infrastructure-playground/vuejs.git\n$ cd vuejs\n$ npm install\n$ npm run dev\n```\n\n```text\nupdateChart(number) {\n const updatedSeries = [\n {\n type: \"candlestick\",\n data: data.concat([number]),\n tooltip: {\n valueDecimals: 2\n },\n upColor: \"#3fbf4a\",\n upLineColor: \"#3fbf4a\",\n color: \"#e81010\"\n }\n ];\n Object.assign(this.chartOptions.series, updatedSeries)\n}\n```\n\n========================================\n\nComments:\n- Not sure if this applies to your example but you need to be aware that JavaScript do have some quirks when you're updating an array: vuejs.org/v2/guide/reactivity.html#For-Arrays Also, you need to keep in my that `data()` is static too, not sure if it can be better into a `computed()` here.\n- Keep which one in computed?\n- The one that you want to be reactive.\n- I tried before but it did not work. Would you like to try via code? I will make this question into a bounty if ever\n- Hi, do you have a minimal reproducible example or a public github link for this somewhere?\n- @DeanChristianArmada I can't reproduce the problem can you check here and provide steps to reproduce the issue\n- I will provide a public github link in a short while\n- Kindly check. I updated my question with my public repository\n- Can `vm.$forceUpdate()` or bind a key on `` component work?\n- @DengSihan even if this one works, it's still a rocket launcher solution with a lot of performance issues.\n- Hello, I appreciate your answer. Actually, I already fixed it here: github.com/richardeschloss/nuxt-highcharts/issues/36. But I will give the bounty to you since you are the only one who actually answered","metadata":{"transformedAt":"2026-08-18T18:33:07.901Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":546,"estimatedTokens":2777}}893{"id":"stack-69430941","source":"stackoverflow","questionId":69430941,"title":"Using CodeMirror with Vuejs/Nuxtjs results in error 'CodeMirror' is not defined when I the server reloads","tags":["javascript","vue.js","nuxt.js","codemirror","ui-codemirror"],"text":"Title: Using CodeMirror with Vuejs/Nuxtjs results in error 'CodeMirror' is not defined when I the server reloads\nTags: javascript, vue.js, nuxt.js, codemirror, ui-codemirror\nSource: Stack Overflow\n\nQuestion:\nI am implementing the `CodeMirror` to one of the textarea in my `Nuxtjs/Vuejs` application. I would like to beautify the `textarea` as per the `XML`.\n\nSometimes the `CodeMirror` works perfectly but sometimes when I reload the page I get the error:\n\n```\nTest.vue\n33:18 error 'CodeMirror' is not defined no-under\n```\n\nSo initially it works perfectly but when I try to make some changes to any file in the project and when the `Nuxtjs/Vuejs` server reloads again to incorporate the new changes then I get the error `error 'CodeMirror' is not defined`\n\nI am not understanding why do I get the error sometimes and I do not get it some other time. As I have added the required CDN and done the steps mentioned in various answers and articles, I would expect that it does not throw the error at all. Can someone please help me with this issue?\n\nSteps followed:\n\nAdded the CDN to my `nuxt-config.js`:\n`Scripts`:\n\n```\nscript: [\n {\n src:\"text/javascript\",\n src:\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.32.0/codemirror.min.js\"\n },\n {\n src:\"text/javascript\",\n src:\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.32.0/mode/xml/xml.min.js\"\n }\n ],\n```\n\n`CSS`:\n\n```\n{\n rel: \"stylesheet\",\n href:\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.1/codemirror.min.css\"\n}\n```\n\nFollowing is my `Test.vue`:\n\n```\n\n \n \n \n \n \n \n \n \n \n \n \n\nexport default {\n data () {\n return {\n xmlInput: ''\n }\n },\n methods: {\n convertToJSON () {\n console.log('ONE')\n const cm = CodeMirror.fromTextArea(document.getElementById('test'), {\n mode: 'application/xml',\n lineNumbers: true,\n matchBrackets: true,\n styleActiveLine: true,\n lineWrapping: true,\n tabSize: 2,\n value: 'console.log(\"Hello, World\");'\n })\n cm.setSize(500, 500)\n }\n }\n}\n\ntextarea {\n height: 78vh;\n white-space: nowrap;\n resize: both;\n}\n\n::-webkit-input-placeholder {\n color: #f1948a;\n text-align: center;\n}\n\n```\n\nCan someone please help me out with this issue? What am I doing wrong here? Any suggestions would be really appreciated. Thanks in advance.\n\nSandbox for re-creating issue:\nhttps://codesandbox.io/s/boring-water-g14zd?file=/pages/index.vue\n\nError in Sandbox:\nhttps://i.sstatic.net/tTTEq.png\n\n========================================\n\nCode:\n```text\nTest.vue\n33:18 error 'CodeMirror' is not defined no-under\n```\n\n```text\nscript: [\n {\n src:\"text/javascript\",\n src:\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.32.0/codemirror.min.js\"\n },\n {\n src:\"text/javascript\",\n src:\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.32.0/mode/xml/xml.min.js\"\n }\n ],\n```\n\n```text\n{\n rel: \"stylesheet\",\n href:\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.1/codemirror.min.css\"\n}\n```\n\n```text\n<template>\n <div>\n <div class=\"row\">\n <div class=\"col-md-5\">\n <div class=\"row\">\n <div class=\"col-md-12\">\n <textarea\n id=\"test\"\n v-model=\"xmlInput\"\n class=\"form-control\"\n placeholder=\"XML Document\"\n spellcheck=\"false\"\n data-gramm=\"false\"\n @input=\"convertToJSON()\"\n />\n </div>\n </div>\n </div>\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n data () {\n return {\n xmlInput: ''\n }\n },\n methods: {\n convertToJSON () {\n console.log('ONE')\n const cm = CodeMirror.fromTextArea(document.getElementById('test'), {\n mode: 'application/xml',\n lineNumbers: true,\n matchBrackets: true,\n styleActiveLine: true,\n lineWrapping: true,\n tabSize: 2,\n value: 'console.log(\"Hello, World\");'\n })\n cm.setSize(500, 500)\n }\n }\n}\n</script>\n\n<style scoped>\ntextarea {\n height: 78vh;\n white-space: nowrap;\n resize: both;\n}\n\n::-webkit-input-placeholder {\n color: #f1948a;\n text-align: center;\n}\n</style>\n```\n\n```text\nCodeMirror\n```\n\n```text\nNuxtjs/Vuejs\n```\n\n```text\ntextarea\n```\n\n```text\nXML\n```\n\n```text\nCodeMirror\n```\n\n```text\nNuxtjs/Vuejs\n```\n\n```text\nerror 'CodeMirror' is not defined\n```\n\n```text\nnuxt-config.js\n```\n\n```text\nScripts\n```\n\n```text\nCSS\n```\n\n```text\nTest.vue\n```\n\n```html\n<template>\n <div>\n <div class=\"row\">\n XML Dat\n <div class=\"col-md-5\">\n <div class=\"row\">\n <div class=\"col-md-12\">\n <textarea\n id=\"test\"\n v-model=\"xmlInput\"\n class=\"form-control\"\n placeholder=\"XML Document\"\n spellcheck=\"false\"\n data-gramm=\"false\"\n />\n </div>\n </div>\n </div>\n </div>\n </div>\n</template>\n```\n\n```js\nexport default {\n data() {\n return {\n xmlInput: \"\",\n };\n },\n mounted() {\n // https://stackoverflow.com/questions/53981928/using-codemirror-cannot-set-property-modeoption-of-undefined\n const editor = document.getElementById(\"test\");\n editor.value = \"\";\n /** eslint-next-line */\n const cm = CodeMirror.fromTextArea(editor, {\n mode: \"application/xml\",\n lineNumbers: true,\n matchBrackets: true,\n styleActiveLine: true,\n lineWrapping: true,\n tabSize: 2,\n value: 'console.log(\"Hello, World\");',\n });\n\n cm.setSize(500, 500);\n },\n};\n```\n\n```text\n@input=\"convertToJSON()\"\n```\n\n========================================\n\nComments:\n- This might help you - stackoverflow.com/questions/67360602/…\n- @MohibArshi Thanks a lot for your response. I tried that but it does not seem to work for me and the error still persists. I do not have any `type` parameter for my `Scripts` and `CSS` has been marked with `rel:stylesheet` so as per the answer this should work. But its not working for me. Can you please suggest me something?\n- There is a type property on nuxt scripts - `{ src: \"...\" type: \"text/javascript\" }`\n- @MohibArshi Thanks a lot for your response. I changed it to `type` but still getting the error. Initially, it worked but when I do force-load the page then it starts throwing the error again. It works sometimes and sometimes it does not work. Not sure what's going wrong here. Any help please?\n- @MohibArshi I tried few things and found out that the problem is happening when I make the changes to some files and when the `nuxtjs/Vuejs` reloads to adapt the changes that's when I get this error. So initially it works perfectly but when I try to make some changes to the file and when the `Nuxtjs/Vuejs` server reloads then I get the error `error 'CodeMirror' is not defined`\n- So I tested the code on codesandbox and initially it was throwing `'CodeMirror' is not defined` error. But i added `\"defer\": true` to the script and it seems to be working fine. Check this out - codesandbox.io/s/falling-cdn-5o0t6?file=/nuxt.config.js\n- @MohibArshi Thanks a lot for taking your time and checking the problem. Actually, for some reason, it still throws the same error for me in my application as well as in the Sandbox. For sandbox, In `Index.vue` file it shows `redline` below the `CodeMirror` and when I hover it shows `CodeMirror` is not defined. Also, in actual application throws the same error event after adding the `defer:true`. Can you please have a look and provide some solution to fix this? Sandbox: codesandbox.io/s/boring-water-g14zd?file=/pages/index.vue. I have also attached the error above.\n- Let us continue this discussion in chat.\n- Thanks a lot for your efforts and response. This is working as expected. You deserve the accepted answer :) Thanks a lot again for helping and have a nice day :)","metadata":{"transformedAt":"2026-08-18T18:33:07.901Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":306,"estimatedTokens":1927}}894{"id":"stack-68218994","source":"stackoverflow","questionId":68218994,"title":"How to access nuxt `$config` in Vuex state? Only access method is through store actions methods?","tags":["javascript","typescript","vue.js","nuxt.js","vuex"],"text":"Title: How to access nuxt `$config` in Vuex state? Only access method is through store actions methods?\nTags: javascript, typescript, vue.js, nuxt.js, vuex\nSource: Stack Overflow\n\nQuestion:\nI have used to dotenv library to use .env file, but I have to change runtimeConfig because I realized it was easy to expose my project secret key.\n\nIn my latest project, I have used nuxt \"^2.14\" and mode is SPA.\nSo I only use \"publicRuntimeConfig\" in nuxt.config.ts like that.\n\n.env\n\n```\nTest_BASE_URL:'https://test.org'\n```\n\nnuxt.config.ts\n\n```\nexport default {\n publicRuntimeConfig:{baseURL: proccess.env.Test_BASE_URL||''}\n}\n```\n\nI can use env like that in vue file.\n\nsample.vue\n\n```\n\nexport default {\n mounted(){\n console.log(this.$config.baseURL)\n }\n}\n\n```\n\nBut I couldn't use \"$config\" in store's state.\nI tried to write that but it always return \"undefied\"\n\nindex.ts\n\n```\nexport const state = (context) => ({\n url:context.$config\n})\n```\n\nI have referred the this guys solutions\nand changed state's value through the actions method.\nI have used SPA, so I made method like 'nuxtServerInit'as plugins.\n\nplugins/clientInit.ts\n\n```\nimport {Context} from \"@nuxt/types\";\n\nexport default function (context:Context) {\n context.store.dispatch('initEnvURL',context.$config)\n}\n```\n\nindex.ts\n\n```\ninterface State {\n testURL: string\n}\nconst state = () => ({\n testURL:''\n})\nconst mutations = {\n setTestURl(state:State,config:any) {\n state.testURL = config.baseURL\n}\nconst actions = {\n initEnvURL({commit},$config) {\n commit('setTestURl',$config)\n}\n}\nexport default {state,mutations,actions}\n```\n\nI success to change state value through actions methods above,\nbut I don't know why \"context\" can't use store/state objects directly.\nDoes anyone know how to use $config in store/state?\nor is it impossible only way to use $config through actions method like above?\n\n========================================\n\nTop Answer:\nIt does NOT show up through the type system even when using `@nuxt/types`.\n\nAccess it like this in `store/index.ts` or `store/module.ts`:\n\n```\nimport { ActionTree, MutationTree } from 'vuex'\n\nconst actions: ActionTree = {\n async yourActionName({ commit }, payload): Promise {\n try {\n let url = this.app.$config.baseURL + \"/path\"; // (url);\n\n commit(\"mutateState\", res.data);\n\n return;\n } catch (error) {\n // Error handling\n }\n },\n};\n```\n\nMy nuxt.config.js looks like:\n\n```\nexport default {\n...\n publicRuntimeConfig: {\n baseURL: process.env.BASE_URL || 'http://localhost:5000/api',\n }\n...\n};\n```\n\n========================================\n\nCode:\n```text\nTest_BASE_URL:'https://test.org'\n```\n\n```text\nexport default {\n publicRuntimeConfig:{baseURL: proccess.env.Test_BASE_URL||''}\n}\n```\n\n```text\n<script>\nexport default {\n mounted(){\n console.log(this.$config.baseURL)\n }\n}\n</script>\n```\n\n```text\nexport const state = (context) => ({\n url:context.$config\n})\n```\n\n```text\nimport {Context} from \"@nuxt/types\";\n\nexport default function (context:Context) {\n context.store.dispatch('initEnvURL',context.$config)\n}\n```\n\n```text\ninterface State {\n testURL: string\n}\nconst state = () => ({\n testURL:''\n})\nconst mutations = {\n setTestURl(state:State,config:any) {\n state.testURL = config.baseURL\n}\nconst actions = {\n initEnvURL({commit},$config) {\n commit('setTestURl',$config)\n}\n}\nexport default {state,mutations,actions}\n```\n\n```js\nnuxtServerInit({ store, config } ) {\n store.commit('UPDATE_BASE_URL', config.baseUrl)\n}\n```\n\n```text\nnuxtServerInit\n```\n\n```text\nimport { ActionTree, MutationTree } from 'vuex'\n\nconst actions: ActionTree<ModuleState, RootState> = {\n async yourActionName({ commit }, payload): Promise<void> {\n try {\n let url = this.app.$config.baseURL + \"/path\"; // <- config is accessed here.\n\n const res = await this.$axios.get<number>(url);\n\n commit(\"mutateState\", res.data);\n\n return;\n } catch (error) {\n // Error handling\n }\n },\n};\n```\n\n```text\nexport default {\n...\n publicRuntimeConfig: {\n baseURL: process.env.BASE_URL || 'http://localhost:5000/api',\n }\n...\n};\n```\n\n```text\n@nuxt/types\n```\n\n```text\nstore/index.ts\n```\n\n```text\nstore/module.ts\n```\n\n========================================\n\nComments:\n- Thank you for your answer! I really understand why $config couldn't use in store/state. I noticed I didn't understand about Nuxt lifecycle and vuex system. I really appreciate it! Thanks!!","metadata":{"transformedAt":"2026-08-18T18:33:07.901Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":238,"estimatedTokens":1094}}895{"id":"stack-73353561","source":"stackoverflow","questionId":73353561,"title":"Meta data keeps showing as \"## Build Setup\" for every page in Vuejs/Nuxt?","tags":["node.js","vue.js","nuxt.js","metadata"],"text":"Title: Meta data keeps showing as \"## Build Setup\" for every page in Vuejs/Nuxt?\nTags: node.js, vue.js, nuxt.js, metadata\nSource: Stack Overflow\n\nQuestion:\nI've added individual meta to every page following the Nuxt documentation but whenever I my links on social media, the meta just show this '## build setup'. Another issue is the same metadata is showing for every page. I read you need to put \"hids\" to have individual page meta but nothing seems to be working?\n\n**Index Meta:**\n\n```\n\nexport default {\n head: {\n title: 'Animal Crossing Portal | The Best Tier Lists for Animal Crossing',\n meta: [\n { property: 'og:description', hid: 'og:description', name: 'og:description', content: 'Vote monthly in Animal Crossing Tier Lists for New Horizons & Pocket Camp! Including Villager Tier Lists, Sanrio, Gyroids & more at Animal Crossing Portal!' },\n { name: 'twitter:title', hid: 'twitter:title', content: 'Animal Crossing Portal | The Best Tier Lists for Animal Crossing' },\n { name: 'twitter:description', hid: 'twitter:description', content: 'Vote monthly in Animal Crossing Tier Lists for New Horizons & Pocket Camp! Including Villager Tier Lists, Sanrio, Gyroids & more at Animal Crossing Portal!' },\n { name: 'twitter:card', hid: 'twitter:card', content: 'summary_large_image' },\n { name: 'twitter:image:src', hid: 'twitter:image:src', content: 'https://www.animalcrossingportal.com/images/meta.jpg' },\n { property: 'og:title', hid: 'og:title', name: 'og:title', content: 'Animal Crossing Portal | The Best Tier Lists for Animal Crossing' },\n { property: 'og:type', hid: 'og:type', content: 'website' },\n { property: 'og:site_name', hid: 'og:site_name', content: 'Animal Crossing Portal' },\n { property: 'og:url', hid: 'og:url', content: 'https://www.animalcrossingportal.com/' },\n { property: 'og:image', hid: 'og:image', content: 'https://www.animalcrossingportal.com/images/meta.jpg' }\n ],\n link: [\n {\n rel: 'canonical',\n href: 'https://www.animalcrossingportal.com/'\n }\n ]\n }\n}\n\n```\n\n**My nuxt.config.js file has:**\n\n```\nhead: {\n meta: [\n { name: 'viewport', content: 'width=device-width, initial-scale=1' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n }\n```\n\n========================================\n\nTop Answer:\nThe meta was actually lying inside of a `README.md` file, removing it from there fixed OP's issue!\n\n========================================\n\nCode:\n```html\n<script>\nexport default {\n head: {\n title: 'Animal Crossing Portal | The Best Tier Lists for Animal Crossing',\n meta: [\n { property: 'og:description', hid: 'og:description', name: 'og:description', content: 'Vote monthly in Animal Crossing Tier Lists for New Horizons & Pocket Camp! Including Villager Tier Lists, Sanrio, Gyroids & more at Animal Crossing Portal!' },\n { name: 'twitter:title', hid: 'twitter:title', content: 'Animal Crossing Portal | The Best Tier Lists for Animal Crossing' },\n { name: 'twitter:description', hid: 'twitter:description', content: 'Vote monthly in Animal Crossing Tier Lists for New Horizons & Pocket Camp! Including Villager Tier Lists, Sanrio, Gyroids & more at Animal Crossing Portal!' },\n { name: 'twitter:card', hid: 'twitter:card', content: 'summary_large_image' },\n { name: 'twitter:image:src', hid: 'twitter:image:src', content: 'https://www.animalcrossingportal.com/images/meta.jpg' },\n { property: 'og:title', hid: 'og:title', name: 'og:title', content: 'Animal Crossing Portal | The Best Tier Lists for Animal Crossing' },\n { property: 'og:type', hid: 'og:type', content: 'website' },\n { property: 'og:site_name', hid: 'og:site_name', content: 'Animal Crossing Portal' },\n { property: 'og:url', hid: 'og:url', content: 'https://www.animalcrossingportal.com/' },\n { property: 'og:image', hid: 'og:image', content: 'https://www.animalcrossingportal.com/images/meta.jpg' }\n ],\n link: [\n {\n rel: 'canonical',\n href: 'https://www.animalcrossingportal.com/'\n }\n ]\n }\n}\n</script>\n```\n\n```js\nhead: {\n meta: [\n { name: 'viewport', content: 'width=device-width, initial-scale=1' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n }\n```\n\n```text\nREADME.md\n```\n\n```text\nog:description\n```\n\n========================================\n\nComments:\n- Did you searched for a `build setup` in your project? Do you have something like that there?\n- Hey kissu thanks for replying, that was my first thought. Unfortunately there's nothing with that in my code\n- Got a public repo for that one?\n- Oh actually, there was an instance of it which slipped my grip! I was searching all files and found it in the read me file. thought nothing of it at the time as I thought it was just a read me! I removed it, and it works now. thanks so much!\n- I'm having the same problem, but cant find an empty build tag in my nuxt config file : do you remember what was your faulty config like ?","metadata":{"transformedAt":"2026-08-18T18:33:07.901Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":113,"estimatedTokens":1239}}896{"id":"stack-68483098","source":"stackoverflow","questionId":68483098,"title":"How to add a vanillaJS npm script to a Nuxt plugin?","tags":["javascript","amazon-web-services","vue.js","amazon-s3","nuxt.js"],"text":"Title: How to add a vanillaJS npm script to a Nuxt plugin?\nTags: javascript, amazon-web-services, vue.js, amazon-s3, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have an issue getting AWS S3 to save images straight to AWS S3.\n\nI tried to import the AWS package as a plugin but it doesn't work.\n\nI do have the following in my `nuxt.config.js`\n\n```\nplugins: [\n ...\n '~plugins/S3.js'\n],\n```\n\nin my `plugins/s3.js`\n\n```\nimport vue from \"vue\"\nimport S3 from \"aws-s3\";\nvue.use(S3)\n```\n\nand I try to use it in my file\n\n```\nconst S3Client = new S3(config)\nS3Client\n.uploadFile(file, this.getRandomName(10))\n.then(data => {\n console.log(data)\n})\n.catch(err => {\n console.log(err)\n})\n```\n\nI get the error\n\nmultiplephotoupload.vue?7624:110 Uncaught (in promise) ReferenceError: S3 is not defined\n\nIf I write it directly into my component, this is defined and working\n\n```\nimport S3 from \"aws-s3\";\n```\n\n========================================\n\nCode:\n```js\nplugins: [\n ...\n '~plugins/S3.js'\n],\n```\n\n```js\nimport vue from \"vue\"\nimport S3 from \"aws-s3\";\nvue.use(S3)\n```\n\n```js\nconst S3Client = new S3(config)\nS3Client\n.uploadFile(file, this.getRandomName(10))\n.then(data => {\n console.log(data)\n})\n.catch(err => {\n console.log(err)\n})\n```\n\n```js\nimport S3 from \"aws-s3\";\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nplugins/s3.js\n```\n\n```js\nimport S3 from 'aws-s3'\n\nexport default ({ _ }, inject) => {\n const config = {\n bucketName: 'myBucket',\n dirName: 'photos' /* optional */,\n region: 'eu-west-1',\n accessKeyId: 'ANEIFNENI4324N2NIEXAMPLE',\n secretAccessKey: 'cms21uMxçduyUxYjeg20+DEkgDxe6veFosBT7eUgEXAMPLE',\n s3Url: 'https://my-s3-url.com/' /* optional */,\n }\n inject('s3', new S3(config))\n}\n```\n\n```text\ns3.js\n```\n\n```text\nthis.$s3\n```\n\n========================================\n\nComments:\n- yes, I said it only works if I import it that way, and it defeats the purpose of using it as a plugin.\n- Do you need to use it globally on several places?\n- Just in three components\n- if you don't mind me asking, how would you use AWS S3 in your Nuxt app\n- @OpeyemiOdedeyi my backend team provided me a GraphQL query that gives me an upload URL.It expires pretty quickly and can be used only once, I use nuxt-dropzone to send the files there. Pretty flexible and does the job fine. But you can do it in a lot of ways IMO.","metadata":{"transformedAt":"2026-08-18T18:33:07.901Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":122,"estimatedTokens":582}}897{"id":"stack-68174642","source":"stackoverflow","questionId":68174642,"title":"how to keep user authenticated after refreshing the page in nuxtjs?","tags":["vue.js","nuxt.js","nuxt-auth"],"text":"Title: how to keep user authenticated after refreshing the page in nuxtjs?\nTags: vue.js, nuxt.js, nuxt-auth\nSource: Stack Overflow\n\nQuestion:\nI'm using laravel passport for API's and nuxt.js for frontend after a successful login if I refresh the page the user is not authenticated anymore and `loggedIn` returns false, its my first nuxt.js project so I have no idea how to deal with that, any advise is appreciated\n\n`login.vue`\n\n```\n\nimport { mapActions } from 'vuex'\n\nexport default {\n data() {\n return {\n email: \"\",\n password: \"\"\n }\n },\n methods:{\n async login(){\n const succesfulLogin = await this.$auth.loginWith('local', {\n data: {\n email: this.email,\n password: this.password\n },\n })\n this.$store.commit(\"saveUser\",succesfulLogin.data)\n this.$store.commit(\"saveToken\", succesfulLogin.data.token)\n\n if (succesfulLogin) {\n await this.$auth.setUser({\n email: this.email,\n password: this.password,\n })\n this.$router.push('/profile')\n }\n }\n }\n}\n\n```\n\n`store/index.js`\n\n```\nexport const state = () => ({\n user:{},\n token: \"\"\n})\n\nexport const mutations = {\n saveUser(state, payload) {\n state.user=payload;\n },\n saveToken(state, token) {\n state.token= token\n }\n \n}\nexport const actions = {\n saveUserAction({commit}, UserObject){\n commit('saveUser');\n },\n logoutUser({commit}){\n commit('logout_user')\n }\n}\nexport const getters = {\n getUser: (state) => {\n return state.user\n },\n isAuthenticated(state) {\n return state.auth.loggedIn\n },\n\n loggedInUser(state) {\n return state.user.user\n }\n}\n```\n\n**after a successful login**\nhttps://i.sstatic.net/FTbPu.png\n\n**after refreshing the page**\nhttps://i.sstatic.net/CrPql.png\n\n========================================\n\nTop Answer:\nYou can just use localStorage and implement it yourself e.g.:\n\n```\nsaveToken(state, token) {\n localStorage.setItem(\"authToken\", token);\n state.token= token\n },\n saveUser(state, payload) {\n localStorage.setItem(\"authUser\", payload);\n state.user=payload;\n },\n```\n\nAnd then retrieving the localStorage when initializing your store you need to do something like this:\n\n```\nexport const state = () => {\n const localUser = localStorage.getItem(\"authToken\")\n const localToken = localStorage.getItem(\"authUser\")\n let user = {}\n let token = \"\"\n if (localUser) user = localUser\n if (localToken) token = localToken\n return {\n user: user,\n token: token\n }\n}\n```\n\nAs @mbuechmann pointed out, be aware of the security risk when storing sensitive information in localStorage. Better to use cookies for tokens, but localStorage is the 'simple' solution.\n\nor use a package like nuxt-vuex-localstorage\n\n========================================\n\nCode:\n```html\n<script>\nimport { mapActions } from 'vuex'\n\nexport default {\n data() {\n return {\n email: \"\",\n password: \"\"\n }\n },\n methods:{\n async login(){\n const succesfulLogin = await this.$auth.loginWith('local', {\n data: {\n email: this.email,\n password: this.password\n },\n })\n this.$store.commit(\"saveUser\",succesfulLogin.data)\n this.$store.commit(\"saveToken\", succesfulLogin.data.token)\n\n if (succesfulLogin) {\n await this.$auth.setUser({\n email: this.email,\n password: this.password,\n })\n this.$router.push('/profile')\n }\n }\n }\n}\n</script>\n```\n\n```js\nexport const state = () => ({\n user:{},\n token: \"\"\n})\n\nexport const mutations = {\n saveUser(state, payload) {\n state.user=payload;\n },\n saveToken(state, token) {\n state.token= token\n }\n \n}\nexport const actions = {\n saveUserAction({commit}, UserObject){\n commit('saveUser');\n },\n logoutUser({commit}){\n commit('logout_user')\n }\n}\nexport const getters = {\n getUser: (state) => {\n return state.user\n },\n isAuthenticated(state) {\n return state.auth.loggedIn\n },\n\n loggedInUser(state) {\n return state.user.user\n }\n}\n```\n\n```text\nloggedIn\n```\n\n```text\nlogin.vue\n```\n\n```text\nstore/index.js\n```\n\n```js\nexport default async ({ app, store }) => {\n if (store?.$auth?.$state?.loggedIn) {\n if (!app.$cookies.get('gql.me_query_expiration')) {\n // do some middleware logic if you wish\n\n await app.$cookies.set('gql.me_query_expiration', '5min', {\n // maxAge: 20,\n maxAge: 5 * 60,\n secure: true,\n })\n }\n }\n}\n```\n\n```js\nrouter: {\n middleware: ['auth', 'global'],\n},\n```\n\n```js\nexport default ({ app }) => {\n const headersConfig = setContext(() => ({\n credentials: 'same-origin',\n headers: {\n Authorization: app.$cookies.get('auth._token.local'), // here\n },\n }))\n\n [...]\n}\n```\n\n```js\nauth: {\n localStorage: false, // REALLY not secure, so nah\n ...\n}\n```\n\n```text\nauth\n```\n\n```text\n/middleware/global.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ncookie-universal-nuxt\n```\n\n```text\n/login\n```\n\n```text\n/plugins/nuxt-apollo-config.js\n```\n\n```text\ngql.me_query_expiration\n```\n\n```text\nauth._token.local\n```\n\n```text\nauth\n```\n\n```text\nsecure\n```\n\n```text\nlocalStorage\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nsaveToken(state, token) {\n localStorage.setItem(\"authToken\", token);\n state.token= token\n },\n saveUser(state, payload) {\n localStorage.setItem(\"authUser\", payload);\n state.user=payload;\n },\n```\n\n```text\nexport const state = () => {\n const localUser = localStorage.getItem(\"authToken\")\n const localToken = localStorage.getItem(\"authUser\")\n let user = {}\n let token = \"\"\n if (localUser) user = localUser\n if (localToken) token = localToken\n return {\n user: user,\n token: token\n }\n}\n```\n\n========================================\n\nComments:\n- Localstorage is not a proper storage for sensitive data. This answer explains it in detail: stackoverflow.com/questions/3718349/html5-localstorage-secur‌​ity\n- @Laurens thanks, I just tried and unfortunately it didn't work, I just have now 'authToken' with a token in local storage but still with refreshing user is no more authenticated\n- @AIB this is not the entire solution, you also must retrieve the localStorage with `localStorage.getItem` when initializing the store, read up on how localStorage works\n- @mbuechmann While you are correct that localstorage is not the safest way, if you have an xss vulnerability, you have bigger problems. Read pragmaticwebsecurity.com/articles/oauthoidc/…. But the best way would be to use cookies instead of localstorage. You can do this with the nuxt/auth module: auth.nuxtjs.org/schemes/cookie\n- @ Laurens is using cookies in this case works with laravel passport or it is irrelevant to the backend?\n- thanks, is using cookies in this case irrelevent to the backend? because I'm using laravel passport for authentication in the backend?\n- @AIB you can use whatever you want (cookie or `localStorage`) on the client to my knowledge, since this one is generated by yourself and not your actual backend.","metadata":{"transformedAt":"2026-08-18T18:33:07.901Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":339,"estimatedTokens":1705}}898{"id":"stack-68166584","source":"stackoverflow","questionId":68166584,"title":"How to handle setInterval in Nuxt","tags":["javascript","vue.js","nuxt.js","setinterval"],"text":"Title: How to handle setInterval in Nuxt\nTags: javascript, vue.js, nuxt.js, setinterval\nSource: Stack Overflow\n\nQuestion:\nI have a timer in my component, which is running with `setInterval` that starts in `mounted()` component.\n\nSuppose this component is at `http://localhost:3000/some-route`.\n\nNow how do I do `clearInterval()` whenever I go to another route like `http://localhost:3000/` as I want to stop the timer.\n\nI've used `unmounted()` but when you go to different route, the component doesn't unmounts but if I go to same route (`/some-route`), `setInterval` runs again as the component is mounted again.\n\nSo, how do I clear the interval every time I go to different route?\n\n========================================\n\nCode:\n```text\nsetInterval\n```\n\n```text\nmounted()\n```\n\n```text\nhttp://localhost:3000/some-route\n```\n\n```text\nclearInterval()\n```\n\n```text\nhttp://localhost:3000/\n```\n\n```text\nunmounted()\n```\n\n```text\n/some-route\n```\n\n```text\nsetInterval\n```\n\n```js\nactionSetPolling({ state, dispatch }) {\n try {\n const myPolling = setInterval(async function () {\n if (someVariable !== 'COMPLETED') {\n // do stuff\n } else if (conditionToStop) {\n // this is facultative, but can be done here so far too\n window.clearInterval(myPolling)\n }\n }, 2000)\n dispatch('setPollingId', myPolling)\n } catch (error) {\n console.warn('error during polling', error.response)\n window.clearInterval(state.pollingId)\n }\n}\n```\n\n```js\nbeforeDestroy() {\n window.clearInterval(state.pollingId)\n},\n```\n\n```text\nthis\n```\n\n```text\nsetPollingId\n```\n\n```text\npollingId\n```\n\n```text\nsetInterval\n```\n\n========================================\n\nComments:\n- To my knowledge, `unmounted()` does not exist. vuejs.org/v2/guide/instance.html#Lifecycle-Diagram\n- OMG. Yes the problem was I was using umounted() which is actually in vuejs 3.0 and not in nuxt which I think uses vuejs 2.0 lifecycle hooks. Anyways I have successfully cleared the interval in destroyed(). Thanks for the answer.\n- @ZaeemKhaliq yep, Nuxt is currenly only available in it's Vue2 form. Nuxt3 (with Vue3) support is coming soon.","metadata":{"transformedAt":"2026-08-18T18:33:07.901Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":97,"estimatedTokens":532}}899{"id":"stack-58450894","source":"stackoverflow","questionId":58450894,"title":"Can't select element generated by third-party Vue plugin","tags":["vue.js","owl-carousel","nuxt.js"],"text":"Title: Can't select element generated by third-party Vue plugin\nTags: vue.js, owl-carousel, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Owl Carousel for Vue. It doesn't seem to work properly since all carousel items are visible in their global container, which is several screens wide (there's no `overflow: hidden` or any `max-width` to make only x items visible at a time).\n\nAnyway I find myself forced to apply some `container` class to a wrapper that the plugin generates dynamically. To that end I do:\n\n```\nmounted () {\n this.$nextTick(() => {\n document.querySelector('.owl-carousel').classList.add('container')\n })\n}\n```\n\nBut, `querySelector('.owl-carousel')` is `null` although I see it in the DOM.\n\nHow can I successfully select it?\n\n========================================\n\nCode:\n```text\nmounted () {\n this.$nextTick(() => {\n document.querySelector('.owl-carousel').classList.add('container')\n })\n}\n```\n\n```text\noverflow: hidden\n```\n\n```text\nmax-width\n```\n\n```text\ncontainer\n```\n\n```text\nquerySelector('.owl-carousel')\n```\n\n```text\nnull\n```\n\n```text\n<div :id=\"elementHandle\" :class=\"['owl-carousel', 'owl-theme', 'your-class-here']\">\n```\n\n```text\nnpm install <git repo url>\n```\n\n========================================\n\nComments:\n- Are you using `ssr/nuxt`? Could you show `nuxt.config.js`?\n- Is `.owl-carousel` part of the shadow DOM?\n- Did you try to select element using $refs ? vuejs.org/v2/guide/…\n- Interesting workaround! Why a high number of props is a bad thing though? Do you think this package is poorly made and recommend against using it altogether?\n- @drake035 I think this should be a directive so you add it like ``, and it will stay reactive instead of a mounted one timer. Tons of props kinda feels very abstract. Btw you can also vuejs.org/v2/api/#Vue-extend this component - with your own template ;) - also mixin jquery into vue kinda feels like a overhead\n- @drake035 so yeah owlCarousel is dead - check github ;) it suggest to switch to tiny slider 2 here vue version: github.com/viktorlarsson/vue-tiny-slider based on vanilla - no jquery\n- Argh I wanted to grant you bounty but it just expired, really sorry!!","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":70,"estimatedTokens":544}}900{"id":"stack-66978964","source":"stackoverflow","questionId":66978964,"title":"How to dynamic call the axios method in VueJS/NuxtJs","tags":["javascript","vue.js","vuejs2","axios","nuxt.js"],"text":"Title: How to dynamic call the axios method in VueJS/NuxtJs\nTags: javascript, vue.js, vuejs2, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to optimize my code. So, I dynamically use the axios function, but the returned response is a pending `console log`. I am using `async/await`. Any one can help me for this.\n\nThis is my code:\n\n```\nmethods: {\n getAgentsNames() {\n const data = this.callAxios('get', `/getAllAgents`)\n console.log(data) // returns pending\n this.agents = data.listings\n },\n\n async callAxios(method, url, paramsBody = null) {\n try {\n const response = await this.$axios({\n method,\n url,\n params: paramsBody,\n headers: this.headers,\n })\n console.log(response) // success and have response data.\n if (response.data.status == 'ok') {\n return response.data\n } else {\n ifNotOK(response, this.$cookies)\n return null\n }\n } catch (error) {\n console.log(error)\n return null\n }\n },\n},\n```\n\n========================================\n\nCode:\n```js\nmethods: {\n getAgentsNames() {\n const data = this.callAxios('get', `/getAllAgents`)\n console.log(data) // returns pending\n this.agents = data.listings\n },\n\n async callAxios(method, url, paramsBody = null) {\n try {\n const response = await this.$axios({\n method,\n url,\n params: paramsBody,\n headers: this.headers,\n })\n console.log(response) // success and have response data.\n if (response.data.status == 'ok') {\n return response.data\n } else {\n ifNotOK(response, this.$cookies)\n return null\n }\n } catch (error) {\n console.log(error)\n return null\n }\n },\n},\n```\n\n```text\nconsole log\n```\n\n```text\nasync/await\n```\n\n```text\nasync getAgentsNames() {\n let data = await this.callAxios(\n```\n\n========================================\n\nComments:\n- thanks its work,. i can optimize the code now","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":91,"estimatedTokens":468}}901{"id":"stack-67918834","source":"stackoverflow","questionId":67918834,"title":"Can you mix up Client rendering and Server rendering for components in Nuxt.js similar to Next.js?","tags":["vue.js","nuxt.js"],"text":"Title: Can you mix up Client rendering and Server rendering for components in Nuxt.js similar to Next.js?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn Next.js you can have one component Static Side Rendered or Server Side Rendered and another component Client Side Rendered on the same page. Can you do the same in Nuxt.js? It seems I cannot find a proper answer.\n\n========================================\n\nTop Answer:\nHybrid Rendering is coming soon to Nuxt 3, as the documentation mentions now: https://v3.nuxtjs.org/guide/concepts/rendering/#hybrid-rendering\n\nAnd there is also a GitHub discussion about that topic as well: https://github.com/nuxt/framework/discussions/560\n\n========================================\n\nCode:\n```text\n<client-only>\n```\n\n```text\n<server-only>\n```\n\n========================================\n\nComments:\n- It seems the question refers to a hybrid mode where you can have both SSG and SSR for the website. nextjs.org/docs/advanced-features/automatic-static-optimizat‌​ion. Nuxt does not have hybrid mode IIRC. It is either SSG or SSR.\n- @Kunukn really good point. We need to see what OP meant here but yeah, there is no SSG + SSR combo in Nuxt to my knowledge neither. Not sure if Nuxt Nitro will do that, it is more for Edge Rendering (SSR on serverless as I've understood).\n- Hi @vjori, any updates on what are you looking for?\n- @kissu Equivalent features of Next.js in Nuxt.js. In Next.js you can mix up 4 modes of rendering in a single page. I was wondering if Nuxt.js supported this feature for us that like Vue.js more than React.js.\n- Can you update your question with more details of the 4 modes? Also, are them available all at the same time?","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":33,"estimatedTokens":426}}902{"id":"stack-66735144","source":"stackoverflow","questionId":66735144,"title":"Cannot import ES modules with \"node\" command in my Nuxt project","tags":["node.js","vue.js","ecmascript-6","nuxt.js","babeljs"],"text":"Title: Cannot import ES modules with \"node\" command in my Nuxt project\nTags: node.js, vue.js, ecmascript-6, nuxt.js, babeljs\nSource: Stack Overflow\n\nQuestion:\n- My nuxt project uses `serverMiddleware` defined in `nuxt.config.js` as serverMiddleware: `['~/api']`\n\n- All the files inside my api directory use import and export statements and work perfectly when I run `npm run dev`\n\n- I also have a seeders directory which contains a bunch of database seeder files with each one having `import` and `export` statements\n\n- When I run it from `package.json` with `\"seed:dev\": \"cross-env NODE_ENV=development node ./api/db/seeders\"`,\n\nI get the following error\n\n```\n(node:12212) Warning: To load an ES module, set \"type\": \"module\" in the package.json or use the .mjs extension.\n/Users/zup/Desktop/code/ACTIVE/ch_v3_final/api/db/seeders/index.js:1\nimport feeds from './feeds-data'\n^^^^^^\n\nSyntaxError: Cannot use import statement outside a module\n at wrapSafe (internal/modules/cjs/loader.js:915:16)\n at Module._compile (internal/modules/cjs/loader.js:963:27)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)\n at Module.load (internal/modules/cjs/loader.js:863:32)\n at Function.Module._load (internal/modules/cjs/loader.js:708:14)\n at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)\n at internal/main/run_main_module.js:17:47\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\nnpm ERR! ch@1.0.0 seed:dev: `cross-env NODE_ENV=development node ./api/db/seeders`\nnpm ERR! Exit status 1\nnpm ERR! \nnpm ERR! Failed at the ch@1.0.0 seed:dev script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /Users/zup/.npm/_logs/2021-03-21T16_38_58_766Z-debug.log\n```\n\nHow do I run the database seeders which use import export statements the way nuxt runs my other files?\n\n========================================\n\nCode:\n```text\n(node:12212) Warning: To load an ES module, set \"type\": \"module\" in the package.json or use the .mjs extension.\n/Users/zup/Desktop/code/ACTIVE/ch_v3_final/api/db/seeders/index.js:1\nimport feeds from './feeds-data'\n^^^^^^\n\nSyntaxError: Cannot use import statement outside a module\n at wrapSafe (internal/modules/cjs/loader.js:915:16)\n at Module._compile (internal/modules/cjs/loader.js:963:27)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)\n at Module.load (internal/modules/cjs/loader.js:863:32)\n at Function.Module._load (internal/modules/cjs/loader.js:708:14)\n at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)\n at internal/main/run_main_module.js:17:47\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\nnpm ERR! ch@1.0.0 seed:dev: `cross-env NODE_ENV=development node ./api/db/seeders`\nnpm ERR! Exit status 1\nnpm ERR! \nnpm ERR! Failed at the ch@1.0.0 seed:dev script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /Users/zup/.npm/_logs/2021-03-21T16_38_58_766Z-debug.log\n```\n\n```text\nserverMiddleware\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n['~/api']\n```\n\n```text\nnpm run dev\n```\n\n```text\nimport\n```\n\n```text\nexport\n```\n\n```text\npackage.json\n```\n\n```text\n\"seed:dev\": \"cross-env NODE_ENV=development node ./api/db/seeders\"\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\npackage.json\n```\n\n```text\n14.16.0\n```\n\n========================================\n\nComments:\n- you can use `require` syntax here. `const feed = require('./feeds-data');`\n- it refers to other files like db, which is full of import and export statements, it still gives the error, db file contains core database logic which is part of the application\n- this is related to nuxt because because the files that are a part of nuxt run without issues, for example here is a demo repo i setup github.com/slidenerd/nuxt-ws-content-bug everything works well here when you run npm run dev but if i have seeders in my database that i run from package.json they dont work with import and export, problem is my seeders refer to other files that run with nuxt (with no problems on import export statements)\n- The thing that is buggy is `cross-env NODE_ENV=development node ./api/db/seeders`, hence the `node` in it and the error which is 100% related to node. All the remaining code is working great. So if your using Nuxt, hosting on AWS, having a cloudinary or hashing thanks to bcrypt, it's not relevant here (also, Nuxt is working great).","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":123,"estimatedTokens":1144}}903{"id":"stack-58534989","source":"stackoverflow","questionId":58534989,"title":"How to fix 404 error when communicate with API","tags":["javascript","laravel","nuxt.js"],"text":"Title: How to fix 404 error when communicate with API\nTags: javascript, laravel, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using nuxt.js *(frontend)* and laravel6 *(backend)* API. Laravel app is running `http://172.16.10.86:8000` port and nuxt.js app is running `http://localhost:3000`. I want to send data in my MySQL database using nuxt.js app. When I send `POST` request from my nuxt.js app it redirects properly but does not insert any data in database. Inside network tab, I found a 404 error.\n\n```\nmethods:{\n async register(){\n try {\n await this.$axios.post('/auth/register',this.form);\n } catch(e) {\n return;\n }\n\n this.$auth.login({data: this.form});\n\n this.$router.push({name:'index'});\n }\n```\n\nnuxt.config.js\n\n```\nauth: {\n strategies: { \n local: { \n endpoints:{\n login:{\n url: '/auth/login',method: 'post', propertyName: 'token'\n },\n user:{\n url:'me', method: 'get', propertyName: 'data'\n },\n logout:{\n url:'logout', method: 'get'\n }\n }\n } \n },\n axios:{\n baseUrl:'http://172.16.10.86:8000/api'\n },\n```\n\n========================================\n\nTop Answer:\nYou need to add full URL for the API server.\n\n```\nmethods:{\n async register() {\n try {\n await this.$axios.post('http://172.16.10.86:8000/api/auth/register', this.form);\n } catch(e) {\n return;\n }\n\n this.$auth.login({data: this.form});\n\n this.$router.push({name:'index'});\n }\n```\n\n========================================\n\nCode:\n```text\nmethods:{\n async register(){\n try {\n await this.$axios.post('/auth/register',this.form);\n } catch(e) {\n return;\n }\n\n this.$auth.login({data: this.form});\n\n this.$router.push({name:'index'});\n }\n```\n\n```text\nauth: {\n strategies: { \n local: { \n endpoints:{\n login:{\n url: '/auth/login',method: 'post', propertyName: 'token'\n },\n user:{\n url:'me', method: 'get', propertyName: 'data'\n },\n logout:{\n url:'logout', method: 'get'\n }\n }\n } \n },\n axios:{\n baseUrl:'http://172.16.10.86:8000/api'\n },\n```\n\n```text\nhttp://172.16.10.86:8000\n```\n\n```text\nhttp://localhost:3000\n```\n\n```text\nPOST\n```\n\n```text\nbaseURL\n```\n\n```text\nbaseUrl\n```\n\n```text\nmethods:{\n async register() {\n try {\n await this.$axios.post('http://172.16.10.86:8000/api/auth/register', this.form);\n } catch(e) {\n return;\n }\n\n this.$auth.login({data: this.form});\n\n this.$router.push({name:'index'});\n }\n```\n\n========================================\n\nComments:\n- You know 404 means that the URL wasn't found?\n- thanks for your comment. where i made mistake ??\n- Can you post the screenshot of your Network Tab?","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":147,"estimatedTokens":663}}904{"id":"stack-57879848","source":"stackoverflow","questionId":57879848,"title":"Conditional state based on the route","tags":["vue.js","vuex","nuxt.js"],"text":"Title: Conditional state based on the route\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a Vuex state property that stores a boolean that I use to determine whether to show or hide the nav bar. For all pages except the landing page the nav bar should appear so I set the default value to true.\n\n```\nexport const state = () => ({\n showNav: true\n})\n```\n\nThen I have a mutation for toggling that.\n\n```\nexport const mutations = {\n toggleNav (state, show) {\n state.showNav = show\n }\n}\n```\n\nIn my landing page, I have a call to `toggleNav` to turn off the nav bar.\n\n```\nexport default {\n mounted () {\n this.$store.commit('toggleNav', false)\n }\n}\n```\n\nThis works as expected with one big problem; When I refresh the landing page I see the nav bar for a brief second until mounted() gets called.\n\nIs there some way to hide the nav bar such that it doesn't briefly appear? I realized I could default `showNav` to `false` and then call `this.$store.commit('toggleNav', true)` on every page but that seems unwieldy.\n\nEDIT: The nav bar is itself its own component.\n\nEDIT 2: I forgot to add that I need to be able to dynamically show the nav bar when `scrollY` exceeds a certain value and then hide it again when `scrollY` returns below that value. My apologies to everyone who answered for not being clearer about this.\n\n========================================\n\nTop Answer:\nRather than relying on state mutation, this had probably best be done during design-time by including a `meta` field when defining the routes. Something like `meta.showNavBar`. For example:\n\n### routes.js\n\n```\nexport default [\n {\n // The landing page\n path: '/welcome',\n name: 'Welcome',\n meta: {\n showNavbar: false\n },\n component: () => import('@/views/Welcome')\n },\n\n {\n path: '/',\n name: 'Homepage',\n meta: {\n // Don't worry about this since we'll take care of it with a computed property.\n // showNavbar: true\n },\n component: () => import('@/views/Home')\n },\n\n {\n // ...\n }\n]\n```\n\n### SomeComponent.vue\n\n```\n\n \n\n export default {\n computed: {\n showNavbar() {\n const { showNavbar } = this.$route.meta;\n\n return showNavbar || typeof showNavbar === 'undefined';\n }\n }\n }\n\n```\n\nAlternatively, you could call it `meta.hideNavbar`, set it to `true` for the landing page and coerce its value to boolean with double-negation operator (`!!`) -- which will default to `false` when not set or left `undefined`, from here, you could simply do:\n\n```\n\n```\n\n========================================\n\nCode:\n```text\nexport const state = () => ({\n showNav: true\n})\n```\n\n```text\nexport const mutations = {\n toggleNav (state, show) {\n state.showNav = show\n }\n}\n```\n\n```text\nexport default {\n mounted () {\n this.$store.commit('toggleNav', false)\n }\n}\n```\n\n```text\ntoggleNav\n```\n\n```text\nshowNav\n```\n\n```text\nfalse\n```\n\n```text\nthis.$store.commit('toggleNav', true)\n```\n\n```text\nscrollY\n```\n\n```text\nscrollY\n```\n\n```text\n/* store/index.js */\nexport const store = () => ({\n showNav: true\n});\n\nexport const mutations = {\n toggleNav(state, bool){\n state.showNav = bool;\n }\n}\n\n\n/* middleware/toggleNavMiddleware.js */\nexport default function(context){\n const { route, store } = context;\n store.commit('toggleNav', route.path === /* your landing page path */);\n}\n\n\n/* layouts/default.vue (assuming this is the target) */\n/* you can also use it in pages/*.vue */\nexport default {\n middleware: ['toggleNavMiddleware'],\n}\n\n\n/* components/NavBar.vue */\n<template>\n <nav v-if=\"$store.state.showNav\">\n <!-- content here -->\n </nav>\n</template>\n```\n\n```js\nexport default [\n {\n // The landing page\n path: '/welcome',\n name: 'Welcome',\n meta: {\n showNavbar: false\n },\n component: () => import('@/views/Welcome')\n },\n\n {\n path: '/',\n name: 'Homepage',\n meta: {\n // Don't worry about this since we'll take care of it with a computed property.\n // showNavbar: true\n },\n component: () => import('@/views/Home')\n },\n\n {\n // ...\n }\n]\n```\n\n```text\n<template>\n <navbar v-if=\"showNavbar\"></navbar>\n</template>\n\n<script>\n export default {\n computed: {\n showNavbar() {\n const { showNavbar } = this.$route.meta;\n\n return showNavbar || typeof showNavbar === 'undefined';\n }\n }\n }\n</script>\n```\n\n```text\n<navbar v-if=\"!!$route.meta.hideNavbar\"></navbar>\n```\n\n```text\nmeta\n```\n\n```text\nmeta.showNavBar\n```\n\n```text\nmeta.hideNavbar\n```\n\n```text\ntrue\n```\n\n```text\n!!\n```\n\n```text\nfalse\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- Try using the `created` hook since it is earlier in the lifecycle...or perhaps a re-purposed navigation guard if you're using vue-router (make the commit within the `beforeRouteEnter` guard).\n- @zer0kompression Neither of those work. I think these still happen too late in the lifecycle.\n- How about using `v-if` on the navbar component based on the current route? So something like ``.\n- @zer0kompression See my second edit. I actually did have `v-if=\"$route.path !== '/landing-page-path'\"` at one point but I couldn't get the nav bar to dynamically appear again after the page had loaded.\n- This doesn't work. I'm guessing because I'm using NuxtJS instead of pure Vue?\n- The basic idea can be implemented with a middleware component (Nuxt)\n- @DarrellBrogdon Not quite sure about how it is different from the NuxtJs version, but yes this minimal setup usually suffices for me. I'm not working with NuxtJs myself, so. Glad you found the answer though.\n- @DarrellBrogdon I have tested it myself and it works just fine. So please show/explain more of your code or let me know how you implemented it instead?.\n- `export default function` has a syntax error (unnecessary trailing parenthesis) and, correct me if I'm wrong but `$store.state.showNav` should reference `toggleNav` instead of `showNav`, no? I should clarify that if I fix those problems then the nav bar does disappear but (and this is my fault for not being clear in my question) I'm unable to dynamically get the nav bar to appear after the page has loaded. I need to, in effect, call `store.commit('toggleNav', true)` when the user scrolls to the top of the page and have the nav appear again.\n- @DarrellBrogdon Corrected the trailing parenthesis. Based on your snippet, it should reference `$store.state.showNav` because that's what is exposed in `state = () => ({ showNav: true })`. `toggleNav` is in mutations so it shouldn't be reference and can only be committed. Can you update your question to make it clearer? To clarify, nav bar should disappear on load, but reappear again should the user scrolls to the top, correct?\n- Yes, thank you for clarifying. After implementing that it does work as expected.\n- @DarrellBrogdon glad it helped.","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":277,"estimatedTokens":1688}}905{"id":"stack-67813655","source":"stackoverflow","questionId":67813655,"title":"Cypress not recognizing my imported module from outside /cypress directory","tags":["javascript","nuxt.js","integration-testing","cypress"],"text":"Title: Cypress not recognizing my imported module from outside /cypress directory\nTags: javascript, nuxt.js, integration-testing, cypress\nSource: Stack Overflow\n\nQuestion:\nI am trying to import a module from a file outside my /cypress directory into the /cypress/integration directory's test.spec.js file like so:\n\n```\nimport { LAB_MODEL } from '../../models/search/lab-model';\n```\n\nBut inside this imported module \"LAB_MODEL\" there are other files being imported using the \"@@\" at the start of the file imports like\n\n```\nimport ExperimentDetails from \"@@/components/experiment/ExperimentDetails\";\n```\n\nand I think this is why Cypress isn't working and giving me this error:\n\n```\nError: Webpack Compilation Error\n./models/search/lab-model.js\nModule not found: Error: Can't resolve '@@/components/experiment/ExperimentDetails' in '/Users/hidden/models/search'\nresolve '@@/components/experiment/ExperimentDetails' in '/Users/hidden/models/search'\n Parsed request is a module\n using description file: /Users/hidden/package.json (relative path: ./models/search)\n Field 'browser' doesn't contain a valid alias configuration\n resolve as module\n```\n\nSo I think this is the reason why my test won't run, but I have no idea how to make Cypress recognize \"@@\" imports and can't find any documentation/stackoverflow answers, any help is appreciated, thanks!\n\n========================================\n\nCode:\n```text\nimport { LAB_MODEL } from '../../models/search/lab-model';\n```\n\n```text\nimport ExperimentDetails from \"@@/components/experiment/ExperimentDetails\";\n```\n\n```text\nError: Webpack Compilation Error\n./models/search/lab-model.js\nModule not found: Error: Can't resolve '@@/components/experiment/ExperimentDetails' in '/Users/hidden/models/search'\nresolve '@@/components/experiment/ExperimentDetails' in '/Users/hidden/models/search'\n Parsed request is a module\n using description file: /Users/hidden/package.json (relative path: ./models/search)\n Field 'browser' doesn't contain a valid alias configuration\n resolve as module\n```\n\n```text\n// somewhere in the Nuxt app\nif (window.Cypress) {\n window.lab_model = LAB_MODEL;\n}\n```\n\n```text\nconst lab_model = cy.state('window').lab_model;\n```\n\n```js\nit('gets labModel from the Nuxt app', () => {\n\n cy.visit('http://localhost:3000/')\n\n cy.window()\n .should('have.property', 'lab_model') // retries until property appears\n .then(labModel => {\n\n console.log(labModel)\n\n // test with labModel here\n })\n})\n```\n\n```text\n@@/\n```\n\n```text\nlab_model\n```\n\n```text\nlab_model\n```\n\n```text\nwindow.lab_model = LAB_MODEL\n```\n\n```text\n/pages/index.vue\n```\n\n```text\n.should()\n```\n\n========================================\n\nComments:\n- This is an elegant answer, but I can't seem to get it to work, there's no obvious spot in my Nuxt app to load that into my window, everywhere I tried I was always met with the error that Cypress can't recognize \"cy.state('window').lab_model\", and the docs you linked to are a bit vague and don't seem to provide a clear path to my module being recognized\n- Nuxt seems to be a bit laggy (at least in dev mode), I can't put my finger on why but adding a `.should()` can fix that","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":110,"estimatedTokens":792}}906{"id":"stack-72131624","source":"stackoverflow","questionId":72131624,"title":"How to deploy nuxt frontend with express backend on AWS?","tags":["amazon-web-services","frontend","nuxt.js","amazon-elastic-beanstalk","backend"],"text":"Title: How to deploy nuxt frontend with express backend on AWS?\nTags: amazon-web-services, frontend, nuxt.js, amazon-elastic-beanstalk, backend\nSource: Stack Overflow\n\nQuestion:\n- I have a Nuxt v2 SSR application as the frontend running on port 3000\n\n- I have an express API as the backend running on port 8000\n\n- I have a python script that loads data from external APIs and needs to run continuously\n\n- Currently all of them are separate projects with their own package.json and what not\n\n- How do I deploy this to AWS?\n\n- The only thing I have figured out so far is that I may have to deploy express API as an Elastic Beanstalk application.\n\n- Should I have a separate docker-compose file for each because they are separate projects currently or should I merge them into one project with a single docker-compose file\n\n- I saw similar questions asked about React, could really appreciate some direction here in Nuxt\n\nNone of these similar questions are based on Nuxt\n\nHow to deploy separated frontend and backend?\n\nHow to deploy a React + NodeJS Express application to AWS?\n\nHow to deploy backend and frontend projects if they are separate?\n\n========================================\n\nTop Answer:\nThere are some ways for you to deploy your stack in AWS. I can give you some options, but you're best shot if you want to save some costs is by using Lambda Functions as your backend, S3 for your front-end and a batch Lambda job for your python script.\n\n- For your backend - https://github.com/vendia/serverless-express\n\n- For your nuxt frontend - https://nuxtjs.org/deployments/amazon-web-services\n\n- For your python job - https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/RunLambdaSchedule.html\n\nIt's not way too simple to execute all of those, but with the following links you'll probably have an idea of how you may implement your solution.\n\n========================================\n\nCode:\n```text\nnuxt generate\n```\n\n```text\ndist\n```\n\n```text\neb\n```\n\n```text\nNPM_CONFIG_UNSAFE_PERM=true\n```\n\n```text\nnpm start\n```\n\n========================================\n\nComments:\n- This may work pretty much the same as the React one if you're shipping Nuxt as SSG. Otherwise, it's a quite broad. Did you gave a read to this one? nuxtjs.org/deployments/amazon-web-services\n- @kissu that guide doesnt cover SSR, only SPA and static sites\n- Why do you have **huge** H1 tags here?\n- fixed that for you","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":72,"estimatedTokens":599}}907{"id":"stack-67689525","source":"stackoverflow","questionId":67689525,"title":"Rerun nuxt route middleware if store getter changes without reloading the page?","tags":["javascript","vue.js","nuxt.js","middleware"],"text":"Title: Rerun nuxt route middleware if store getter changes without reloading the page?\nTags: javascript, vue.js, nuxt.js, middleware\nSource: Stack Overflow\n\nQuestion:\nGiven following middleware, whats the best way to rerun the logic when ever `store.getters.authenticated` changes, and not only on the initial load.\n\n***middleware/auth.js***\n\n```\nexport default function ({ store, redirect }) {\n if (!store.getters.authenticated) {\n return redirect({ name: \"login\" })\n }\n}\n```\n\n========================================\n\nCode:\n```text\nexport default function ({ store, redirect }) {\n if (!store.getters.authenticated) {\n return redirect({ name: \"login\" })\n }\n}\n```\n\n```text\nstore.getters.authenticated\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nthis.$nuxt.refresh()\n```\n\n```text\nfetch()\n```\n\n========================================\n\nComments:\n- Since it's a middleware, it should call itself pretty often already. Otherwise you could use vuex' `watch` method and watch `store.getters.authenticated` old vs new value: vuex.vuejs.org/api/#watch\n- Sorry, I seem to have missed your comment. Personally, that approach feels kind of off. The store shouldn't be responsible for checking permissions and redirect, thats what middleware is designed for in nuxt. I ended up doing 'this.$router.go()`, and refresh the page to rerun he middleware. Changing permissions means you have done a major change (switching accounts or logging out) in which case a refresh is totally reasonable and less error prone.\n- Yep, happens to me sometimes too. Did not get notified even if following a post (sometimes hopefully). Hope it's not a global SO bug. Posted an answer, this way you'll probably see it.\n- Is there a call like `this.$nuxt.refresh()` in Nuxt 3? `refreshNuxtData` doesn't re-run middlewares. `reloadNuxtApp` reloads everything from server, that's a bit too much/slow.","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":51,"estimatedTokens":467}}908{"id":"stack-55665100","source":"stackoverflow","questionId":55665100,"title":"How to prevent user to leave page using middleware in Nuxt?","tags":["vue.js","router","middleware","guard","nuxt.js"],"text":"Title: How to prevent user to leave page using middleware in Nuxt?\nTags: vue.js, router, middleware, guard, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI got a Nuxt application, and in some special route, I want to prevent user from leaving the page by showing plain confirm javascript dialog.\n\nI did some beforeRouteLeave And Nuxt recommends users to use middleware for doing this 'beforeRoute' things. Here's my code.\n\n```\nexport default function (context) {\n if (process.client &&\n context.from.path.includes(\"board/write\") &&\n context.route.name !== \"board-articleId\") {\n if (!confirm(\"Are you sure you want to leave the page?\")) {\n context.next(false)\n }\n }\n}\n```\n\nAs you can see, I'm checking if my current route is certain page (context.from.path...), ask user if user wants to leave the page. And if they canceled, which makes confirm as false, do\n\n***next(false)***\n\nand it works fine as it makes the user stay on the page.\n\nBut the problem is, **the loading bar of the browser still loads even if the page doesn't change. And it looks like the route is still changing anyway despite the actual page doesn't change.**\n\nHow can I prevent this to happen?\n\n========================================\n\nTop Answer:\nTo make sure the address bar query (`?bla=bla`) not touched I recommend doing this:\n\n```\nexport default function ({ from }) {\n redirect(from);\n}\n```\n\n========================================\n\nCode:\n```text\nexport default function (context) {\n if (process.client &&\n context.from.path.includes(\"board/write\") &&\n context.route.name !== \"board-articleId\") {\n if (!confirm(\"Are you sure you want to leave the page?\")) {\n context.next(false)\n }\n }\n}\n```\n\n```text\nredirect(from.path)\n```\n\n```text\nnext(false)\n```\n\n```text\nfrom, route, next, redirect...\n```\n\n```text\nexport default function ({ from }) {\n redirect(from);\n}\n```\n\n```text\n?bla=bla\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":78,"estimatedTokens":476}}909{"id":"stack-72940087","source":"stackoverflow","questionId":72940087,"title":"nuxt app deployed to Netlify: fetch to api working locally, but not on deployed site: getting a 404","tags":["javascript","vue.js","nuxt.js","netlify"],"text":"Title: nuxt app deployed to Netlify: fetch to api working locally, but not on deployed site: getting a 404\nTags: javascript, vue.js, nuxt.js, netlify\nSource: Stack Overflow\n\nQuestion:\nI have a Nuxt.js app that I'm trying to deploy to Netlify - and everything works on my local machine, but the fetch request to the api returns a 404 when it's deployed to Netlify. I don't know how to make that server route available to my client when it's deployed.\n\nthe fetch request in my api-client.js file looks like this:\n\n```\nasync fetchInfo(state) {\n let response = await fetch(`/api/info/${state}`);\n let data = await response.json();\n return data;\n }\n```\n\nand the api looks like this (in api/index.js file):\n\n```\nconst rp = require('request-promise');\nconst apiKey = process.env.POLICY_API_KEY;\n\nexport default function (req, res, next) {\n if (req.url.includes(\"/info\")) {\n let stateAbbr = req.originalUrl.slice(-2);\n rp({\n uri: `https://third-party-api-here.com/states/${stateAbbr}/`,\n method: 'GET',\n headers: { \n 'token': apiKey,\n },\n json: true\n }).then(function success(response) {\n if (response) {\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify(response));\n return;\n }\n }).catch(function error(response) {\n console.log('error', response.error);\n });\n return;\n }\n next();\n}\n```\n\nI think this might have something to do with CORS? I'm getting this error in the browser when I try to hit that route in the deployed app:\n`GET https://my-app-name.netlify.app/api/info/MN 404`\n`SyntaxError: Unexpected token < in JSON at position 0`\n\n========================================\n\nTop Answer:\nYou can have netlify host your /server/api endpoints if you specify in your environment variables NITRO_PRESET=netlify-edge, and use nuxt build to build your deployment. It will then create edge functions that handles your /server/api endpoints. I think this used to be the default until recently with nuxt / nitro, but I believed it changes recently, possibly in nitropack v2.4.0(?) to default to NITRO_PRESET=netlify, where I believe it doesn't create functions for the /server/api endpoints.\n\n========================================\n\nCode:\n```text\nasync fetchInfo(state) {\n let response = await fetch(`/api/info/${state}`);\n let data = await response.json();\n return data;\n }\n```\n\n```text\nconst rp = require('request-promise');\nconst apiKey = process.env.POLICY_API_KEY;\n\nexport default function (req, res, next) {\n if (req.url.includes(\"/info\")) {\n let stateAbbr = req.originalUrl.slice(-2);\n rp({\n uri: `https://third-party-api-here.com/states/${stateAbbr}/`,\n method: 'GET',\n headers: { \n 'token': apiKey,\n },\n json: true\n }).then(function success(response) {\n if (response) {\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify(response));\n return;\n }\n }).catch(function error(response) {\n console.log('error', response.error);\n });\n return;\n }\n next();\n}\n```\n\n```text\nGET https://my-app-name.netlify.app/api/info/MN 404\n```\n\n```text\nSyntaxError: Unexpected token < in JSON at position 0\n```\n\n========================================\n\nComments:\n- Netlify serves static files only - it does not run backends unless you use their serverless Lambda functions (which you obviously do not). You may need to deploy your application on Heroku or on your own VPS if you want to run backend/server-side code.\n- True, be sure that you do not need a server for your usage. You have one when working locally (for Hot Module Reload etc), but Netlify does not allow for such thing.\n- omg, just hosted on Heroku and it's working 😅 thank you!","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":111,"estimatedTokens":921}}910{"id":"stack-63359724","source":"stackoverflow","questionId":63359724,"title":"Nuxt and i18n: Google showing mixed language results","tags":["internationalization","seo","nuxt.js","nuxt-i18n"],"text":"Title: Nuxt and i18n: Google showing mixed language results\nTags: internationalization, seo, nuxt.js, nuxt-i18n\nSource: Stack Overflow\n\nQuestion:\nI've made a site using Nuxt.\n\nThe site has 2 languages: Italian (default) and English for everyone else.\nI installed nuxt-i18n and configured it, and everything seems to work fine (especially when looking at the code with the devtools, html lang, rel=alternate and so on..).\n\nBut here's the problem: when i search for the site with google (in italian), the snippet for the site in the SERP is in english.\n\nHere's my code:\n\n```\n['nuxt-i18n', {\n seo: false,\n baseUrl: 'https://www.leconturbanti.it',\n locales: [\n {\n name: 'Italiano',\n code: 'it',\n iso: 'it-IT',\n file: 'it-IT.js'\n },\n {\n name: 'English',\n code: 'en',\n iso: 'en-US',\n file: 'en-US.js'\n },\n ],\n pages: {\n 'contatti/index': {\n it: '/contatti',\n en: '/contact-us'\n },\n 'illustrazioni-collezione/index': {\n it: '/illustrazioni-collezione',\n en: '/illustrations-capsule'\n }\n },\n langDir: 'lang/',\n parsePages: false,\n defaultLocale: 'it',\n lazy: true\n }]\n```\n\nI set `seo: false` for better performance as explained in the docs, and merge the data in the default layout:\n\n```\nhead(){\n return{\n script:[\n {type: `text/javascript`, innerHTML: this.$t('policy.cookieId')},\n {src: `//cdn.iubenda.com/cs/iubenda_cs.js`, charset: `UTF-8`, type: `text/javascript`}\n ],\n __dangerouslyDisableSanitizers: ['script'],\n ...this.$nuxtI18nSeo()\n }\n },\n```\n\nI also set the meta tags for every page with `$t` in the `head()`. For example, in home:\n\n```\nhead(){\n return{\n title: this.$t('seo.home.title'),\n meta: [\n { hid: 'description', name: 'description', content: this.$t('seo.home.description')},\n { hid: 'og:title', property: 'og:title', content: this.$t('seo.home.title') },\n { hid: 'og:url', property: 'og:url', content: this.$t('seo.home.url') },\n { hid: 'twitter:title', property: 'twitter:title', content: this.$t('seo.home.title') },\n { hid: 'og:description', property: 'og:description', content: this.$t('seo.home.description') },\n { hid: 'twitter:description', property: 'twitter:description', content: this.$t('seo.home.description') },\n ] \n }\n },\n```\n\nI can't understand what i did wrong. I already added the site in Search Console. If you need to visit it for inspection, the url is: www.leconturbanti.it\n\nIf you need more of my code in order to answer just ask.\nThank you.\n\n========================================\n\nTop Answer:\nMy nuxt page head:\n\n```\nhead(){\n return {\n ...this.$nuxtI18nHead({ addDirAttribute: true, addSeoAttributes: true }),\n title: this.page.title,\n meta: [\n {\n property: 'og:description',\n name: 'description',\n content: this.page.description\n },\n {\n property: 'og:title',\n name: 'title',\n content: this.page.title\n }\n ],\n }\n },\n```\n\nMy nuxt.config.js\n\n```\ni18n: {\n locales ,\n strategy: 'prefix',//no_prefix , prefix , prefix_and_default ,prefix_except_default\n vueI18nLoader: true,\n defaultLocale: process.env.LOCALE_DEFAULT||'en',\n langDir: '~/locales/',\n vueI18n: {\n silentTranslationWarn: true\n },\n detectBrowserLanguage: false\n },\n```\n\n========================================\n\nCode:\n```js\n['nuxt-i18n', {\n seo: false,\n baseUrl: 'https://www.leconturbanti.it',\n locales: [\n {\n name: 'Italiano',\n code: 'it',\n iso: 'it-IT',\n file: 'it-IT.js'\n },\n {\n name: 'English',\n code: 'en',\n iso: 'en-US',\n file: 'en-US.js'\n },\n ],\n pages: {\n 'contatti/index': {\n it: '/contatti',\n en: '/contact-us'\n },\n 'illustrazioni-collezione/index': {\n it: '/illustrazioni-collezione',\n en: '/illustrations-capsule'\n }\n },\n langDir: 'lang/',\n parsePages: false,\n defaultLocale: 'it',\n lazy: true\n }]\n```\n\n```js\nhead(){\n return{\n script:[\n {type: `text/javascript`, innerHTML: this.$t('policy.cookieId')},\n {src: `//cdn.iubenda.com/cs/iubenda_cs.js`, charset: `UTF-8`, type: `text/javascript`}\n ],\n __dangerouslyDisableSanitizers: ['script'],\n ...this.$nuxtI18nSeo()\n }\n },\n```\n\n```js\nhead(){\n return{\n title: this.$t('seo.home.title'),\n meta: [\n { hid: 'description', name: 'description', content: this.$t('seo.home.description')},\n { hid: 'og:title', property: 'og:title', content: this.$t('seo.home.title') },\n { hid: 'og:url', property: 'og:url', content: this.$t('seo.home.url') },\n { hid: 'twitter:title', property: 'twitter:title', content: this.$t('seo.home.title') },\n { hid: 'og:description', property: 'og:description', content: this.$t('seo.home.description') },\n { hid: 'twitter:description', property: 'twitter:description', content: this.$t('seo.home.description') },\n ] \n }\n },\n```\n\n```text\nseo: false\n```\n\n```text\n$t\n```\n\n```text\nhead()\n```\n\n```text\nnuxt-i18n\n```\n\n```text\ndetectBrowserLanguage: false\n```\n\n```text\nhead(){\n return {\n ...this.$nuxtI18nHead({ addDirAttribute: true, addSeoAttributes: true }),\n title: this.page.title,\n meta: [\n {\n property: 'og:description',\n name: 'description',\n content: this.page.description\n },\n {\n property: 'og:title',\n name: 'title',\n content: this.page.title\n }\n ],\n }\n },\n```\n\n```text\ni18n: {\n locales ,\n strategy: 'prefix',//no_prefix , prefix , prefix_and_default ,prefix_except_default\n vueI18nLoader: true,\n defaultLocale: process.env.LOCALE_DEFAULT||'en',\n langDir: '~/locales/',\n vueI18n: {\n silentTranslationWarn: true\n },\n detectBrowserLanguage: false\n },\n```\n\n========================================\n\nComments:\n- Any luck with this? Running into the same issue..\n- Yes, i posted an answer. Give a look.\n- You know, I kinda figured this was the issue but I didn't want to mess with SEO rankings trying to fix it. Thanks for confirming!\n- An answer with code sample should explain a bit what in this code sharing is related to the actual question. (E.g.: This is how the defaultLocale and detectBrowserLanguage parameters should be set to avoid this problem...)","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":258,"estimatedTokens":1561}}911{"id":"stack-65325228","source":"stackoverflow","questionId":65325228,"title":"How can I use conditional operator in v-text as Vue.Js components?","tags":["javascript","typescript","vue.js","nuxt.js","vuetify.js"],"text":"Title: How can I use conditional operator in v-text as Vue.Js components?\nTags: javascript, typescript, vue.js, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nI am using Vue.Js and also using Nuxt.js as framework, and language is TypeScript.\n\nI really want to make the table like following using below data.\n\n```\nexport const dummy_taskData =\n[\n {\n id: \"common_task\",\n tasks: [\n {\n tid: \"all#budget\",\n tname: \"Invoie\"\n },\n {\n tid: \"all#inquiry\",\n tname: \"QA\"\n },\n {\n tid: \"all#deskwork\",\n tname: \"deskwork\"\n },\n {\n tid: \"XX#business\",\n tname: \"PaperWork\"\n },\n {\n tid: \"XX#H&R\",\n tname: \"PaperWork\"\n },\n {\n tid: \"YY#H&R\",\n tname: \"PaperWork\"\n }\n ]\n }\n]\n```\n\nhttps://i.sstatic.net/AbyMG.png\n\nSo I tried to make code the following.\n\n```\n\n \n \n \n task\n item\n item2\n \n \n \n \n \n common_task\n \n {{item.tname}}\n \n \n \n \n\nimport { Component, Vue } from 'nuxt-property-decorator'\nimport { dummy_taskData } from '~/store/dummy'\n \ninterface Tasks {\n tid: string\n tname: string\n}\ninterface Items {\n id: string\n tasks: Tasks[]\n}\n@Component({})\nexport default class extends Vue {\n items: Items[] = dummy_taskData\n newItems:(Tasks|undefined)[] = []\n mounted() {\n let findCommon:Items[] = this.items.filter((e:Items)=>{\n return e.id === 'common_task'\n })\n let makeNewItems = findCommon[0].tasks.map((item)=>{\n if(item.tid.includes(\"all\")){\n return {tid:\"all\",tname:item.tname}\n } \n else if(item.tid.includes('XX')){\n return {tid:\"XX\",tname:item.tname}\n } else {\n return {tid:item.tid,tname:item.tname}\n }\n })\n this.newItems = makeNewItems\n }\n}\n\n.v-data-table--dense > .v-data-table__wrapper > table > tbody > tr > td, .v-data-table--dense > .v-data-table__wrapper > table > thead > tr > td, .v-data-table--dense > .v-data-table__wrapper > table > tfoot > tr > td{\n border-bottom: thin solid rgba(255,255,255,0.12);\n}\n\n```\n\nI ran this code, but error occurred like\n\n```\nTypeError: Cannot read property 'tid' of undefined\n```\n\nI thought 'conditional operator' was best way that kind of case,\nbut I couldn't fix my code.\nDoes anyone advise me?\n\n========================================\n\nCode:\n```text\nexport const dummy_taskData =\n[\n {\n id: \"common_task\",\n tasks: [\n {\n tid: \"all#budget\",\n tname: \"Invoie\"\n },\n {\n tid: \"all#inquiry\",\n tname: \"QA\"\n },\n {\n tid: \"all#deskwork\",\n tname: \"deskwork\"\n },\n {\n tid: \"XX#business\",\n tname: \"PaperWork\"\n },\n {\n tid: \"XX#H&R\",\n tname: \"PaperWork\"\n },\n {\n tid: \"YY#H&R\",\n tname: \"PaperWork\"\n }\n ]\n }\n]\n```\n\n```text\n<template>\n <v-simple-table dense>\n <thead>\n <tr>\n <th>task</th>\n <th>item</th>\n <th>item2</th>\n </tr>\n </thead>\n <tbody class=\"hover_stop\">\n <template v-for=\"(item,index,tid) in newItems\">\n <tr :key=\"tid\">\n <td v-if=\"tid === 0\" :rowspan=\"newItems.length\">common_task</td>\n <td v-text=\"item.tid === newItems[item.index-1].tid?'':item.tid\"></td>\n <td>{{item.tname}}</td>\n </tr>\n </template>\n </tbody>\n </v-simple-table>\n</template>\n<script lang=\"ts\">\nimport { Component, Vue } from 'nuxt-property-decorator'\nimport { dummy_taskData } from '~/store/dummy'\n \ninterface Tasks {\n tid: string\n tname: string\n}\ninterface Items {\n id: string\n tasks: Tasks[]\n}\n@Component({})\nexport default class extends Vue {\n items: Items[] = dummy_taskData\n newItems:(Tasks|undefined)[] = []\n mounted() {\n let findCommon:Items[] = this.items.filter((e:Items)=>{\n return e.id === 'common_task'\n })\n let makeNewItems = findCommon[0].tasks.map((item)=>{\n if(item.tid.includes(\"all\")){\n return {tid:\"all\",tname:item.tname}\n } \n else if(item.tid.includes('XX')){\n return {tid:\"XX\",tname:item.tname}\n } else {\n return {tid:item.tid,tname:item.tname}\n }\n })\n this.newItems = makeNewItems\n }\n}\n</script>\n<style lang=\"scss\" scoped>\n.v-data-table--dense > .v-data-table__wrapper > table > tbody > tr > td, .v-data-table--dense > .v-data-table__wrapper > table > thead > tr > td, .v-data-table--dense > .v-data-table__wrapper > table > tfoot > tr > td{\n border-bottom: thin solid rgba(255,255,255,0.12);\n}\n</style>\n```\n\n```text\nTypeError: Cannot read property 'tid' of undefined\n```\n\n```html\nnewItems[item.index-1]\n```\n\n```html\n<template v-for=\"(item, index) in newItems\">\n <tr :key=\"item.tid\">\n <td v-if=\"item.tid === 0\" :rowspan=\"newItems.length\">common_task</td>\n <td v-text=\"index && item.tid === newItems[index - 1].tid ? '' : item.tid\"></td>\n <td>{{item.tname}}</td>\n </tr>\n</template>\n```\n\n```text\nnewItems\n```\n\n```text\nv-for\n```\n\n```text\ntid\n```\n\n```text\nitem.tid\n```\n\n```text\nitem.index\n```\n\n```text\n<td>s\n```\n\n```text\nitems\n```\n\n```text\nindex\n```\n\n```text\ntid\n```\n\n```text\ntname\n```\n\n```text\nindex-1\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":279,"estimatedTokens":1266}}912{"id":"stack-72345480","source":"stackoverflow","questionId":72345480,"title":"Nuxt3 Router - $route is not defined","tags":["vue.js","nuxt.js","vue-router","vuejs3","nuxt3.js"],"text":"Title: Nuxt3 Router - $route is not defined\nTags: vue.js, nuxt.js, vue-router, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI've set up a fresh Nuxt3 project, and am having an issue when I use a NuxtLink component to navigate to a dynamic route page.\n\n```\n\n \n \n {{project.text}}\n \n Add Project\n \n\nimport { useProjectsStore } from '@/store/projects.js'\nexport default {\n setup() {\n const projects = useProjectsStore()\n\n return { projects }\n },\n}\n\n```\n\nIn this code here, when I click add project, it creates a NuxtLink component fine. When I click the link, the URL changes in the window to /projects/0 as expected, but I get this error in the console and the page content doesn't update.\n\n```\nUncaught (in promise) ReferenceError: $route is not defined at [id].vue:14:72\n```\n\nBut when I refresh the page, going directly to the `/projects/0` location, it loads fine with no $route is not defined error.\n\nWeirdly though, if I add in a NuxtLink component that goes to `/projects/0` and click that link, instead of creating the NuxtLink component with the Add Project button, the route works fine with no error.\n\nThis is the `[id].vue` file contents:\n\n```\n\n \n \n\n### Single project\n\n \n\n### {{project}}\n\n \n\nimport { useProjectsStore } from '@/store/projects.js'\n\nexport default {\n setup() {\n const projects = useProjectsStore()\n const project = projects.projects.find((project) => project.id === $route.params.id)\n\nconsole.log(project);\n return { project }\n },\n}\n\n```\n\n========================================\n\nCode:\n```html\n<template>\n <div>\n <div v-for=\"project in projects.projects\">\n <NuxtLink :to=\"{ path: `/projects/${project.id}` }\">{{project.text}}</NuxtLink>\n </div>\n <button @click=\"projects.addProject('Test Project', 'Director')\">Add Project</button>\n </div>\n</template>\n\n<script>\nimport { useProjectsStore } from '@/store/projects.js'\nexport default {\n setup() {\n const projects = useProjectsStore()\n\n return { projects }\n },\n}\n</script>\n```\n\n```text\nUncaught (in promise) ReferenceError: $route is not defined at [id].vue:14:72\n```\n\n```html\n<template>\n <div>\n <h2>Single project</h2>\n <h1>{{project}}</h1>\n </div>\n</template>\n\n<script>\nimport { useProjectsStore } from '@/store/projects.js'\n\nexport default {\n setup() {\n const projects = useProjectsStore()\n const project = projects.projects.find((project) => project.id === $route.params.id)\n\nconsole.log(project);\n return { project }\n },\n}\n</script>\n```\n\n```text\n/projects/0\n```\n\n```text\n/projects/0\n```\n\n```text\n[id].vue\n```\n\n```js\nexport default {\n setup() {\n const projects = useProjectsStore()\n const route=useRoute()\n const project = projects.projects.find((project) => project.id === route.params.id)\n\nconsole.log(project);\n return { project }\n },\n}\n```\n\n```text\nuseRoute\n```\n\n========================================\n\nComments:\n- you're welcome, try also to define `project` as computed property\n- What do you mean by that?\n- `const project = computed(()=>projects.projects.find((project) => project.id === route.params.id))`\n- when using the history navigation useRoute().params can be empty.","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":154,"estimatedTokens":783}}913{"id":"stack-67741207","source":"stackoverflow","questionId":67741207,"title":"FUNCTION_INVOCATION_FAILED error on Vercel and Nuxt deployment","tags":["vue.js","nuxt.js","vercel"],"text":"Title: FUNCTION_INVOCATION_FAILED error on Vercel and Nuxt deployment\nTags: vue.js, nuxt.js, vercel\nSource: Stack Overflow\n\nQuestion:\nImported a Nuxt project from GitHub with `vercel.json` config:\n\n```\n{\n \"version\": 2,\n \"builds\": [\n {\n \"src\": \"nuxt.config.js\",\n \"use\": \"@nuxtjs/vercel-builder\"\n }\n ]\n}\n```\n\nMy `package.json`:\n\n```\n{\n \"name\": \"test-app-v2\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint:js\": \"eslint --ext \\\".js,.vue\\\" --ignore-path .gitignore .\",\n \"lint\": \"yarn lint:js\"\n },\n \"lint-staged\": {\n \"*.{js,vue}\": \"eslint\"\n },\n \"husky\": {\n \"hooks\": {\n \"pre-commit\": \"lint-staged\"\n }\n },\n \"dependencies\": {\n \"@nuxtjs/composition-api\": \"^0.24.0\",\n \"@nuxtjs/pwa\": \"^3.3.5\",\n \"core-js\": \"^3.9.1\",\n \"nuxt\": \"^2.15.3\"\n },\n \"devDependencies\": {\n \"@nuxt/types\": \"^2.15.3\",\n \"@nuxt/typescript-build\": \"^2.1.0\",\n \"@nuxtjs/eslint-config-typescript\": \"^6.0.0\",\n \"@nuxtjs/eslint-module\": \"^3.0.2\",\n \"@nuxtjs/vuetify\": \"^1.11.3\",\n \"babel-eslint\": \"^10.1.0\",\n \"eslint\": \"^7.22.0\",\n \"eslint-config-prettier\": \"^8.1.0\",\n \"eslint-plugin-nuxt\": \"^2.0.0\",\n \"eslint-plugin-prettier\": \"^3.3.1\",\n \"eslint-plugin-vue\": \"^7.7.0\",\n \"husky\": \"^4.3.8\",\n \"lint-staged\": \"^10.5.4\",\n \"prettier\": \"^2.2.1\"\n }\n}\n```\n\nand `nuxt.config.js`\n\n```\nimport colors from 'vuetify/es5/util/colors'\n\nexport default {\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n titleTemplate: '%s - test-app-v2',\n title: 'test-app-v2',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: '' },\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n // https://go.nuxtjs.dev/typescript\n '@nuxt/typescript-build',\n // https://go.nuxtjs.dev/vuetify\n '@nuxtjs/vuetify',\n '@nuxtjs/composition-api/module',\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\n // https://go.nuxtjs.dev/pwa\n '@nuxtjs/pwa',\n ],\n\n // PWA module configuration: https://go.nuxtjs.dev/pwa\n pwa: {\n manifest: {\n lang: 'en',\n },\n },\n\n // Vuetify module configuration: https://go.nuxtjs.dev/config-vuetify\n vuetify: {\n customVariables: ['~/assets/variables.scss'],\n theme: {\n dark: false,\n themes: {\n dark: {\n primary: colors.blue.darken2,\n accent: colors.grey.darken3,\n secondary: colors.amber.darken3,\n info: colors.teal.lighten1,\n warning: colors.amber.base,\n error: colors.deepOrange.accent4,\n success: colors.green.accent3,\n },\n },\n },\n },\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {},\n}\n```\n\nI have no API yet and this is the error log in function tab:\n\nhttps://i.sstatic.net/rGADV.png\n\n========================================\n\nTop Answer:\nWasn't the OPs aim to deploy it using SSR? Using build command `yarn generate` will just generate a static site.\n\n========================================\n\nCode:\n```json\n{\n \"version\": 2,\n \"builds\": [\n {\n \"src\": \"nuxt.config.js\",\n \"use\": \"@nuxtjs/vercel-builder\"\n }\n ]\n}\n```\n\n```json\n{\n \"name\": \"test-app-v2\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint:js\": \"eslint --ext \\\".js,.vue\\\" --ignore-path .gitignore .\",\n \"lint\": \"yarn lint:js\"\n },\n \"lint-staged\": {\n \"*.{js,vue}\": \"eslint\"\n },\n \"husky\": {\n \"hooks\": {\n \"pre-commit\": \"lint-staged\"\n }\n },\n \"dependencies\": {\n \"@nuxtjs/composition-api\": \"^0.24.0\",\n \"@nuxtjs/pwa\": \"^3.3.5\",\n \"core-js\": \"^3.9.1\",\n \"nuxt\": \"^2.15.3\"\n },\n \"devDependencies\": {\n \"@nuxt/types\": \"^2.15.3\",\n \"@nuxt/typescript-build\": \"^2.1.0\",\n \"@nuxtjs/eslint-config-typescript\": \"^6.0.0\",\n \"@nuxtjs/eslint-module\": \"^3.0.2\",\n \"@nuxtjs/vuetify\": \"^1.11.3\",\n \"babel-eslint\": \"^10.1.0\",\n \"eslint\": \"^7.22.0\",\n \"eslint-config-prettier\": \"^8.1.0\",\n \"eslint-plugin-nuxt\": \"^2.0.0\",\n \"eslint-plugin-prettier\": \"^3.3.1\",\n \"eslint-plugin-vue\": \"^7.7.0\",\n \"husky\": \"^4.3.8\",\n \"lint-staged\": \"^10.5.4\",\n \"prettier\": \"^2.2.1\"\n }\n}\n```\n\n```js\nimport colors from 'vuetify/es5/util/colors'\n\nexport default {\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n titleTemplate: '%s - test-app-v2',\n title: 'test-app-v2',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: '' },\n ],\n link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n // https://go.nuxtjs.dev/typescript\n '@nuxt/typescript-build',\n // https://go.nuxtjs.dev/vuetify\n '@nuxtjs/vuetify',\n '@nuxtjs/composition-api/module',\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\n // https://go.nuxtjs.dev/pwa\n '@nuxtjs/pwa',\n ],\n\n // PWA module configuration: https://go.nuxtjs.dev/pwa\n pwa: {\n manifest: {\n lang: 'en',\n },\n },\n\n // Vuetify module configuration: https://go.nuxtjs.dev/config-vuetify\n vuetify: {\n customVariables: ['~/assets/variables.scss'],\n theme: {\n dark: false,\n themes: {\n dark: {\n primary: colors.blue.darken2,\n accent: colors.grey.darken3,\n secondary: colors.amber.darken3,\n info: colors.teal.lighten1,\n warning: colors.amber.base,\n error: colors.deepOrange.accent4,\n success: colors.green.accent3,\n },\n },\n },\n },\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {},\n}\n```\n\n```text\nvercel.json\n```\n\n```text\npackage.json\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nvercel.json\n```\n\n```text\nyarn generate\n```\n\n========================================\n\nComments:\n- I am getting the same error when trying to deploy an SSR nuxt project using vercel.json and @nuxt/vercel-builder. The accepted answer obviously meant deploying it as a static site - have you found a solution to your original problem?\n- But this is not SSR, this is using generate, which is JS/client and not server rendered.\n- @MichaelGiovanniPumo not a Vercel specialist but indeed, I don't think that Vercel is exposing a Node.js server, it's for JAMstack only projects.\n- @kissu I'm not sure that's correct, Vercel explicitly states it supports SSR builds with Nuxt: nuxtjs.org/deployments/vercel/#ssr-with-vercel\n- @fredrivett it's written serverless runtime. Not sure that you have a free Node.js running server. But if it fits into a serverless runtime, you can probably have SSR benefits, for sure.\n- @kissu yeah you're right that Vercel don't provide a free Node.js server to be fair, but it seems from my experience deploying a Nuxt app that the serverless functions offer comparable experience, allowing for Vue apps to render whilst JS is disabled\n- @fredrivett there are lighter solution to allow static Vue apps that are more suitable towards serverless hosting IMO.","metadata":{"transformedAt":"2026-08-18T18:33:07.902Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":311,"estimatedTokens":1922}}914{"id":"stack-67807245","source":"stackoverflow","questionId":67807245,"title":"Access Nuxt custom plugin from Composition API","tags":["vue.js","nuxt.js","vue-composition-api"],"text":"Title: Access Nuxt custom plugin from Composition API\nTags: vue.js, nuxt.js, vue-composition-api\nSource: Stack Overflow\n\nQuestion:\nI am using VueClipboard in my nuxt project.\n\nhttps://www.npmjs.com/package/vue-clipboard2\n\nI have a plugin file vue-clipboard.js\n\n```\nimport Vue from \"vue\";\nimport VueClipboard from 'vue-clipboard2';\nVue.use(VueClipboard);\n```\n\nIt is imported into nuxt.config\n\n```\nplugins: ['@/plugins/vue-clipboard'],\n```\n\nThis sets up a global variable $copyText and in nuxt **without the composition API** I can do something like\n\n```\nmethods: {\n async onCopyCodeToClipboard() {\n const code = 'code'\n await this.$copyText(code)\n },\n},\n```\n\nHowever inside the setup using the composition API (@nuxtjs/composition-api) when I write a function I do not have access to this.$copyText\n\n```\nconst onCopyCodeToClipboard = async () => {\n const code = context.slots.default()[0].elm.outerHTML\n // -> Can't use this here - await this.$copyText(code)\n}\n```\n\nSo how do I make `$copyText` available to use inside the composition API?\n\n========================================\n\nTop Answer:\nIf you are using nuxt bridge, you should directly import the useContext from useNuxtApp() like:\n\n```\nconst { $copyText } = useNuxtApp()\n```\n\nhttps://nuxt.com/docs/bridge/bridge-composition-api#usecontext-and-withcontext\n\n========================================\n\nCode:\n```js\nimport Vue from \"vue\";\nimport VueClipboard from 'vue-clipboard2';\nVue.use(VueClipboard);\n```\n\n```js\nplugins: ['@/plugins/vue-clipboard'],\n```\n\n```js\nmethods: {\n async onCopyCodeToClipboard() {\n const code = 'code'\n await this.$copyText(code)\n },\n},\n```\n\n```js\nconst onCopyCodeToClipboard = async () => {\n const code = context.slots.default()[0].elm.outerHTML\n // -> Can't use this here - await this.$copyText(code)\n}\n```\n\n```text\n$copyText\n```\n\n```js\nimport { useContext } from '@nuxtjs/composition-api'\n\nexport default function () {\n const { $copyText } = useContext();\n\n $copyText('code');\n}\n```\n\n```text\nuseContext()\n```\n\n```js\nconst { $copyText } = useNuxtApp()\n```\n\n========================================\n\nComments:\n- you should use useContext for get plugin","metadata":{"transformedAt":"2026-08-18T18:33:07.903Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":111,"estimatedTokens":537}}915{"id":"stack-72128279","source":"stackoverflow","questionId":72128279,"title":"Flexbox child height it content","tags":["css","vue.js","nuxt.js","vuetify.js"],"text":"Title: Flexbox child height it content\nTags: css, vue.js, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nI have a container with display: flex, and it childs height, is higher than it content.\nI'm using Vuetify (vuejs)\n\nFor example:\n\nI have a v-col with 2 span\n\n```\n\n 134 POSTS\n 120 POSTS\n\n```\n\nIf I put flex-direction to column, then:\n\nhttps://i.sstatic.net/5qz0I.png\n\nheight of spans is greater than it content!\n\nIf I put flex-direction to row, then:\n\nhttps://i.sstatic.net/Ybx3O.png\n\nthe same happens.\n\nI expect that the span height is only his content height\n\nEdit:\n\nI try again and the problem is only when I try to put inside display flex column inside a card: here is the code to try in vuetify\n\n```\n\n \n \n \n 123123 \n 123121 \n \n \n \n\n```\n\nhttps://i.sstatic.net/ByrLR.png\n\nSolution:\n\nI found the solution, v-card-title have a class with line-height, the solution is edit this line-height\n\nhttps://i.sstatic.net/haXoK.png\n\nhttps://i.sstatic.net/RvqUG.png\n\n========================================\n\nCode:\n```html\n<v-col style=\"display:flex;flex-direction:column\">\n <span style=\"background-color:green;font-size:0.4rem\">134 POSTS</span>\n <span style=\"background-color:green;font-size:0.4rem\">120 POSTS</span>\n</v-col>\n```\n\n```html\n<v-card>\n <v-card-title>\n <v-row>\n <v-col class=\"d-flex\" style=\"flex-direction: column\">\n <span style=\"font-size: 0.6rem\"> 123123 </span>\n <span style=\"font-size: 0.6rem\"> 123121 </span>\n </v-col>\n </v-row>\n </v-card-title>\n</v-card>\n```\n\n```text\nv-card-title\n```\n\n```text\nline-height: 2rem\n```\n\n========================================\n\nComments:\n- Set a padding to 0\n- Your issue cannot be reproduced with the given code. Working perfectly fine on my side. Some other CSS is being applied to your blocks. Please check in your browser devtools.","metadata":{"transformedAt":"2026-08-18T18:33:07.903Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":96,"estimatedTokens":455}}916{"id":"stack-48376653","source":"stackoverflow","questionId":48376653,"title":"Config Axios globally with Authenticated in NuxtJS - VueJS","tags":["vue.js","vuejs2","axios","vuex","nuxt.js"],"text":"Title: Config Axios globally with Authenticated in NuxtJS - VueJS\nTags: vue.js, vuejs2, axios, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI finding way to config Axios globally with Authenticated in NuxtJS - VueJS (I use mainly NUXTJS).\n\nAll I need is: *If user logged in and have token in $store, axios will get this token. If user is anonymous, axios wont get this token* \n\n**~/plugins/axios**\n\n```\nimport axios from 'axios'\nimport AuthenticationStore from '~/store'\n\nvar api = axios.create({\n baseURL: 'http://localhost:8000/api/v1/',\n 'headers': {'Authorization': 'JWT ' + AuthenticationStore.state.token}\n})\n\napi.interceptors.request.use(function (config) {\n config.headers = {\n 'Authorization': AuthenticationStore.state.token ? 'JWT ' + AuthenticationStore.state.token : ''\n }\n return config\n}, function (error) {\n // Do something with request error\n return Promise.reject(error)\n})\n\nexport default api\n```\n\n**~/store/index.js**\n\n```\nconst AuthenticationStore = () => {\n return new Vuex.Store({\n state: {\n token: null\n },\n mutations: {\n SET_TOKEN: function (state, token) {\n state.token = token\n instance.defaults.headers = { Authorization: 'Bearer ' + token }\n }\n },\n actions: {\n ....\n }\n })\n}\n\nexport default AuthenticationStore\n```\n\nError: `[nuxt] Error while initializing app TypeError: Cannot read property 'token' of undefined`\n\n========================================\n\nCode:\n```text\nimport axios from 'axios'\nimport AuthenticationStore from '~/store'\n\nvar api = axios.create({\n baseURL: 'http://localhost:8000/api/v1/',\n 'headers': {'Authorization': 'JWT ' + AuthenticationStore.state.token}\n})\n\napi.interceptors.request.use(function (config) {\n config.headers = {\n 'Authorization': AuthenticationStore.state.token ? 'JWT ' + AuthenticationStore.state.token : ''\n }\n return config\n}, function (error) {\n // Do something with request error\n return Promise.reject(error)\n})\n\nexport default api\n```\n\n```text\nconst AuthenticationStore = () => {\n return new Vuex.Store({\n state: {\n token: null\n },\n mutations: {\n SET_TOKEN: function (state, token) {\n state.token = token\n instance.defaults.headers = { Authorization: 'Bearer ' + token }\n }\n },\n actions: {\n ....\n }\n })\n}\n\nexport default AuthenticationStore\n```\n\n```text\n[nuxt] Error while initializing app TypeError: Cannot read property 'token' of undefined\n```\n\n```text\n// ~/plugins/axios\nimport axios from 'axios'\nimport AuthenticationStore from '~/store'\n\nvar api = axios.create({\n baseURL: 'http://localhost:8000/api/v1/',\n 'headers': {'Authorization': 'JWT ' + AuthenticationStore.state.token}\n})\n api.interceptors.request.use(function (config) {\n config.headers = {\n 'Authorization': AuthenticationStore.state.token ? 'Bearer ' + AuthenticationStore.state.token : ''\n }\n return config\n}, function (error) {\n // Do something with request error\n return Promise.reject(error)\n})\nexport default api\n```\n\n```text\nconst AuthenticationStore = () => {\n```\n\n```text\nconst AuthenticationStore = new Vuex.Store({ ...\n```\n\n========================================\n\nComments:\n- Did you try exporting the state as a function like: export const state = () => ({ // goes here })\n- I tried it like you said in `~/store/index.js`. Take a look my code above please!\n- Well, I just wondered if you tried the modules approach way shown here, but apparently it is more like the classical way. Then, I can say using the state like `this.$state.token` might help.\n- @vahdet Thanks. I'll try it\n- Sorry, I made mistake about code in `store/index.js`. Please review my code above. I have some issues about import store into axios.js file.\n- what issues exactly you have?\n- My error is `[nuxt] Error while initializing app TypeError: Cannot read property 'token' of undefined`\n- When I console.log(AuthenticationStore), it render: `AuthenticationStore() { return new __WEBPACK_IMPORTED_MODULE_7_vuex__[\"default\"].Store({ state: { authUser: null, userInfo: null, token: null },`\n- Updated my answer. Hope it helps\n- Thanks. Youre right. I just understand vaguely about Vuex Store. Maybe I'll try it. Thanks for help :)","metadata":{"transformedAt":"2026-08-18T18:33:07.903Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":150,"estimatedTokens":1037}}917{"id":"stack-53379201","source":"stackoverflow","questionId":53379201,"title":"Select a layout for dynamically generated nuxt page","tags":["vue.js","vue-router","nuxt.js"],"text":"Title: Select a layout for dynamically generated nuxt page\nTags: vue.js, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a project where all my data - including page routes - comes from a GraphQL endpoint but needs to be hosted via a static site (I know, I know. Don't get me started).\n\nI've managed to generate routes statically from the data using the following code in `nuxt.config.js`:\n\n```\ngenerate: {\n routes: () => {\n const uri = 'http://localhost:4000/graphql'\n const apolloFetch = createApolloFetch({ uri })\n const query = `\n query Pages {\n pages {\n slug\n template\n pageContent {\n replaced\n components {\n componentName\n classes\n body\n }\n }\n }\n }\n `\n\n return apolloFetch({ query }) // all apolloFetch arguments are optional\n .then(result => {\n const { data } = result\n return data.pages.map(page => page.slug)\n })\n .catch(error => {\n console.log('got error')\n console.log(error)\n })\n }\n }\n```\n\nThe problem I am trying to solve is that some pages need to use a different layout from the default, the correct layout to use is specified in the GraphQL data as `page.template` but I don't see any way to pass that information to the router.\n\nI've tried changing `return data.pages.map(page => page.slug)` to:\n\n```\nreturn data.pages.map(page => {\n route: page.slug,\n layout: page.template\n })\n```\n\nbut that seems to be a non-starter. Does anyone know how to pass a layout preference to the vue router?\n\n========================================\n\nCode:\n```text\ngenerate: {\n routes: () => {\n const uri = 'http://localhost:4000/graphql'\n const apolloFetch = createApolloFetch({ uri })\n const query = `\n query Pages {\n pages {\n slug\n template\n pageContent {\n replaced\n components {\n componentName\n classes\n body\n }\n }\n }\n }\n `\n\n return apolloFetch({ query }) // all apolloFetch arguments are optional\n .then(result => {\n const { data } = result\n return data.pages.map(page => page.slug)\n })\n .catch(error => {\n console.log('got error')\n console.log(error)\n })\n }\n }\n```\n\n```text\nreturn data.pages.map(page => {\n route: page.slug,\n layout: page.template\n })\n```\n\n```text\nnuxt.config.js\n```\n\n```text\npage.template\n```\n\n```text\nreturn data.pages.map(page => page.slug)\n```\n\n========================================\n\nComments:\n- in the docs it says: \"dynamic routes are ignored by the generate command: nuxtjs.org/api/configuration-generate#routes\" - but it's just a wild guess\n- Did you manage to find a solution?\n- This is what I ended up doing :) Then I said 'screw it' when the next issue arose and just switched to Gatsby. :)\n- Have you considered Gridsome?\n- Link above is broken, so here it is the new link to the docs","metadata":{"transformedAt":"2026-08-18T18:33:07.903Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":122,"estimatedTokens":723}}918{"id":"stack-54982462","source":"stackoverflow","questionId":54982462,"title":"ExpressJS - Serve both universal Nuxt app and AngularJS SPA","tags":["javascript","node.js","express","vue.js","nuxt.js"],"text":"Title: ExpressJS - Serve both universal Nuxt app and AngularJS SPA\nTags: javascript, node.js, express, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a blog project with this structure:\n\n- server - written in Node/Express\n\n- admin - AngularJS SPA\n\n- public - AngularJS SPA (for the moment)\n\nThe admin and public parts have the same domain, but the admin part uses a different subdomain, which allows me to serve the app like this in Express:\n\n\r\n\r\n\n```\napp.get('*', (req, res) => {\r\n var firstIndex = req.get('host').indexOf('.');\r\n var subdomain = req.get('host').substr(0, firstIndex).toLowerCase();\r\n if (subdomain === '') {\r\n // Public part\r\n res.sendFile(path.join(__dirname, '../public', 'index.html'));\r\n } else if (subdomain.indexOf('admin') !== -1) {\r\n // Admin part\r\n res.sendFile(path.join(__dirname, '../admin/js', 'index.html'));\r\n } else {\r\n // Static files\r\n res.sendFile(path.join(__dirname, '../', req.url));\r\n }\r\n});\n```\n\n\r\n\r\n\r\n\nThis solution works fine. It captures all requests and serve the right index.html for each subdomain.\n\n**PROBLEM** -> \nI would like to pass the public part of the project in VueJS, and specifically using **Nuxt** to benefit from server-side rendering. I'm new to Nuxt so don't understand yet every details of this framework.\n\nI saw it is possible to serve an universal app with Express, but I have no idea of how to make it compatible with my current solution. \n\nAny help would be appreciated!\nThanks\n\n========================================\n\nTop Answer:\nI used express static files to do what you're asking, if you want to read more, you can do it at http://expressjs.com/en/starter/static-files.html\n\nFirst of all, in your \"app.js\" file you have to add this two lines:\n\n```\napp.use('/public', express.static(__dirname +'../public'));\napp.use('/admin', express.static(__dirname +'../admin/js'));\n```\n\nAfter that, you have to check the index.html from both front-end projects, and make sure each of them has the correct base href. For example, \n\npublic/index.html should have:\n\n```\n\n```\n\nadmin/index.html should have:\n\n```\n\n```\n\nI hope it works for you!\n\n========================================\n\nCode:\n```js\napp.get('*', (req, res) => {\n var firstIndex = req.get('host').indexOf('.');\n var subdomain = req.get('host').substr(0, firstIndex).toLowerCase();\n if (subdomain === '') {\n // Public part\n res.sendFile(path.join(__dirname, '../public', 'index.html'));\n } else if (subdomain.indexOf('admin') !== -1) {\n // Admin part\n res.sendFile(path.join(__dirname, '../admin/js', 'index.html'));\n } else {\n // Static files\n res.sendFile(path.join(__dirname, '../', req.url));\n }\n});\n```\n\n```text\napp.get('*', (req, res, next) => {\n var firstIndex = req.get('host').indexOf('.');\n var subdomain = req.get('host').substr(0, firstIndex).toLowerCase();\n if (subdomain === '') {\n // Public part, call next() to use the nuxt middleware!\n next();\n } else if (subdomain.indexOf('admin') !== -1) {\n // Admin part\n res.sendFile(path.join(__dirname, '../admin/js', 'index.html'));\n } else {\n // Static files\n res.sendFile(path.join(__dirname, '../', req.url));\n }\n});\n\n// The nuxt middleware\napp.use(nuxt.render);\n```\n\n```text\n// If Public part, response Nuxt server render app.\napp.use((req, res, next) => {\n var subdomain = req.get('host').substr(0, firstIndex).toLowerCase();\n if (subdomain === '') {\n // Public part, call nuxt.render middleware\n nuxt.render(req, res, next);\n } else {\n next();\n }\n});\n\n// admin / static files\napp.get('*', (req, res, next) => {\n var firstIndex = req.get('host').indexOf('.');\n var subdomain = req.get('host').substr(0, firstIndex).toLowerCase();\n if (subdomain.indexOf('admin') !== -1) {\n // Admin part\n res.sendFile(path.join(__dirname, '../admin/js', 'index.html'));\n } else {\n // Static files\n res.sendFile(path.join(__dirname, '../', req.url));\n }\n});\n```\n\n```text\nnuxt.render\n```\n\n```text\nnext()\n```\n\n```text\napp.use('/public', express.static(__dirname +'../public'));\napp.use('/admin', express.static(__dirname +'../admin/js'));\n```\n\n```text\n<base href=\"/public/\">\n```\n\n```text\n<base href=\"/admin/\">\n```\n\n========================================\n\nComments:\n- Thank you Felipe but it is that I have already (to manage to single page application) and it works perfectly. I would like to pass one SPA into an universal app (which use server side rendering) and my doubt is: how to configure my server to do this?","metadata":{"transformedAt":"2026-08-18T18:33:07.903Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":168,"estimatedTokens":1118}}919{"id":"stack-50682539","source":"stackoverflow","questionId":50682539,"title":"Why can't I build this nuxtjs app inside docker, while local builds work?","tags":["webpack","sass","nuxt.js"],"text":"Title: Why can't I build this nuxtjs app inside docker, while local builds work?\nTags: webpack, sass, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm developing this nuxtjs project on a Mac (all the latest and greatest) and local builds and generation work fine. I'm using `sass-loader` as a dev dependency, and my `nuxt.config.js` file is not very different from the default:\n\n```\nmodule.exports = {\n head: {\n title: 'temp-www',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: 'Nuxt.js project' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n modules: [\n [ 'nuxt-fontawesome', {\n component: 'fa',\n imports: [\n { set: '@fortawesome/fontawesome-free-brands' },\n ]\n }],\n ],\n loading: { color: '#3B8070' },\n build: {\n extend (config, { isDev, isClient }) {\n if (isDev && isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n }\n }\n}\n```\n\nI then created a `Dockerfile` like this\n\n```\nFROM node:stretch\n\nENV NODE_ENV=production\nENV HOST=0.0.0.0\n\nRUN mkdir -p /app\nCOPY . /app\nWORKDIR /app\n\nEXPOSE 3000\n\nRUN npm install\nRUN npm run build\nCMD [\"npm\", \"start\"]\n```\n\n(and appropriate `.dockerignore`) but I get the following error while building the image.\n\n```\nERROR in ./layouts/default.vue\nModule not found: Error: Can't resolve 'sass-loader' in '/app/layouts'\n @ ./layouts/default.vue 2:2-436\n @ ./.nuxt/App.js\n @ ./.nuxt/index.js\n @ ./.nuxt/client.js\n```\n\nIn there, and in other `.vue` files, I use sass in a block like ``. I tried changing that to `sass` but it makes no difference.\n\nStrangely, this question says it should work by making `sass-loader` and `node-sass` as runtime deps, not devtime deps. I skeptically tried that, and it got worse, until I changed the `lang` attribute in the `style` blocks to `scss` instead of `sass`. In this case, and this case only, I got the image built correctly.\n\nWhat am I missing?\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n head: {\n title: 'temp-www',\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: 'Nuxt.js project' }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n modules: [\n [ 'nuxt-fontawesome', {\n component: 'fa',\n imports: [\n { set: '@fortawesome/fontawesome-free-brands' },\n ]\n }],\n ],\n loading: { color: '#3B8070' },\n build: {\n extend (config, { isDev, isClient }) {\n if (isDev && isClient) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n }\n }\n}\n```\n\n```text\nFROM node:stretch\n\nENV NODE_ENV=production\nENV HOST=0.0.0.0\n\nRUN mkdir -p /app\nCOPY . /app\nWORKDIR /app\n\nEXPOSE 3000\n\nRUN npm install\nRUN npm run build\nCMD [\"npm\", \"start\"]\n```\n\n```text\nERROR in ./layouts/default.vue\nModule not found: Error: Can't resolve 'sass-loader' in '/app/layouts'\n @ ./layouts/default.vue 2:2-436\n @ ./.nuxt/App.js\n @ ./.nuxt/index.js\n @ ./.nuxt/client.js\n```\n\n```text\nsass-loader\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nDockerfile\n```\n\n```text\n.dockerignore\n```\n\n```text\n.vue\n```\n\n```text\n<style lang=\"scss\">\n```\n\n```text\nsass\n```\n\n```text\nsass-loader\n```\n\n```text\nnode-sass\n```\n\n```text\nlang\n```\n\n```text\nstyle\n```\n\n```text\nscss\n```\n\n```text\nsass\n```\n\n```text\nnpm install sass-loader --save-dev\n```\n\n```text\nnpm install sass-loader --save\n```\n\n```text\nsass-loader\n```\n\n```text\nnpm install\n```\n\n========================================\n\nComments:\n- (I am using `sass-loader`). By doing what you suggest, I would still need to include the `node_modules` directory, or at least the modules that are specified in `nuxt.config.js`. The alternative is to `generate` and serve as static files. I would prefer to use the `build` rather than the `generate`d code, if possible.\n- and you have install sass-loader as dependency (`--save`) or devDependency (`--save-dev`) ? If you want use NODE_ENV \"production\", you have to use `--save` as explain before. About my last suggestion, it's just a philosophy from continuous delivery \"Build binaries only once, Deploy anywhere\". Make a complete `build` with node_modules with a CI platform (Jenkins, Travis, GitlabCI), and deploy it every where :)\n- `sass-loader` was a devDependency, and I was making a `build`. The problem, as you say, is that devDependencies are ignored in `production` – which I hadn't considered, I thought it was more like a build-time/run-time thing. The problem with `build`ing, whether locally or in CI, is that webpack has `modules` in its config that need to be available at run-time. In my case, `sass` was not an issue, because once building was done, it was done. However, I has a module in webpack's modules. Isn't there a way of telling webpack to pull these modules into the build? `nuxt generate` seems to do it.\n- I'm confused, I re-did a `build` inside Docker and I didn't have issues with stuff needing to be in `node_modules`. I must have done something wrong yesterday.","metadata":{"transformedAt":"2026-08-18T18:33:07.903Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":221,"estimatedTokens":1326}}920{"id":"stack-68071808","source":"stackoverflow","questionId":68071808,"title":"How to send the content of v-file-input?","tags":["vue.js","nuxt.js","vuetify.js"],"text":"Title: How to send the content of v-file-input?\nTags: vue.js, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nMy component is something like this:\n\n```\n\n \n \n Upload\n \n\nexport default {\n data(){\n return {\n image: null\n }\n },\n methods: {\n async uploadImage(){\n await this.$axios.put('url', {image: this.image})\n }\n }\n}\n\n```\n\nIf I click the button and send the request, the request payload is `{image: {}}`. Why? How to send the content of `this.image`?\n\n========================================\n\nTop Answer:\nJust send file with FormData. You can put this code into uploadImage():\n\n```\nlet form = new FormData();\nform.append(file, this.file);\nthis.$axios.post('url', form)\n```\n\nAnd then U can access it in server.\n\n========================================\n\nCode:\n```html\n<template>\n <div>\n <v-file-input accept=\"image/*\" v-model=\"image\"></v-file-input>\n <button @click=\"uploadImage\">Upload</button>\n </div>\n</template>\n\n<script>\nexport default {\n data(){\n return {\n image: null\n }\n },\n methods: {\n async uploadImage(){\n await this.$axios.put('url', {image: this.image})\n }\n }\n}\n</script>\n```\n\n```text\n{image: {}}\n```\n\n```text\nthis.image\n```\n\n```text\nPOST\n```\n\n```text\nPUT\n```\n\n```text\nconsole.log(this.image)\n```\n\n```text\nmultipart/form-data\n```\n\n```text\nlet form = new FormData();\nform.append(file, this.file);\nthis.$axios.post('url', form)\n```\n\n```text\naddImage (file) {\n if (file) {\n const reader = new FileReader()\n\n reader.onload = (e) => {\n const imgObj = new Image()\n // console.log(e.target.result)\n imgObj.src = e.target.result\n // console.log(imgObj)\n this.imageHandler = imgObj\n }\n if (file) {\n reader.readAsDataURL(file)\n }\n } else {\n console.log('error')\n }\n }\n```\n\n```text\nconst reader = new FileReader()\n\nconst imgObj = new Image()\n\nimgObj.src = e.target.result\n```\n\n```text\nthis.imageHandler = imgObj\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.903Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":133,"estimatedTokens":479}}921{"id":"stack-48918960","source":"stackoverflow","questionId":48918960,"title":"Using class model in Vue.js?","tags":["vue.js","nuxt.js"],"text":"Title: Using class model in Vue.js?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\ni'm making CRUD admin tool using Nuxt.js (Vue.js SSR framework)\nbut when object more nested, it is difficult to handling this objects.\n\nfor example, when i have object like this\n\nin A.vue file\n\n```\ndata: () => ({\n page: {\n language: \"\",\n background: \"\",\n content: { \n title: \"\",\n age: {\n male: [\".......\"],\n female: [\"....\"]\n } \n }\n ...and more complex\n }\n})\n```\n\ni want using class model like this,\n\nin A.vue file \n\n```\ndata: () => ({\n page: new Page();\n})\n```\n\nin Class files...\n\n```\nclass Page() {\n language, background, content properties...\n}\nclass Content() {\n title, age properties...\n}\nclass Age() {\n male, female properties...\n}\n```\n\nbut class is not a pure object, it does not match the concept of vue.js\n(Vue will walk through all of its properties and convert them to getter/setters using Object.defineProperty.)\n\nso, i used util function that get data, and returning page object\nwith default values,\n\nin A.vue\n\n```\ndata: () => ({\n page: getPageObject()\n})\n```\n\nin PageUtils.js\n\n```\nfunction getPageObejct(data) {\n return {\n ....data,\n language: 'en',\n background: '',\n content: {\n title: 'title'\n ....\n }\n }\n }\n```\n\n...but i don't think that best way of handle complex data\n\nhow can i using class or other mapping model \nfor convenient using data? (default value, method..)\n\n========================================\n\nCode:\n```text\ndata: () => ({\n page: {\n language: \"\",\n background: \"\",\n content: { \n title: \"\",\n age: {\n male: [\".......\"],\n female: [\"....\"]\n } \n }\n ...and more complex\n }\n})\n```\n\n```text\ndata: () => ({\n page: new Page();\n})\n```\n\n```text\nclass Page() {\n language, background, content properties...\n}\nclass Content() {\n title, age properties...\n}\nclass Age() {\n male, female properties...\n}\n```\n\n```text\ndata: () => ({\n page: getPageObject()\n})\n```\n\n```text\nfunction getPageObejct(data) {\n return {\n ....data,\n language: 'en',\n background: '',\n content: {\n title: 'title'\n ....\n }\n }\n }\n```\n\n========================================\n\nComments:\n- Use state management. You don't have to clatter all of the data in a component, rather make a store for each module in your app. I have a multiple store sample in one of my github project. You check it our here. github.com/jofftiquez/wakeupbilliejoe.com\n- i don't think it about store concept ....\n- i'm using nuxt.js, component fetching data and using it directly.. so i want to mapping model for fetched data. it not about store concept. and Immutable.js not compatible with Vue.js...? here is link about that forum.vuejs.org/t/immutable-js-with-vue/6366\n- it is better using store management like vuex if handle common data for components.. but when fetching data from server and using it directly, store is not necessarily needed.\n- i'm focus on using fetched data directly in component using mapping model (just like es6 class)...\n- Yep. I suspect this is a recipe for making life needlessly harder. As others have noted, Vue's event model is not sophisticated. You're fine as long as your data is used ***only within your component***, but the lesson of history is that just about every item of app state will eventually have more than one representation on screen, and then you're in trouble.","metadata":{"transformedAt":"2026-08-18T18:33:07.903Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":155,"estimatedTokens":857}}922{"id":"stack-63100693","source":"stackoverflow","questionId":63100693,"title":"Nuxt Efficient Cache","tags":["caching","nuxt.js","workbox"],"text":"Title: Nuxt Efficient Cache\nTags: caching, nuxt.js, workbox\nSource: Stack Overflow\n\nQuestion:\n*Serve static assets with an efficient cache policy*. I get this if I audit my app. I added this code to nuxt.config but this would help.\n\n```\nrender: {\n static: {\n maxAge: 2592000\n }\n},\n```\n\nits by default caching static assets 1h in browser. **Where can I change it. or How?**\n\n========================================\n\nCode:\n```text\nrender: {\n static: {\n maxAge: 2592000\n }\n},\n```\n\n```text\n// in firebase.json\n\"hosting\": {\n // ...\n\n // Add the \"headers\" attribute within \"hosting\", override cache control\n \"headers\": [ {\n \"source\": \"**/*.@(jpg|jpeg|gif|png)\",\n \"headers\": [ {\n \"key\": \"Cache-Control\",\n \"value\": \"max-age=2592000\"\n } ]\n }\n ]\n}\n```\n\n========================================\n\nComments:\n- Are you sure lighthouse is complaining about your own files, and not 3rd party files? Often things like Stripe or Intercom get flagged by Lighthouse as being served without an efficient cache policy, despite there being nothing you can do about it.\n- Yes they are my own files i can reach them by mywebsite.com/img/image.jpg\n- are you running an reverse proxy infront of your nuxt app? if yes your reverse proxy could add an cache control header to it\n- no i use static generate and host on firebase","metadata":{"transformedAt":"2026-08-18T18:33:07.903Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":52,"estimatedTokens":332}}923{"id":"stack-70980186","source":"stackoverflow","questionId":70980186,"title":"Bootstrap-vue: How to hide the v-b-tooltip when you hover on the tooltip itself (not the button)","tags":["css","vue.js","nuxt.js","bootstrap-vue"],"text":"Title: Bootstrap-vue: How to hide the v-b-tooltip when you hover on the tooltip itself (not the button)\nTags: css, vue.js, nuxt.js, bootstrap-vue\nSource: Stack Overflow\n\nQuestion:\nI have buttons that are close to each other that when the tooltip pops out it would block the other buttons out, here's a picture of the said problem:\n\nhttps://i.sstatic.net/66IGG.png\n\nIf I hover the request button below the other one and then tries to hover the button above it, I will end up hovering on the tooltip instead of the button below it.\n\nI can hide the tooltip on hover (see code below) using CSS but it produces a flickering effect when I hover to the next button then ends up not showing the tooltip on that specific next button.\n\n```\n.tooltip:hover {\n display: none;\n}\n```\n\nSo my questions would be:\n\n- Is there a property on `bootstrap-vue` that would only show the tooltip when hovered on the button itself;\n\n- or hide the tooltip when hovering the tooltip itself;\n\n- If none, any alternative that would replicate the behavior I wanted without needing to change or edit each existing button on my app (*preferred*).\n\n========================================\n\nTop Answer:\nAlternative solution:\n\nAdd an event listener as to when the mouse leaves/(un)hover the button and hide all tooltips:\n\n```\n\n The Button\n\n```\n\nThe con with this is that you'll have to edit this to all existing buttons on other tables. That's why I'm still open to other more easier and general solution than this.\n\nBoostrap-vue Documentation: How to hide all open tooltips\n\n========================================\n\nCode:\n```css\n.tooltip:hover {\n display: none;\n}\n```\n\n```text\nbootstrap-vue\n```\n\n```js\nnew Vue({\n el: \"#app\"\n});\n```\n\n```html\n<link type=\"text/css\" rel=\"stylesheet\" href=\"//unpkg.com/bootstrap@4.5.3/dist/css/bootstrap.min.css\" />\n<link type=\"text/css\" rel=\"stylesheet\" href=\"//unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.css\" />\n\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.min.js\"></script>\n<script src=\"https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.js\"></script>\n\n<div id=\"app\" class=\"p-5\">\n <b-button v-b-tooltip.noninteractive.hover title=\"Try and hover me!\">\n Hover me\n </b-button>\n</div>\n```\n\n```text\nnoninteractive\n```\n\n```html\n<button\n v-b-tooltip.hover=\"'Edit This Bish'\"\n @mouseleave=\"$root.emit('bv::hide::tooltip')\"\n>\n The Button\n</button>\n```\n\n```html\n<div v-b-tooltip.noninteractive=\"{title: `I'm a tooltip`}\">Hover me!</div>\n```\n\n========================================\n\nComments:\n- Would it be helpfull to reposition the tooltips on the left and on the right?\n- @wittgenstein That was what I thought at first, but the problem would persist on adjacent buttons. I have some tables with four buttons that are close to each other so this wouldn't help.\n- Thanks! Completely missed that! Is it better in any way, like performance-wise than my answer? If none, I won't be bothered in changing my existing fix that I've implemented for each button in my app 😅. Though, I would choose this as the answer as it is more inline with bootstrap-vue rather than my hacky approach.\n- Also can you think of an alternative solution using CSS, so that I'll just write the code once on my stylesheet instead of editing the each existing button property on my app?\n- If you're using the component `` you can use the configuration to set up global defaults for props. However I don't recall whether these also work for directives.\n- Unfortunately I don't use the component itself, only its property equivalent for my buttons, but what you've shared is definitely the right direction, I'll try to make it work on my `nuxt` config\n- It seems to only work on components. Wasn't able to make it work on my `nuxt.config.js` file sadly.","metadata":{"transformedAt":"2026-08-18T18:33:07.903Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":104,"estimatedTokens":941}}924{"id":"stack-51658044","source":"stackoverflow","questionId":51658044,"title":"Vue: method is not a function within inline-template component tag","tags":["vue.js","vuejs2","vue-component","nuxt.js"],"text":"Title: Vue: method is not a function within inline-template component tag\nTags: vue.js, vuejs2, vue-component, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have this component:\n\n```\n\n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n {{ result.description }}\n\n \n \n Created: {{ result.created_at }}\n \n \n \n \n \n \n \n {{ result.description }}\n\n \n \n Created: {{ result.created_at }}\n \n \n \n \n \n \n \n \n \n Close\n Save changes\n \n \n \n \n\n import Algolia from '@/components/algolia/menu';\n\n export default {\n components: {\n \"algolia-menu\": Algolia,\n },\n data() {\n return {\n category: 'category',\n };\n },\n methods: {\n getTemplate(result) {\n console.log(result)\n }\n }\n }\n\n```\n\nI have a click listener on the `.card` div within my `` tag which calls my `getTemplate` method. But, whenever I click on that element, it produces this error:\n\n imageModal.vue?8d74:85 Uncaught TypeError: _vm.getTemplate is not a\n function\n at click (imageModal.vue?8d74:85)\n at invoker (vue.runtime.esm.js:2023)\n at HTMLDivElement.fn._withTask.fn._withTask\n\nWhy is this happening? I have tried `@click.native` as well, but that didn't work.\n\n========================================\n\nCode:\n```text\n<template>\n <div class=\"modal fade modal-primary\" id=\"imageModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"ImageLabel\"\n aria-hidden=\"true\">\n <div class=\"modal-dialog modal-lg animated zoomIn animated-3x\">\n <div class=\"modal-content\">\n <ais-index index-name=\"templates\"\n app-id=\"BZF8JU37VR\"\n api-key=\"33936dae4a732cde18cc6d77ba396b27\">\n <div class=\"modal-header\">\n <algolia-menu :attribute=\"category\"\n :class-names=\"{ 'nav-item__item': 'nav-color', 'nav-item__link': 'nav-link', 'nav-item__item--active': 'active'}\">\n </algolia-menu>\n </div>\n\n <div class=\"modal-body\">\n <div class=\"container\">\n <ais-results :results-per-page=\"10\" inline-template>\n <div class=\"row\">\n <div class=\"col-6\" v-for=\"result in results.slice(0, 5)\" :key=\"result.objectID\">\n <div class=\"card\" @click=\"getTemplate(result)\">\n <img class=\"img-fluid\" v-lazy=\"result.image\"/>\n <div class=\"card-body\">\n <p>{{ result.description }}</p>\n </div>\n <div class=\"card-footer\">\n <small>Created: {{ result.created_at }}</small>\n </div>\n </div>\n </div>\n <div class=\"col-6\" v-for=\"result in results.slice(5, 10)\" :key=\"result.objectID\">\n <div class=\"card\">\n <img class=\"img-fluid\" v-lazy=\"result.image\"/>\n <div class=\"card-body\">\n <p>{{ result.description }}</p>\n </div>\n <div class=\"card-footer\">\n <small>Created: {{ result.created_at }}</small>\n </div>\n </div>\n </div>\n </div>\n </ais-results>\n </div>\n </div>\n </ais-index>\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-danger\" data-dismiss=\"modal\">Close</button>\n <button type=\"button\" class=\"btn btn-primary\">Save changes</button>\n </div>\n </div>\n </div>\n </div>\n</template>\n\n<script>\n import Algolia from '@/components/algolia/menu';\n\n export default {\n components: {\n \"algolia-menu\": Algolia,\n },\n data() {\n return {\n category: 'category',\n };\n },\n methods: {\n getTemplate(result) {\n console.log(result)\n }\n }\n }\n</script>\n```\n\n```text\n.card\n```\n\n```text\n<ais-results>\n```\n\n```text\ngetTemplate\n```\n\n```text\n@click.native\n```\n\n```text\n<ais-results :results-per-page=\"10\" inline-template @card-click=\"getTemplate\">\n <div class=\"row\">\n <div class=\"col-6\" v-for=\"result in results.slice(0, 5)\" :key=\"result.objectID\">\n <div class=\"card\" @click=\"$emit('card-click', result)\">\n ...\n </div>\n </div>\n </div>\n</ais-results>\n```\n\n```text\n<ais-results>\n```\n\n```text\n<ais-results>\n```\n\n```text\ngetTemplate\n```\n\n```text\n<ais-results>\n```\n\n```text\ngetTemplate\n```\n\n```text\nresult\n```\n\n```text\n<ais-results>\n```\n\n```text\n.card\n```\n\n```text\ncard-click\n```\n\n```text\n@click=\"$emit('card-click', result)\"\n```\n\n```text\n<ais-results>\n```\n\n```text\n@card-click=\"getTemplate\"\n```\n\n```text\ncard-click\n```\n\n```text\ngetTemplate\n```\n\n```text\nresult\n```\n\n========================================\n\nComments:\n- what do you mean by that @thanksd\n- it does... at the bottom of the code\n- Ok very sorry for the confusion. For some reason cmd f didn’t pick up the `getTemplate` reference in your template. The issue is that you’re using an inline template for your `` component tag, so the data references for the elements within that tag are scoped to the `` instance. This means Vue is looking for a `getTemplate` method on the `` component, but not finding it.\n- What if I don't have an actual event. What if I just need to access a function from the 'outside' of the `ais-results` tag?\n- That specific component provides a default slot that you could use instead of an inline template. Otherwise, if you are the owner of a component using an inline template, you could pass the function as a prop.","metadata":{"transformedAt":"2026-08-18T18:33:07.903Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":264,"estimatedTokens":1361}}925{"id":"stack-49451899","source":"stackoverflow","questionId":49451899,"title":"passing data to dynamicaly created siblings","tags":["vuejs2","vuex","nuxt.js"],"text":"Title: passing data to dynamicaly created siblings\nTags: vuejs2, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am struggling to get the answer to a what I think is an simple question, without success. I'm new to Vue.\n\n**Description:**\n\nLet's take the use case of a \"dot navigation\" of a website. This will be a component (DotSideNavi) which will render with a v-for loop 4 \"dots\" components (DotNaviElem). \n\n**Actions:**\n\nWhen clicking on one \"dot\", \n\n- all others need to be deactivated(remove active class) and\n\n- the clicked one need to be activated right after\n\n**Try and Fail:** \n\nI tried using the `$emit` and `$on`, both at the \"dot\" el, so when clicking on one \"dot\" I was expecting the event to be passed to all the 4 \"dots\". Instead, the event was triggered 4 times for the same \"dot\" el only. \n\n`Vuex`: Tried do implement the same logic, but again the state was changed only for the clicked \"dot\" \n\n- Passing data back and forth from child-parent-child is considered a bad practice\n\n- Identifying each dot and using that to deactivate them seems like the wrong way to solve this.\n\n- From what I read about `slots`, they seem not relevant\n\n**Code (simplified):**\n\n```\n\n \n \n />\n \n\n import DotNaviElem from '~/atoms/DotNaviElem.vue';\n\n export default {\n components: {\n DotNaviElem\n }\n };\n\n \n \n \n\n export default {\n data() {\n return {\n isCurrentSlide: false\n };\n },\n\n methods: {\n activateDotNaviElem() {\n this.isCurrentSlide = !this.isCurrentSlide;\n }\n }\n };\n\n```\n\n**Requirements:**\n\nno other external libraries are allowed.. \n\n**Framework:**\n\nNuxt, Vue, Vuex\n\n**Question**:\n\nCan somebody explain me what's the \"vue\" way to code this and point me to the right resources? This has to be simpler than it looks now. \n\n**Bonus:**\n\nI would appreciate a quick explanation on why 1. and 2. (Try and Fail) are not triggering events/state changes for all the \"dot\" components? \n\n**Repository**\n\nYou can find in the following repository, a project with this example included:\n\n https://github.com/stavros-liaskos/nuxt-fun\n\nRelevant files:\n\ncomponents/DotSideNavi.vue (navigation)\n\natoms/DotNaviElem.vue (dot element)\n\n========================================\n\nCode:\n```text\n<!-- Side Dot Navi -->\n<template>\n <div class=\"dot-side-nav\">\n <dot-navi-elem v-for=\"(n, index) in 4\"\n v-bind:key=\"index\"\n v-bind:class=\"{ 'active': index === 0 }\" <!-- just dummy init for activating first dot -->\n />\n </div>\n</template>\n\n<script>\n import DotNaviElem from '~/atoms/DotNaviElem.vue';\n\n export default {\n components: {\n DotNaviElem\n }\n };\n</script>\n\n<!-- Dot Navi Element used for Side Dot Navi -->\n<template>\n <span class=\"dot-wrapper \"\n v-bind:class=\"{ active: isCurrentSlide}\"\n v-on:click=\"activateDotNaviElem()\"\n >\n <span class=\"dot\"></span>\n </span>\n</template>\n\n<script>\n export default {\n data() {\n return {\n isCurrentSlide: false\n };\n },\n\n methods: {\n activateDotNaviElem() {\n this.isCurrentSlide = !this.isCurrentSlide;\n }\n }\n };\n</script>\n```\n\n```text\n$emit\n```\n\n```text\n$on\n```\n\n```text\nVuex\n```\n\n```text\nslots\n```\n\n```js\nVue.component('dot-navigation', {\n\tdata() {\n \treturn {\n \tindex: 0\n }\n },\n template: '<div><p>{{ index }}</p><dot-navigation-element v-for=\"(n, index) in 4\" v-bind:key=\"index\" v-on:test=\"setActive\" :index=\"n\" /></div>' ,\n methods: {\n \tsetActive(index) {\n \tconsole.log(\"sdf\")\n \tthis.index = index\n }\n }\n});\n\nVue.component('dot-navigation-element', {\n\tprops: ['index'],\n template: '<span v-on:click=\"activate\">dot</span>',\n methods: {\n \tactivate() {\n \tconsole.log(\"activate\");\n \tthis.$emit('test', this.index)\n }\n }\n \n});\n\n// create a new Vue instance and mount it to our div element above with the id of app\nvar vm = new Vue({\n el: '#app'\n});\n```\n\n```html\n<div id=\"app\">\n <dot-navigation></dot-navigation>\n</div>\n```\n\n========================================\n\nComments:\n- Can you provide a fiddle?\n- @Borjante I edited my original post to include an example of the above\n- As far as I understand, in the above snippet, the parent (dot-navigation) can identify which child (dot-navigation-element) is clicked but will not deactivate the rest of them, which is actually the expected result.\n- Now you would just need to pass down to the elements the active index, and then, each element will have to check if their index is == to the active element.","metadata":{"transformedAt":"2026-08-18T18:33:07.903Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":210,"estimatedTokens":1136}}926{"id":"stack-62526975","source":"stackoverflow","questionId":62526975,"title":"redirect default '/' to a specific path nuxt / netlify","tags":["vuejs2","nuxt.js","vue-router"],"text":"Title: redirect default '/' to a specific path nuxt / netlify\nTags: vuejs2, nuxt.js, vue-router\nSource: Stack Overflow\n\nQuestion:\nBasically I want the root route `'/'` to be redirected to my `'/home'` route.\n\nMy Nuxt app is hosted on Netlify so I tried to do this is the `_redirects` file\n\n```\n/ /home\n```\n\nas per their redirect docs - but it's not working.\n\nNow I know that in Vue in the router config you can set up redirects, but how do I achieve the same thing in Nuxt??\n\nany help would be appreciated!\n\n========================================\n\nCode:\n```text\n/ /home\n```\n\n```text\n'/'\n```\n\n```text\n'/home'\n```\n\n```text\n_redirects\n```\n\n```text\n<script>\n export default {\n middleware: 'redirect'\n }\n</script>\n```\n\n```text\nexport default function ({ store, redirect }) {\n return redirect('/home')\n}\n```\n\n```text\nindex.vue\n```\n\n```text\nredirect.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.903Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":59,"estimatedTokens":215}}927{"id":"stack-62452822","source":"stackoverflow","questionId":62452822,"title":"In Nuxt w/ Express how to prevent re-compilation when saving server","tags":["nuxt.js"],"text":"Title: In Nuxt w/ Express how to prevent re-compilation when saving server\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt with an Express server as a backend, and I'm building a Rest API on the backend, whenever I make any changes to the `server/index.js` file it recompiles the client and server, is there anyway to prevent that? It slows things down a lot having to wait 5-8 seconds every time I make a change to the API.\n\nI don't see any reason the entire system needs to be recompiled since the server restarts with Nodemon.\n\nIs there anyway around this? I've tried speeding up the build process and it helps a bit but not enough. On a Non Nuxt express server saving a change takes less than 300 milliseconds.\n\nhttps://i.sstatic.net/fzA03.png\n\n========================================\n\nTop Answer:\nYou are using your app in develop mode, so in this way whenever any file is changed nuxt will recompile the application to automatically display your changes in your browser.\n\nInstead of using developer mode\n\n```\nnpm run dev\n```\n\nyou can choose to run in production mode\n\n```\nnpm start\n```\n\nAnother thing is you say that when you change some file in your Api, your Nuxt recompiles, I don't know why you use the Api path within the same Nuxt directory.\n\nHowever, you can exclude \"monitoring\" of specific files and folders when using the nodemon. Just create a file called nodemon.json in your Nuxt's root folder.\n\nTake a look nodemon docs: https://github.com/remy/nodemon#ignoring-files\n\nNow insert something like this:\n\n```\n{ \n \"ignore\": [\"logs\", \"dist\", \".nuxt\", \"file.js\"] \n}\n```\n\nAnd voilá, now the nodemon will no longer monitor these folders and files.js\n\n========================================\n\nCode:\n```text\nserver/index.js\n```\n\n```text\nif (config.dev) {\n const builder = new Builder(nuxt)\n await builder.build()\n}\n```\n\n```text\nnpm run dev\n```\n\n```text\nuncommented\n```\n\n```text\nnpm run dev\n```\n\n```text\ncomment out\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm start\n```\n\n```text\n{ \n \"ignore\": [\"logs\", \"dist\", \".nuxt\", \"file.js\"] \n}\n```\n\n```text\nconst clientRefresh = !fs.existsSync(\"./nuxt-build.txt\");\n if (config.dev && clientRefresh) {\n const builder = new Builder(nuxt);\n await builder.build();\n fs.writeFile(\"nuxt-build.txt\", new Date() + \"\", { flag: \"wx\" }, function (err) {\n if (err) throw err;\n });\n }\n```\n\n```text\n\"scripts\": {\n \"dev\": \"rm -f nuxt-build.txt && cross-env NODE_ENV=development nodemon server/index.js --watch server\",\n }\n```\n\n```text\nnpm run dev\n```\n\n```text\n//\nwatchers: {\n chokidar: {\n ignored: /(server)/\n },\n webpack: {\n ignored: /(server)/\n }\n},\n//\n```\n\n========================================\n\nComments:\n- I want nodemon to monitor the server files and restart the server, what I'm trying to avoid is completely re-compiling the entire system. Also whenever I make changes to template files I do want those changes to automatically display in the browser, so unfortunately none of those solutions really solve the issue\n- If you don't recompile the changes, nuxt cannot displayed this for you. No make sense for me, because if you make any changes, the server need be recompile to display this updates.\n- Nuxt generate static files (compiled) inside .nuxt folder. Every change need be re-compiled after update some file, and recompiled to be \"attached\"in .nuxt path. No make sense \"disable\" recompile. Nuxt is a server running a lot of things. You need compile, generate your file to be converted to HTML.\n- The files I'm talking about are not HTML files they are server API files, the server needs rebooted but I don't see the need to recompile any files.","metadata":{"transformedAt":"2026-08-18T18:33:07.903Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":131,"estimatedTokens":918}}928{"id":"stack-61939898","source":"stackoverflow","questionId":61939898,"title":"Why does the scoped styles are not being loaded in nuxt page?","tags":["css","vue.js","css-selectors","nuxt.js"],"text":"Title: Why does the scoped styles are not being loaded in nuxt page?\nTags: css, vue.js, css-selectors, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have two freshsales form as separate components in a nuxt site(say formA and formB).I have written styles overriding the default form styles which is scoped to those form components.But when I use them in a page the scoped styles are not being loaded and applied.\n\nIf I try the same without scoping,I am getting styles being applied.But formA styles is being applied for any page using formB component also.(which is expected as nuxt/vue app is concerned).\n\nWhy my scoped styles are not working?\n\nI'll leave the sample code below.\n\n//contactForm.vue\n//xxx refers to the unique id\n\n```\n\n \n \n \n\n.fserv-form {\n border-radius: 10px;\n padding: 20px;\n position: relative;\n font-family: Arial, sans-serif;\n}\n.fserv-field:nth-child(3){\n width: 187px;\n padding-right: 5px;\n display: inline-block;\n}\n.fserv-field:nth-child(5){\n width: 140px;\n padding: 0;\n display: inline-block;\n}\n@media screen and (max-width: 360px) {\n .fserv-field:nth-child(3) {\n width: 135px;\n }\n .fserv-field:nth-child(5) {\n width: 110px;\n }\n}\n@media screen and (max-width: 986px) and (min-width: 525px){\n .fserv-field:nth-child(3),.fserv-field:nth-child(5) {\n width: 100%;\n padding: 0 30px/*! * Datetimepicker for Bootstrap 3 * ! version : 4.7.14 * https://github.com/Eonasdan/bootstrap-datetimepicker/ */;\n display: block;\n }\n}\n\n```\n\n//register.vue\n\n```\n\n \n \n \n \n \n\n.fserv-form {\n border-radius: 10px;\n padding: 20px;\n position: relative;\n font-family: Arial, sans-serif;\n}\n.fserv-field{\n padding: 40px !important;\n}\n.fserv-field:nth-child(3){\n width: 187px;\n padding-right: 5px;\n display: inline-block !important;\n}\n.fserv-field:nth-child(4){\n width: 140px;\n padding: 0;\n display: inline-block !important;\n}\n@media screen and (max-width: 360px) {\n .fserv-field:nth-child(3) {\n width: 135px;\n }\n .fserv-field:nth-child(4) {\n width: 110px;\n }\n}\n@media screen and (max-width: 986px) and (min-width: 525px){\n .fserv-field:nth-child(3),.fserv-field:nth-child(4) {\n width: 100%;\n padding: 0 30px/*! * Datetimepicker for Bootstrap 3 * ! version : 4.7.14 * https://github.com/Eonasdan/bootstrap-datetimepicker/ */;\n display: block;\n }\n}\n\n```\n\nI'm trying to use these components in two different pages.But the problem is if I made the style as scoped,no scopes styles are being applied.If I removed scoped,I'm getting the contact form styles on both pages applied.\n\nAny proper way to do this.I want the styles to be separately applied for each form(like I'm selecting the field like this using css selector `.fserv-field:nth-child(4)`).\n\nOr is there a better way to select the form fields without conflict.The field order would be like 3,4 (in contactForm) whereas 3,5. (in register form)\n\nThank you!\n\n========================================\n\nCode:\n```text\n<template>\n <div>\n <script\n src=\"https://facilio.freshsales.io/web_forms/xxxxxx/form.js\"\n crossorigin=\"anonymous\"\n id=\"xxxxx\"\n ></script>\n </div>\n</template>\n<style scoped>\n\n.fserv-form {\n border-radius: 10px;\n padding: 20px;\n position: relative;\n font-family: Arial, sans-serif;\n}\n.fserv-field:nth-child(3){\n width: 187px;\n padding-right: 5px;\n display: inline-block;\n}\n.fserv-field:nth-child(5){\n width: 140px;\n padding: 0;\n display: inline-block;\n}\n@media screen and (max-width: 360px) {\n .fserv-field:nth-child(3) {\n width: 135px;\n }\n .fserv-field:nth-child(5) {\n width: 110px;\n }\n}\n@media screen and (max-width: 986px) and (min-width: 525px){\n .fserv-field:nth-child(3),.fserv-field:nth-child(5) {\n width: 100%;\n padding: 0 30px/*! * Datetimepicker for Bootstrap 3 * ! version : 4.7.14 * https://github.com/Eonasdan/bootstrap-datetimepicker/ */;\n display: block;\n }\n}\n</style>\n```\n\n```text\n<template>\n <div>\n <script\n src=\"https://facilio.freshsales.io/web_forms/xxxxxx/form.js\"\n crossorigin=\"anonymous\"\n id=\"xxxxx\"\n ></script>\n </div>\n </template>\n <style scoped>\n\n.fserv-form {\n border-radius: 10px;\n padding: 20px;\n position: relative;\n font-family: Arial, sans-serif;\n}\n.fserv-field{\n padding: 40px !important;\n}\n.fserv-field:nth-child(3){\n width: 187px;\n padding-right: 5px;\n display: inline-block !important;\n}\n.fserv-field:nth-child(4){\n width: 140px;\n padding: 0;\n display: inline-block !important;\n}\n@media screen and (max-width: 360px) {\n .fserv-field:nth-child(3) {\n width: 135px;\n }\n .fserv-field:nth-child(4) {\n width: 110px;\n }\n}\n@media screen and (max-width: 986px) and (min-width: 525px){\n .fserv-field:nth-child(3),.fserv-field:nth-child(4) {\n width: 100%;\n padding: 0 30px/*! * Datetimepicker for Bootstrap 3 * ! version : 4.7.14 * https://github.com/Eonasdan/bootstrap-datetimepicker/ */;\n display: block;\n }\n}\n</style>\n```\n\n```text\n.fserv-field:nth-child(4)\n```\n\n```text\n<template>\n <div>\n <script\n src=\"https://facilio.freshsales.io/web_forms/xxxxxx/form.js\"\n crossorigin=\"anonymous\"\n id=\"xxxxx\"\n ></script>\n </div>\n</template>\n<style scoped>\n\n>>> .fserv-form {\n border-radius: 10px;\n padding: 20px;\n position: relative;\n font-family: Arial, sans-serif;\n}\n>>> .fserv-field:nth-child(3){\n width: 187px;\n padding-right: 5px;\n display: inline-block;\n}\n>>> .fserv-field:nth-child(5){\n width: 140px;\n padding: 0;\n display: inline-block;\n}\n@media screen and (max-width: 360px) {\n >>> .fserv-field:nth-child(3) {\n width: 135px;\n }\n >>> .fserv-field:nth-child(5) {\n width: 110px;\n }\n}\n@media screen and (max-width: 986px) and (min-width: 525px){\n >>> .fserv-field:nth-child(3),.fserv-field:nth-child(5) {\n width: 100%;\n padding: 0 30px/*! * Datetimepicker for Bootstrap 3 * ! version : 4.7.14 * \n https://github.com/Eonasdan/bootstrap-datetimepicker/ */;\n display: block;\n }\n}\n</style>\n```\n\n```text\n<template>\n <div>\n <script\n src=\"https://facilio.freshsales.io/web_forms/xxxxxx/form.js\"\n crossorigin=\"anonymous\"\n id=\"xxxxx\"\n ></script>\n </div>\n </template>\n <style scoped>\n\n>>> .fserv-form {\n border-radius: 10px;\n padding: 20px;\n position: relative;\n font-family: Arial, sans-serif;\n}\n>>> .fserv-field{\n padding: 40px !important;\n}\n>>> .fserv-field:nth-child(3){\n width: 187px;\n padding-right: 5px;\n display: inline-block !important;\n}\n>>> .fserv-field:nth-child(4){\n width: 140px;\n padding: 0;\n display: inline-block !important;\n}\n@media screen and (max-width: 360px) {\n >>> .fserv-field:nth-child(3) {\n width: 135px;\n }\n >>> .fserv-field:nth-child(4) {\n width: 110px;\n }\n}\n@media screen and (max-width: 986px) and (min-width: 525px){\n >>> .fserv-field:nth-child(3),.fserv-field:nth-child(4) {\n width: 100%;\n padding: 0 30px/*! * Datetimepicker for Bootstrap 3 * ! version : 4.7.14 * https://github.com/Eonasdan/bootstrap-datetimepicker/ */;\n display: block;\n }\n}\n</style>\n```\n\n```text\n>>>\n```\n\n```text\nscoped\n```\n\n========================================\n\nComments:\n- Great it works, it would be great if you could also guide me how to ignore eslint problems logged in the terminal when using `>>>` operator.\n- Using ::v-deep solved this. Anyway, suggestions on the above comment would also help someone.\n- @mariappan.gameo Glad it helped you. Could you post the ESLint error log? This seems weird since ESLint shouldn't really attempt to lint CSS.\n- Please have a look at the below screenshot (link) ibb.co/j8z5b8T\n- This does not appear to be ESLint. Can you with us what tool you use to lint your CSS? Is it `vscode-stylelint`?\n- I don't think I'm using any special vs code extensions for linting css separately.Just I have prettier and eslint(by Dirk Baeumer) in vscode.","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":326,"estimatedTokens":1955}}929{"id":"stack-61905389","source":"stackoverflow","questionId":61905389,"title":"custom default styles have been removed by PurgeCSS in nuxt-tailwindcss","tags":["nuxt.js","tailwind-css","css-purge"],"text":"Title: custom default styles have been removed by PurgeCSS in nuxt-tailwindcss\nTags: nuxt.js, tailwind-css, css-purge\nSource: Stack Overflow\n\nQuestion:\nIn my SSR Nuxt.js project, I am using Nuxt offical tailwindcss-module\n\nI coded a default style for `` tags like below.\n\n**/assets/scss/app.scss**\n\n```\na{\n color: color(\"blue\", \"base\");\n transition: color .3s ease;\n\n &:hover,&:active{\n color: color(\"blue\", \"darken-4\");\n }\n}\n```\n\n**pages/index.vue**\n\n```\n\n Login\n\n```\n\n**nuxt.config.js**\n\n```\nbuildModules:['@nuxtjs/tailwindcss'],\n css:['@/assets/scss/app.scss']\n```\n\nWhen I run `npm run dev`, the PurgeCSS would not work, so the result is what I expected.\n\nBut when I run `npm run prod`, the PurgeCSS of tailwindcss will remove my own style for `` tags in **'@/assets/scss/app.scss'**\n\nHow can I config `tailwind.config.js` to make custom default styles be rendered in result? Whitelist only accepts classnames/ids.\n\nThanks a lot!\n\n========================================\n\nCode:\n```text\na{\n color: color(\"blue\", \"base\");\n transition: color .3s ease;\n\n &:hover,&:active{\n color: color(\"blue\", \"darken-4\");\n }\n}\n```\n\n```js\n<template>\n <nuxt-link to=\"/login\">Login</nuxt-link>\n</template>\n```\n\n```js\nbuildModules:['@nuxtjs/tailwindcss'],\n css:['@/assets/scss/app.scss']\n```\n\n```text\n<a></a>\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run prod\n```\n\n```text\n<a></a>\n```\n\n```text\ntailwind.config.js\n```\n\n```text\n/* purgecss start ignore */\na {...}\n/* purgecss end ignore */\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":95,"estimatedTokens":375}}930{"id":"stack-74023464","source":"stackoverflow","questionId":74023464,"title":"Typescript giving Error on @click even in simple programs while using nuxt 3","tags":["typescript","nuxt.js","vuejs3","nuxt3.js"],"text":"Title: Typescript giving Error on @click even in simple programs while using nuxt 3\nTags: typescript, nuxt.js, vuejs3, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am getting this error while using @click in Nuxt3 with Typescript\n\n```\nType '($event: any) => void' is not assignable to type 'MouseEvent'.ts(2322)\n__VLS_types.ts(107, 56): The expected type comes from property 'click' which is declared here on type 'EventObject'\n```\n\n========================================\n\nCode:\n```text\nType '($event: any) => void' is not assignable to type 'MouseEvent'.ts(2322)\n__VLS_types.ts(107, 56): The expected type comes from property 'click' which is declared here on type 'EventObject<undefined, \"click\", {}, MouseEvent | undefined>'\n```\n\n```text\n@types/node\n```\n\n```text\n@types/node\n```\n\n```text\n18.11.0\n```\n\n```text\n18.8.0\n```\n\n========================================\n\nComments:\n- Same issue here with nuxt 3.0.0-rc.11\n- Thanks, it worked. I had to delete my package-lock files and nuxt folder before re-installing packages to get it work.","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":41,"estimatedTokens":260}}931{"id":"stack-61729405","source":"stackoverflow","questionId":61729405,"title":"Vue.js How To Manage nuxt keep-alive key?","tags":["vue.js","caching","nuxt.js","vue-router","keep-alive"],"text":"Title: Vue.js How To Manage nuxt keep-alive key?\nTags: vue.js, caching, nuxt.js, vue-router, keep-alive\nSource: Stack Overflow\n\nQuestion:\nI am using Nuxt for my vue project. I want to build a multi-tab application. But I could not manage the caching mechanism of nuxt.\n\nThe case is that, my full path never contains any parameters even in update paths.\n\nI mean my paths are always like\n\n/myapp/customer/update\n\ninstead of\n\n/myapp/custmer/update/:id\n\nSo when I try to bind the nuxt key like\n\n``\n\nIt does not caches anything and keeps loading all lifecyles (beforeCreate, created, beforeMount, mounted...)\n\nIf I do not use **:key**,\n\nthen **keep-alive** works perfect for pages without parameters\n\nbut works wrong with parameters. If I route to customer with id:3 once, then when I go to another customer with id:4, it still caches and displays the data of customer with id:3.\n\nHere is my nuxt-link code:\n\n```\n\n \n {{ tag.name }}\n \n \n \n```\n\nAnd below is the code that I use for viewing routes\n\n```\n\n```\n\nAny help will be pleasured.\n\nThank you...\n\n========================================\n\nCode:\n```text\n<span\n v-for=\"(tag, index) in tabbedViews\"\n :key=\"tag.name + (tag.params ? JSON.stringify(tag.params) : '')\"\n >\n <nuxt-link\n :key=\"tag.name + (tag.params ? JSON.stringify(tag.params) : '')\"\n :to=\"{ name: tag.name, params: tag.params }\"\n @click.native=\"tabClicked(index)\"\n >\n {{ tag.name }}\n <span\n v-if=\"!tag.keepOpen\"\n class=\"el-icon-close\"\n @click.prevent.stop=\"closeSelectedTag(index)\"\n />\n </nuxt-link>\n </span>\n```\n\n```text\n<nuxt keep-alive :key=\"$route.path + ($route.params ? JSON.stringify($route.params) : '')\" />\n```\n\n```text\n<nuxt keep-alive :key=\"$route.path + ($route.params ? JSON.stringify($route.params) : '')\" />\n```\n\n```text\n:nuxt-child-key\n```\n\n```text\n:key\n```\n\n========================================\n\nComments:\n- I'm not sure but when `$route.params` is empty, it might be an empty array instead of undefined or null. That might affect your if condition.\n- @Eldar, thank you for your answer. Yes, it was an empty object as you said, and I fixed this situation. But it did not solve the problem.","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":94,"estimatedTokens":563}}932{"id":"stack-74846556","source":"stackoverflow","questionId":74846556,"title":"'fileURLToPath' is not exported by __vite-browser-external","tags":["vue.js","nuxt.js","vite","rollupjs","nuxt3.js"],"text":"Title: 'fileURLToPath' is not exported by __vite-browser-external\nTags: vue.js, nuxt.js, vite, rollupjs, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI'm getting this build error with Nuxt3.0 stable.\n\n`nuxi dev` works fine.\n\nI get the following error when I run `nuxi build`.\n\n```\nERROR 'fileURLToPath' is not exported by __vite-browser-external, imported by node_modules/local-pkg/dist/shared.mjs 13:57:26\nfile: /node_modules/local-pkg/dist/shared.mjs:41:9\n39: import path from \"path\";\n40: import fs, { promises as fsPromises } from \"fs\";\n41: import { fileURLToPath } from \"url\";\n ^\n42: \n43: // node_modules/.pnpm/yocto-queue@1.0.0/node_modules/yocto-queue/index.js\n\n ERROR 'fileURLToPath' is not exported by __vite-browser-external, imported by node_modules/local-pkg/dist/shared.mjs 13:57:26\n\n at error (node_modules/rollup/dist/es/shared/rollup.js:1858:30)\n at Module.error (node_modules/rollup/dist/es/shared/rollup.js:12429:16)\n at Module.traceVariable (node_modules/rollup/dist/es/shared/rollup.js:12788:29)\n at ModuleScope.findVariable (node_modules/rollup/dist/es/shared/rollup.js:11440:39)\n```\n\nThis is my `nuxt.config.ts`\n\n```\nexport default defineNuxtConfig({\n modules: ['@pinia/nuxt'],\n runtimeConfig: {\n },\n hooks: {\n 'components:dirs'(dirs: any) {\n dirs.push({\n path: '~/components',\n })\n },\n },\n components: {\n global: true,\n },\n nitro: {\n preset: 'aws-lambda',\n serveStatic: true,\n },\n app: {\n baseURL: '/',\n },\n build: {\n transpile: ['chart.js'],\n },\n typescript: {\n shim: false,\n strict: true,\n },\n vite: {\n resolve: {\n alias: {\n './runtimeConfig': './runtimeConfig.browser',\n },\n },\n },\n})\n```\n\nI tried these but build still doesn't work.\n\nPolyfill node os module with vite/rollup.js\n\nhttps://github.com/aws-amplify/amplify-js/issues/9639#issuecomment-1315152038\n\n========================================\n\nCode:\n```text\nERROR 'fileURLToPath' is not exported by __vite-browser-external, imported by node_modules/local-pkg/dist/shared.mjs 13:57:26\nfile: /node_modules/local-pkg/dist/shared.mjs:41:9\n39: import path from \"path\";\n40: import fs, { promises as fsPromises } from \"fs\";\n41: import { fileURLToPath } from \"url\";\n ^\n42: \n43: // node_modules/.pnpm/yocto-queue@1.0.0/node_modules/yocto-queue/index.js\n\n\n ERROR 'fileURLToPath' is not exported by __vite-browser-external, imported by node_modules/local-pkg/dist/shared.mjs 13:57:26\n\n at error (node_modules/rollup/dist/es/shared/rollup.js:1858:30)\n at Module.error (node_modules/rollup/dist/es/shared/rollup.js:12429:16)\n at Module.traceVariable (node_modules/rollup/dist/es/shared/rollup.js:12788:29)\n at ModuleScope.findVariable (node_modules/rollup/dist/es/shared/rollup.js:11440:39)\n```\n\n```js\nexport default defineNuxtConfig({\n modules: ['@pinia/nuxt'],\n runtimeConfig: {\n },\n hooks: {\n 'components:dirs'(dirs: any) {\n dirs.push({\n path: '~/components',\n })\n },\n },\n components: {\n global: true,\n },\n nitro: {\n preset: 'aws-lambda',\n serveStatic: true,\n },\n app: {\n baseURL: '/',\n },\n build: {\n transpile: ['chart.js'],\n },\n typescript: {\n shim: false,\n strict: true,\n },\n vite: {\n resolve: {\n alias: {\n './runtimeConfig': './runtimeConfig.browser',\n },\n },\n },\n})\n```\n\n```text\nnuxi dev\n```\n\n```text\nnuxi build\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\n**/*.test.*\n```\n\n```text\n.nuxtignore\n```\n\n========================================\n\nComments:\n- I got the issue when building my project with vite, i.e. running `vite build`","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":161,"estimatedTokens":918}}933{"id":"stack-74576221","source":"stackoverflow","questionId":74576221,"title":"How to correctly use UnoCSS presets with Nuxt3?","tags":["css","nuxt.js","nuxt3.js","daisyui","unocss"],"text":"Title: How to correctly use UnoCSS presets with Nuxt3?\nTags: css, nuxt.js, nuxt3.js, daisyui, unocss\nSource: Stack Overflow\n\nQuestion:\n### Problem\n\nI use Nuxt3 + UnoCSS + DaisyUI community preset. When running `npx nuxi dev`, everything works well. However, when running `npx nuxi generate && npx serve dist`, UnoCSS works well but some of the DaisyUI preset styles are incorrect:\n\n### Reproduce\n\nI create a small online demo to illustrate this problem:\n\n### https://stackblitz.com/edit/nuxt-starter-5h7iuh\n\nThis is in dev:\n\nwhile this is in deployment:\n\n### My try\n\nI spent almost the whole day debugging but still did not find the reason... The only thing I found is that some styles in the daisyUI preset are not correct. Here's an example:\n\nThis is the styles of `btn-sm` class defined in `@kidonng/daisyui/utilities/styled/button.css`:\n\n```\n.btn-sm {\n @apply h-8 px-3 min-h-8;\n font-size: 0.875rem;\n }\n```\n\nand this is what I see in chrome dev tool when running dev server (`h-8` means `height: 2rem`):\n\nBut this is what I see in chrome dev tool in deployment preview:\n\nAnd this is the corresponding CSS file generated by Nuxt (`entry.7b197c61.css`):\n\n```\n.btn-md,\n.btn-sm {\n height: 3rem;\n min-height: 3rem;\n padding-left: 1rem;\n padding-right: 1rem;\n font-size: 0.875rem;\n}\n```\n\nThe correct style should be `height: 2rem`, but the generated CSS is `height: 3rem`. This is really weird... I don't know what causes this and how to fix it. Hope someone may help me. Thanks in advance!\n\n========================================\n\nCode:\n```css\n.btn-sm {\n @apply h-8 px-3 min-h-8;\n font-size: 0.875rem;\n }\n```\n\n```css\n.btn-md,\n.btn-sm {\n height: 3rem;\n min-height: 3rem;\n padding-left: 1rem;\n padding-right: 1rem;\n font-size: 0.875rem;\n}\n```\n\n```text\nnpx nuxi dev\n```\n\n```text\nnpx nuxi generate && npx serve dist\n```\n\n```text\nbtn-sm\n```\n\n```text\n@kidonng/daisyui/utilities/styled/button.css\n```\n\n```text\nh-8\n```\n\n```text\nheight: 2rem\n```\n\n```text\nentry.7b197c61.css\n```\n\n```text\nheight: 2rem\n```\n\n```text\nheight: 3rem\n```\n\n```text\ncssnano: {\n preset: [\n 'default',\n {\n mergeRules: false,\n normalizeWhitespace: false,\n },\n ],\n},\n```\n\n```text\nnormalizeWhitespace\n```\n\n```text\n@apply\n```\n\n========================================\n\nComments:\n- Fix was released in version `@unocss/nuxt@0.49.8`","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":132,"estimatedTokens":582}}934{"id":"stack-62833892","source":"stackoverflow","questionId":62833892,"title":"How to import third party plugin into Nuxt and initialize during mounted hook?","tags":["nuxt.js"],"text":"Title: How to import third party plugin into Nuxt and initialize during mounted hook?\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nWhat is the correct way to use a third party plugin with Nuxt? I consulted the Nuxt plugin documentation, but it is not working for me.\n\nLet me explain:\n\nI am trying to use a JavaScript image annotation library called Annotorious and the Annotorious docs state to use the plugin like so:\n\n```\nimport { Annotorious } from '@recogito/annotorious';\n\nconst anno = new Annotorious({ image: 'hallstatt' }); // image element or ID\n```\n\nI created a plugin named `annotorious.client.js` and placed it in my `plugins` folder:\n\nplugins/annotorious.client.js\n\n```\nimport Vue from 'vue'\nimport Annotorious from '@recogito/annotorious'\nVue.use(Annotorious) \nThen, in `nuxt.config.js` file I added:\n\n`plugins: ['~/plugins/annotorious.client.js']`.\n\nThen, in my Nuxt page I tried to initialize the plugin like so:\n\n```\n\n...snip...\n \n...snip...\n\n import Annotorious from '~/plugins/annotorious.client.js'\n export default {\n data() {\n return {\n photo: {},\n anno: {}\n }\n },\n async mounted() {\n await this.getPhoto()\n this.anno = new Annotorious({ image: this.photo.filename })\n```\n\nNote: IN a regular Vue app (built with Vue-Cli), everything works great. However, once I tried to use Nuxt I get issues. Here's a console error:\n\n```\nvue.runtime.esm.js?2b0e:5106 Uncaught TypeError: Cannot read property 'install' of undefined\n at Function.Vue.use (vue.runtime.esm.js?2b0e:5106)\n at eval (annotorious.client.js?8beb:3)\n at Module../plugins/annotorious.client.js (default~app.js:4509)\n at __webpack_require__ (runtime.js:854)\n at fn (runtime.js:151)\n at eval (index.js:46)\n at Module../.nuxt/index.js (default~app.js:203)\n at __webpack_require__ (runtime.js:854)\n at fn (runtime.js:151)\n at Module.eval (client.js:49)\n```\n\nAnyone spot anything in my code? How to get this working? I would throw up a codesandbox but their Nuxt starter is broken. Thanks for any help!!\n\n========================================\n\nTop Answer:\nIt looks like Annotorious is **not** a Vue plugin, so no you should not use `Vue.use(Annotorious)`.\n\nThe reason you get `Uncaught TypeError: Cannot read property 'install'` is because Vue attempts to call the `install` function on the object you pass to `Vue.use`.\n\nTry to just import Annotorious in you component and use it. You can also import in the `mounted` hook in case the library uses functions objects that are not defined on the server.\n\n========================================\n\nCode:\n```text\nimport { Annotorious } from '@recogito/annotorious';\n\nconst anno = new Annotorious({ image: 'hallstatt' }); // image element or ID\n```\n\n```text\nimport Vue from 'vue'\nimport Annotorious from '@recogito/annotorious'\nVue.use(Annotorious) <-- am I supposed to be doing it like this?\n```\n\n```text\n<template>\n...snip...\n <img :id=\"photo.filename\" :src=\"photo.url\" />\n...snip...\n</template>\n\n<script>\n import Annotorious from '~/plugins/annotorious.client.js'\n export default {\n data() {\n return {\n photo: {},\n anno: {}\n }\n },\n async mounted() {\n await this.getPhoto()\n this.anno = new Annotorious({ image: this.photo.filename })\n```\n\n```text\nvue.runtime.esm.js?2b0e:5106 Uncaught TypeError: Cannot read property 'install' of undefined\n at Function.Vue.use (vue.runtime.esm.js?2b0e:5106)\n at eval (annotorious.client.js?8beb:3)\n at Module../plugins/annotorious.client.js (default~app.js:4509)\n at __webpack_require__ (runtime.js:854)\n at fn (runtime.js:151)\n at eval (index.js:46)\n at Module../.nuxt/index.js (default~app.js:203)\n at __webpack_require__ (runtime.js:854)\n at fn (runtime.js:151)\n at Module.eval (client.js:49)\n```\n\n```text\nannotorious.client.js\n```\n\n```text\nplugins\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nplugins: ['~/plugins/annotorious.client.js']\n```\n\n```text\nimport { Annotorious } from '@recogito/annotorious';\n\nexport default (context, inject) => {\n const initAnnotorious = (id) => new Annotorious({ image: id });\n inject('initAnnotorious', initAnnotorious)\n // For Nuxt <= 2.12, also add 👇\n context.$initAnnotorious = initAnnotorious\n}\n```\n\n```text\nplugins: [\n { src: '~/plugins/annotorious.js', mode: 'client' },\n ]\n```\n\n```text\n<template>\n <img id=\"hallstatt\" src=\"https://www.howtogeek.com/wp-content/uploads/2017/03/xwpv_top-650x363.png.pagespeed.gp+jp+jw+pj+ws+js+rj+rp+rw+ri+cp+md.ic.1-Of_zmw5H.png\" alt=\"\">\n</template>\n\n<script>\nexport default {\n mounted() {\n var anno = this.$initAnnotorious(\"hallstatt\");\n console.log(anno) \n }\n}\n</script>\n```\n\n```text\nplugins > annotorious.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nVue.use(Annotorious)\n```\n\n```text\nUncaught TypeError: Cannot read property 'install'\n```\n\n```text\ninstall\n```\n\n```text\nVue.use\n```\n\n```text\nmounted\n```\n\n========================================\n\nComments:\n- Wow that works! That was the one thing i did not try based on docs.","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":207,"estimatedTokens":1248}}935{"id":"stack-70835694","source":"stackoverflow","questionId":70835694,"title":"Nuxt Vue Typescript global plugins unavailable inside script lang ts","tags":["typescript","vue.js","nuxt.js"],"text":"Title: Nuxt Vue Typescript global plugins unavailable inside script lang ts\nTags: typescript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am currently converting a nuxt vue js (v2 not v3) project into typescript and I cannot figure out why plugins do not get recognized inside .vue files, while they work in all .ts files.\n\nAs you can see in the code snippets, I also try using bootstrap vue and i18n which are both not recognized inside .vue script tags either, only work in ts files.\nThe only workaround is to create a function that uses them inside the mixin.ts files and extend them that way. Or import all the plugins manually into each script. This kind of defeats the point of global plugins, so is there something I am missing, or why are they not recognized by default ?\n\nI also tried extending Vue directly in the main .vue components instead of a mixin, but the same issue is still there.\n\n**Component.vue**\n\n```\n\n ...\n \n {{$testFunction('test')}} this also works, but does not give any type indication or warnings \n \n\nimport Component, { mixins } from 'vue-class-component';\nimport { TableMixin } from '../../mixins/tablemixin';\n\n@Component\nclass Contacts extends mixins(TableMixin) {\n test() {\n // Property '$testFunction' does not exist on type 'Contacts'.Vetur(2339)\n console.log(this.$testFunction('test'));\n }\n testMixin() {\n // Works fine through mixin...\n console.log(this.testMixinFunction('test'));\n }\n}\nexport default Contacts;\n\n```\n\n**mixins/tablemixin.ts**\n\n```\nimport Vue from 'vue';\nimport Component from 'vue-class-component';\n\n@Component\nexport class TableMixin extends Vue { \n testMixinFunction(str: string) {\n return this.$testFunction(str);\n }\n}\n```\n\n**plugins/helpers.ts**\n\n```\nimport Vue from 'vue'\n\ndeclare module 'vue/types/vue' {\n interface Vue {\n $testFunction(str: string): string;\n }\n}\n\nVue.prototype.$testFunction = (str: string): string => {\n return str + 'tested';\n}\n```\n\n**nuxt.config.js**\n\n```\nplugins: [ \n '~/plugins/helpers'\n]\n```\n\n**tsconfig.json**\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"ES2018\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\",\n \"lib\": [\n \"ESNext\",\n \"ESNext.AsyncIterable\",\n \"DOM\"\n ],\n \"esModuleInterop\": true,\n \"allowJs\": true,\n \"sourceMap\": true,\n \"strict\": true,\n \"noEmit\": true,\n \"baseUrl\": \".\",\n \"experimentalDecorators\": true,\n \"paths\": {\n \"~/*\": [\n \"./*\"\n ],\n \"@/*\": [\n \"./*\"\n ]\n },\n \"types\": [\n \"@types/node\",\n \"@nuxt/types\",\n \"nuxt-i18n\",\n \"bootstrap-vue\"\n ]\n },\n \"exclude\": [\n \"node_modules\"\n ]\n}\n```\n\n========================================\n\nCode:\n```text\n<template>\n ...\n <div>\n {{$testFunction('test')}} this also works, but does not give any type indication or warnings \n </div> \n</template\n\n<script lang = \"ts\">\nimport Component, { mixins } from 'vue-class-component';\nimport { TableMixin } from '../../mixins/tablemixin';\n\n@Component\nclass Contacts extends mixins(TableMixin) {\n test() {\n // Property '$testFunction' does not exist on type 'Contacts'.Vetur(2339)\n console.log(this.$testFunction('test'));\n }\n testMixin() {\n // Works fine through mixin...\n console.log(this.testMixinFunction('test'));\n }\n}\nexport default Contacts;\n</script>\n```\n\n```text\nimport Vue from 'vue';\nimport Component from 'vue-class-component';\n\n@Component\nexport class TableMixin extends Vue { \n testMixinFunction(str: string) {\n return this.$testFunction(str);\n }\n}\n```\n\n```text\nimport Vue from 'vue'\n\ndeclare module 'vue/types/vue' {\n interface Vue {\n $testFunction(str: string): string;\n }\n}\n\nVue.prototype.$testFunction = (str: string): string => {\n return str + 'tested';\n}\n```\n\n```text\nplugins: [ \n '~/plugins/helpers'\n]\n```\n\n```text\n{\n \"compilerOptions\": {\n \"target\": \"ES2018\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\",\n \"lib\": [\n \"ESNext\",\n \"ESNext.AsyncIterable\",\n \"DOM\"\n ],\n \"esModuleInterop\": true,\n \"allowJs\": true,\n \"sourceMap\": true,\n \"strict\": true,\n \"noEmit\": true,\n \"baseUrl\": \".\",\n \"experimentalDecorators\": true,\n \"paths\": {\n \"~/*\": [\n \"./*\"\n ],\n \"@/*\": [\n \"./*\"\n ]\n },\n \"types\": [\n \"@types/node\",\n \"@nuxt/types\",\n \"nuxt-i18n\",\n \"bootstrap-vue\"\n ]\n },\n \"exclude\": [\n \"node_modules\"\n ]\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":218,"estimatedTokens":1062}}936{"id":"stack-47131889","source":"stackoverflow","questionId":47131889,"title":"nuxtjs/axios What is the way to initialize version 4.4.0? (nuxt.js)","tags":["javascript","node.js","vue.js","axios","nuxt.js"],"text":"Title: nuxtjs/axios What is the way to initialize version 4.4.0? (nuxt.js)\nTags: javascript, node.js, vue.js, axios, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI would like to use the nuxtjs/axios module.\n\nAt first, I install the module with npm\n\n npm install nuxtjs/axios\n\nThen I set the options in the nuxt.config.js file.\n\n```\nmodules: [\n ['@ nuxtjs/axios', {\n baseURL: 'http://localhost: 4000',\n browserBaseURL: '/api',\n }],\n]\n```\n\nWhen I start the app with\n\n npm run dev\n\nI expect the below output:\n\nhttps://i.sstatic.net/SwZrc.png\n\nIn nuxtjs/axios version 2.1.0, it is built as follows.\n\nhttps://i.sstatic.net/FJZoA.png\n\n [AXIOS] Base URL: http: // localhost: 3000 /, Browser: /\n\nWhy can not I see the above message?\n\nI think it might be because of a problem with asyncData () {}.\n\nAlso browserBaseURL: '/ api' does not work.\n\n========================================\n\nCode:\n```text\nmodules: [\n ['@ nuxtjs/axios', {\n baseURL: 'http://localhost: 4000',\n browserBaseURL: '/api',\n }],\n]\n```\n\n```text\nmodules: [\n '@nuxtjs/axios'\n],\naxios: {\n baseURL: 'http://localhost: 4000',\n browserBaseURL: '/api'\n}\n```\n\n```text\nnpm i -S @nuxtjs/axios\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":67,"estimatedTokens":289}}937{"id":"stack-73571871","source":"stackoverflow","questionId":73571871,"title":"Hydration problem with client-side authentication and computed property in Vue/Nuxt layout","tags":["vue.js","nuxt.js","vuejs3","nuxt3.js","hydration"],"text":"Title: Hydration problem with client-side authentication and computed property in Vue/Nuxt layout\nTags: vue.js, nuxt.js, vuejs3, nuxt3.js, hydration\nSource: Stack Overflow\n\nQuestion:\nMy app (vue/nuxt 3) stores the user authentication state in localStorage. As a consequence it is only available on the client and prerendered pages always show the unauthenticated content. Client will render the authenticated content as soon as it is aware of it. That's ok and accepted.\n\nHowever, this does not seem to apply for computed properties. My whole layout depends on the authentication state, e.g. like this:\n\n```\n\n \n \n \n\nconst computedClasses = computed(() => ({ \n if ($someReferenceToStore.user.logged.in) {\n return 'loggedin'\n } else {\n return 'anonymous'\n }\n}))\n\n```\n\nThe problem is, that even though the user is logged in, the `computedClasses` is not updated to `loggedin` but the server generated `anonymous` is shown. How to solve this? How can I make the client update the computed property and overwrite the server rendered classes?\n\nI know, I can wrap parts of my template that depend on the authentication state with `` to avoid hydration mismatches. Wrapping my layout with `` would basically disable any server rendering. Can I set a property of an element (the `:class=\"...\"`) to client-only?\n\n========================================\n\nCode:\n```html\n<template>\n <div :class=\"computedClasses\">\n <slot />\n </div>\n</template>\n\n<script setup>\nconst computedClasses = computed(() => ({ \n if ($someReferenceToStore.user.logged.in) {\n return 'loggedin'\n } else {\n return 'anonymous'\n }\n}))\n</script>\n```\n\n```text\ncomputedClasses\n```\n\n```text\nloggedin\n```\n\n```text\nanonymous\n```\n\n```text\n<ClientOnly>\n```\n\n```text\n<ClientOnly>\n```\n\n```text\n:class=\"...\"\n```\n\n```html\n<template>\n <div :class=\"computedClasses\">\n <slot />\n </div>\n</template>\n\n<script setup>\nconst computedClasses = ref('');\n\nonMounted(() => {\n computedClasses.value = $someReferenceToStore.user.logged.in ? 'loggedin' : 'anonymous';\n});\n</script>\n```\n\n========================================\n\nComments:\n- If it's specific to a user, it should not be SSR'ed anyway. Using `client-only` will only not SSR the code nested inside of it, not the whole app. Also, I think that a DOM mismatch is not taking into consideration the CSS (could maybe try to verify that one firstly). As always, if you want to debug this kind of issue I recommend toggling JS back and forth to see what are the differences between server/client. Overall, if it's specific to a user, it should not be generated on the server: your facebook feed is not SSR'ed, it's kept only on the client since it's a personalised/dynamic content.\n- The layout is not really user-specific. But it depends on whether the user is logged in or not. I want to SSR the \"not logged in\" layout. The layout is the outer-most div. So, if I put `client-only` around it, my whole app will be in it...\n- If it depends if logged-in or not, it's what I call specific. You can always refractor your code to allow the skeleton to be public (SSR'ed) but otherwise I'm not sure what to say. If the type of your app asks for an authentication early (like Facebook), you're pretty much down with SSR, mainly because some layout doesn't really bring any benefit SSR-wise.\n- No, my app is pretty much usable without authentication. But if you are authenticated you can use more functionality that is in a separate menu bar. Whether this menu is displayed or not, is part of my layout... To simplify: I need to change properties (like width) of the main `div` (with all the content that should be SSRed) depending on the authentication state. How would you refactor that? Sorry, might be a stupid question, but I have no idea...\n- You could refactor it to be 80% SSR'ed and 20% client only. No secret sauce here but the reconciliation during the hydration is not THAT flexible in Nuxt. Some frameworks like Qwik/Marko may offer more granularity but the overall concept of hydration is quite clunky. Still, if you don't use most of the benefits, SSR is not worth it for 100% of your app.","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":98,"estimatedTokens":1026}}938{"id":"stack-69915969","source":"stackoverflow","questionId":69915969,"title":"Nuxt throws: Class constructor i cannot be invoked without 'new'","tags":["javascript","vue.js","visual-studio-code","vuejs2","nuxt.js"],"text":"Title: Nuxt throws: Class constructor i cannot be invoked without 'new'\nTags: javascript, vue.js, visual-studio-code, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using `drawflow` npm library in my `Vuejs/Nuxtjs` application but when I start the application I get the following error:\n\n```\nClass constructor i cannot be invoked without 'new'\n```\n\nFollowing are the steps I have followed as per documentation:\n\n- Install the `drawflow` using `npm i drawflow --save`\n\n- `Vue Component` with following code:\n\n```\n\n \n \n \n \n\n### Drawflow\n\n \n \n \n \n\nimport Vue from 'vue'\nimport Drawflow from 'drawflow'\nVue.use(Drawflow)\n\nexport default {\n name: 'App',\n data () {\n return {\n }\n },\n mounted () {\n const id = document.getElementById('drawflow')\n console.log(id)\n this.editor = new Drawflow(id, Vue, this)\n this.editor.start()\n },\n methods: {\n }\n}\n\n @import 'drawflow/dist/drawflow.min.css';\n\n```\n\n- My `nuxt.config.js` file:\n\n\r\n\r\n\n```\nexport default {\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: \"App | Generator\",\n htmlAttrs: {\n lang: \"en\"\n },\n meta: [\n { charset: \"utf-8\" },\n { name: \"viewport\", content: \"width=device-width, initial-scale=1\" },\n { hid: \"description\", name: \"description\", content: \"\" },\n { name: \"format-detection\", content: \"telephone=no\" }\n ],\n script: [],\n link: [\n { rel: \"icon\", type: \"image/x-icon\", href: \"/Logo.ico\" },\n {\n rel: \"stylesheet\",\n href: \"https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css\"\n },\n {\n rel: \"stylesheet\",\n href: \"https://unpkg.com/vue-multiselect@2.1.0/dist/vue-multiselect.min.css\"\n }\n ]\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\"@/assets/css/styles.css\"],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [\n { src: \"~/plugins/bus\", mode:\"client\" }\n ],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n // https://go.nuxtjs.dev/eslint\n [\n \"@nuxtjs/eslint-module\",\n {\n fix: true\n }\n ],\n [\"@nuxtjs/dotenv\"]\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\"@nuxtjs/axios\", \"bootstrap-vue/nuxt\"],\n\n // Axios module configuration: https://go.nuxtjs.dev/config-axios\n axios: {\n baseURL: process.env.API_URL,\n headers: {\n \"Content-Type\": \"text/plain\"\n }\n },\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {\n transpile: [\"drawflow\"]\n },\n\n server: {\n port: 5000\n },\n\n vue: {\n config: {\n productionTip: false,\n devtools: true\n }\n }\n};\n```\n\n\r\n\r\n\r\n\n- Following is my `.eslintrc.js`:\n\n\r\n\r\n\n```\nmodule.exports = {\n root: true,\n env: {\n browser: true,\n node: true\n },\n parserOptions: {\n parser: '@babel/eslint-parser',\n requireConfigFile: false\n },\n extends: [\n '@nuxtjs',\n 'plugin:nuxt/recommended'\n ],\n plugins: [\n ],\n // add your custom rules here\n rules: {}\n}\n```\n\n========================================\n\nCode:\n```text\nClass constructor i cannot be invoked without 'new'\n```\n\n```text\n<template>\n <div class=\"container-fluid\">\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <h1>Drawflow</h1>\n <div id=\"drawflow\" ref=\"drawflow\" />\n </div>\n </div>\n </div>\n</template>\n\n<script>\nimport Vue from 'vue'\nimport Drawflow from 'drawflow'\nVue.use(Drawflow)\n\nexport default {\n name: 'App',\n data () {\n return {\n }\n },\n mounted () {\n const id = document.getElementById('drawflow')\n console.log(id)\n this.editor = new Drawflow(id, Vue, this)\n this.editor.start()\n },\n methods: {\n }\n}\n</script>\n\n<style>\n @import 'drawflow/dist/drawflow.min.css';\n</style>\n```\n\n```js\nexport default {\n // Global page headers: https://go.nuxtjs.dev/config-head\n head: {\n title: \"App | Generator\",\n htmlAttrs: {\n lang: \"en\"\n },\n meta: [\n { charset: \"utf-8\" },\n { name: \"viewport\", content: \"width=device-width, initial-scale=1\" },\n { hid: \"description\", name: \"description\", content: \"\" },\n { name: \"format-detection\", content: \"telephone=no\" }\n ],\n script: [],\n link: [\n { rel: \"icon\", type: \"image/x-icon\", href: \"/Logo.ico\" },\n {\n rel: \"stylesheet\",\n href: \"https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css\"\n },\n {\n rel: \"stylesheet\",\n href: \"https://unpkg.com/vue-multiselect@2.1.0/dist/vue-multiselect.min.css\"\n }\n ]\n },\n\n // Global CSS: https://go.nuxtjs.dev/config-css\n css: [\"@/assets/css/styles.css\"],\n\n // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins\n plugins: [\n { src: \"~/plugins/bus\", mode:\"client\" }\n ],\n\n // Auto import components: https://go.nuxtjs.dev/config-components\n components: true,\n\n // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules\n buildModules: [\n // https://go.nuxtjs.dev/eslint\n [\n \"@nuxtjs/eslint-module\",\n {\n fix: true\n }\n ],\n [\"@nuxtjs/dotenv\"]\n ],\n\n // Modules: https://go.nuxtjs.dev/config-modules\n modules: [\"@nuxtjs/axios\", \"bootstrap-vue/nuxt\"],\n\n // Axios module configuration: https://go.nuxtjs.dev/config-axios\n axios: {\n baseURL: process.env.API_URL,\n headers: {\n \"Content-Type\": \"text/plain\"\n }\n },\n\n // Build Configuration: https://go.nuxtjs.dev/config-build\n build: {\n transpile: [\"drawflow\"]\n },\n\n server: {\n port: 5000\n },\n\n vue: {\n config: {\n productionTip: false,\n devtools: true\n }\n }\n};\n```\n\n```js\nmodule.exports = {\n root: true,\n env: {\n browser: true,\n node: true\n },\n parserOptions: {\n parser: '@babel/eslint-parser',\n requireConfigFile: false\n },\n extends: [\n '@nuxtjs',\n 'plugin:nuxt/recommended'\n ],\n plugins: [\n ],\n // add your custom rules here\n rules: {}\n}\n```\n\n```text\ndrawflow\n```\n\n```text\nVuejs/Nuxtjs\n```\n\n```text\ndrawflow\n```\n\n```text\nnpm i drawflow --save\n```\n\n```text\nVue Component\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n.eslintrc.js\n```\n\n```html\n<template>\n <div class=\"container-fluid\">\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <h1>Drawflow</h1>\n <div id=\"drawflow-graph\" ref=\"drawflow\" />\n </div>\n </div>\n </div>\n</template>\n\n<script>\nimport Vue from 'vue'\nexport default {\n data() {\n return {\n editor: {},\n }\n },\n async mounted() {\n const importedModule = await import('drawflow')\n const Drawflow = importedModule.default\n this.editor = new Drawflow(this.$refs.drawflow, Vue, this)\n this.editor.start()\n this.editor.addNode(\n 'github',\n 0,\n 1,\n 150,\n 300,\n 'github',\n 'name',\n 'Cool Vue example'\n )\n },\n}\n</script>\n\n<style>\n@import 'drawflow/dist/drawflow.min.css';\n#drawflow-graph {\n width: 800px;\n height: 800px;\n border: 2px solid teal;\n}\n</style>\n```\n\n========================================\n\nComments:\n- jsconfig is for VS Code. It doesn't affect how the app works. The error commonly occurs when you use es5 target for libs that aren't supposed to be used with it.\n- @EstusFlask Thanks a lot for the response. Can you please suggest what shall I do to avoid this issue?\n- Post nuxt and babel configs for starters. jsconfig is irrelevant.\n- @EstusFlask Thanks. I have added `nuxt.config.js` file content. However, I could not find the `babel config` file. Seems like it's not present within my project. Please let me know where can I find it and I will post it.\n- Btw, don't use `@nuxtjs/dotenv`, it's deprecated too as I've explained in one of my previous answers.\n- Don't worry about babel config too much btw, it is perfectly fine to have it with the `transpile` key. The default of Nuxt are fine in your case. And I've achieved to make it work without touching to babel at any point so you should not have to neither.","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":405,"estimatedTokens":1951}}939{"id":"stack-68635262","source":"stackoverflow","questionId":68635262,"title":"How to get the error (404) page into the ''dist\" directory in nuxt?","tags":["javascript","vue.js","nuxt.js","custom-error-pages"],"text":"Title: How to get the error (404) page into the ''dist\" directory in nuxt?\nTags: javascript, vue.js, nuxt.js, custom-error-pages\nSource: Stack Overflow\n\nQuestion:\nI created an error page as in the documentation and it works.\n\nhttps://nuxtjs.org/docs/2.x/concepts/views#error-page\n\nIn short, I create an `error.vue` file in the `/layouts` directory and optionally pass it a custom `layout`.\n\n```\n\n \n \n\n### Page not found\n\n \n\n### An error occurred\n\n Home page\n \n\n export default {\n props: ['error'],\n layout: 'error' // custom layout\n }\n\n```\n\nBut my product task requires the `404` page to go into the `/dist` directory after the `generate` command.\n\nLike this\n\n```\ndist/\n--| 200.html\n--| 404.html //do not exist for me\n```\n\nThe following solutions **didn't** help:\n\n- If I just add a `404` page to the `/pages` directory, then Nuxt will still show its **default** error page.\n\nIs there a laconic way to do this?\nThanks in advance!\n\n========================================\n\nCode:\n```text\n<template>\n <div>\n <h1 v-if=\"error.statusCode === 404\">Page not found</h1>\n <h1 v-else>An error occurred</h1>\n <NuxtLink to=\"/\">Home page</NuxtLink>\n </div>\n</template>\n\n<script>\n export default {\n props: ['error'],\n layout: 'error' // custom layout\n }\n</script>\n```\n\n```text\ndist/\n--| 200.html\n--| 404.html //do not exist for me\n```\n\n```text\nerror.vue\n```\n\n```text\n/layouts\n```\n\n```text\nlayout\n```\n\n```text\n404\n```\n\n```text\n/dist\n```\n\n```text\ngenerate\n```\n\n```text\n404\n```\n\n```text\n/pages\n```\n\n```text\nrouter: {\n extendRoutes(routes, resolve) {\n routes.push({\n name: 'custom',\n path: '*',\n component: resolve('@/pages/404.vue')\n })\n }\n},\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n404.vue\n```\n\n```text\n/pages\n```\n\n```text\n404.html\n```\n\n```text\n/dist\n```\n\n========================================\n\nComments:\n- Why did you need a `404` page at first? Nuxt is handling this for you.\n- @kissu The nginx configuration is such that if the page is not found, it expects to find a 404 page to give it. And if he does not find it, then he gives his standard.","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":144,"estimatedTokens":520}}940{"id":"stack-59862897","source":"stackoverflow","questionId":59862897,"title":"Nuxt js application not running on AWS beanstalk - 502 error","tags":["amazon-elastic-beanstalk","nuxt.js"],"text":"Title: Nuxt js application not running on AWS beanstalk - 502 error\nTags: amazon-elastic-beanstalk, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a **Nuxt js** application which needs to be deployed the **AWS Elastic Beanstalk**. I'm using bitbucket internal CI/CD to deploy my application to ELB. The application is successfully deployed as per Bitbucket. But in the AWS Beanstalk console, the health is degraded and hence shows **502 Bad Gateway** error when URL is visited.\n\nI have checked AWS logs, here they are (doesn't show any error):\n\n```\n-------------------------------------\n/var/log/nodejs/nodejs.log\n-------------------------------------\nServer running at http://127.0.0.1:8081/\n\n> stack-web@1.0.0 start /var/app/current\n> nuxt start\n\nℹ Listening on: http://:5100/ // ℹ --> This is some werid character appearing\n```\n\nI have checked my upload `.zip` file it contains `.nuxt` folder and inside that, it has `dist` folder as well. The `dist` folder contains 2 folders `client` and `server`.\n\nBelow is my project dir structure. Please help me with this.\n\nhttps://i.sstatic.net/zoe8J.png\n\n========================================\n\nCode:\n```text\n-------------------------------------\n/var/log/nodejs/nodejs.log\n-------------------------------------\nServer running at http://127.0.0.1:8081/\n\n> stack-web@1.0.0 start /var/app/current\n> nuxt start\n\nℹ Listening on: http://<IP_ADDRESS>:5100/ // ℹ --> This is some werid character appearing\n```\n\n```text\n.zip\n```\n\n```text\n.nuxt\n```\n\n```text\ndist\n```\n\n```text\ndist\n```\n\n```text\nclient\n```\n\n```text\nserver\n```\n\n```text\nserver: {\n port: process.env.PORT || 5100,\n host: '0.0.0.0' // default: localhost\n}\n```\n\n```text\nprocess.env.PORT\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nserver\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":84,"estimatedTokens":437}}941{"id":"stack-69373660","source":"stackoverflow","questionId":69373660,"title":"Vue: How to change a value of state and use it in other page and change page structure at starting by it?","tags":["vue.js","nuxt.js"],"text":"Title: Vue: How to change a value of state and use it in other page and change page structure at starting by it?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn this project, we can login from `login.vue` by clicking `login` button and if it is success then we can see `Lnb.vue` in `dashboard.vue`\n\nI thought if i code like this then `pageSso` will be `1` when I check the checkbox in `login.vue` in `Lnb.vue` then it will not show only \"Account\" menu.\nWhen I used `console.log(pageSso)` at mounted cycle it showed `pageSso` was `0`. What would be the problem?\n\n**store/store.js**\n\n```\nexport const state = () => ({\n pageSso: 0,\n})\nexport const getters = {\n pageSso: (state) => state.pageSso,\n}\n\nexport const mutations = {\n setPageSso(state, data) {\n console.log('mutations setPageSso data', data)\n state.pageSso = data\n }\n}\n\nexport const actions = {\n setPageSso({\n commit\n }, data) {\n console.log('actions setPageSso data', data)\n commit('setPageSso', data)\n },\n\n}\n```\n\n**pages/login.vue**\n\n```\n\nSSO checkbox\n login\n\n export default {\n data() {\n return {\n sso: '',\n }\n },\n computed: {},\n methods: {\n submit() {\n this.$store.dispatch('store/setPageSso', this.sso)\n //this.$store.dispatch('store/login', data)\n },\n\n```\n\n**pages/dashboard.vue**\n\n```\n\n \n \n \n \n \n \n \n\n import Lnb from '@/components/Lnb'\n import Gnb from '@/components/Gnb'\n export default {\n components: {\n Lnb,\n Gnb\n },\n mounted() {},\n }\n\n```\n\n**components/Lnb.vue**\n\n```\n\n \n \n \n Settings\n \n \n \n \n \n Account\n \n \n \n\n import {\n mapState\n } from 'vuex'\n export default {\n data() {\n return {}\n },\n computed: {\n ...mapState('store', {\n // navbarState: (state) => state.navbarState,\n\n pageSso: (state) => state.pageSso,\n }),\n },\n mounted() {\n console.log('pageSso ->', this.pageSso);\n },\n methods: {\n\n },\n }\n\n```\n\n========================================\n\nCode:\n```js\nexport const state = () => ({\n pageSso: 0,\n})\nexport const getters = {\n pageSso: (state) => state.pageSso,\n}\n\nexport const mutations = {\n setPageSso(state, data) {\n console.log('mutations setPageSso data', data)\n state.pageSso = data\n }\n}\n\nexport const actions = {\n setPageSso({\n commit\n }, data) {\n console.log('actions setPageSso data', data)\n commit('setPageSso', data)\n },\n\n}\n```\n\n```html\n<template>\n<input\n class=\"checkbox_sso\"\n type=\"checkbox\"\n v-model=\"sso\"\n true-value=\"1\"\n false-value=\"0\" >SSO checkbox\n <button class=\"point\" @click=\"submit\">login</button>\n</template>\n<script>\n export default {\n data() {\n return {\n sso: '',\n }\n },\n computed: {},\n methods: {\n submit() {\n this.$store.dispatch('store/setPageSso', this.sso)\n //this.$store.dispatch('store/login', data)\n },\n</script>\n```\n\n```html\n<template>\n <div class=\"base flex\">\n <Lnb />\n <div class=\"main\">\n <Gnb />\n <nuxt-child />\n </div>\n </div>\n</template>\n<script>\n import Lnb from '@/components/Lnb'\n import Gnb from '@/components/Gnb'\n export default {\n components: {\n Lnb,\n Gnb\n },\n mounted() {},\n }\n</script>\n```\n\n```html\n<template>\n <ul>\n <li :class=\"{ active: navbarState == 7 ? true : false }\">\n <a href=\"/dashboard/settings\">\n <img src=\"../assets/images/ico_settings.svg\" alt=\"icon\" /> Settings\n </a>\n </li>\n <li v-show=\"pageSso != 1\" :class=\"{ active: navbarState == 8 ? true : false }\">\n <a href=\"/dashboard/user\">\n <img src=\"../assets/images/ico_user.svg\" alt=\"icon\" />\n Account\n </a>\n </li>\n </ul>\n</template>\n<script>\n import {\n mapState\n } from 'vuex'\n export default {\n data() {\n return {}\n },\n computed: {\n ...mapState('store', {\n // navbarState: (state) => state.navbarState,\n\n pageSso: (state) => state.pageSso,\n }),\n },\n mounted() {\n console.log('pageSso ->', this.pageSso);\n },\n methods: {\n\n },\n }\n</script>\n```\n\n```text\nlogin.vue\n```\n\n```text\nlogin\n```\n\n```text\nLnb.vue\n```\n\n```text\ndashboard.vue\n```\n\n```text\npageSso\n```\n\n```text\n1\n```\n\n```text\nlogin.vue\n```\n\n```text\nLnb.vue\n```\n\n```text\nconsole.log(pageSso)\n```\n\n```text\npageSso\n```\n\n```text\n0\n```\n\n```text\n<Lnb />\n```\n\n```text\n<Lnb v-if=\"pageSso === 1\" />\n```\n\n```text\nconsole.log(pageSso)\n```\n\n```text\n0\n```\n\n```text\npageSso\n```\n\n```text\nsubmit()\n```\n\n```text\nv-show\n```\n\n```text\nv-if\n```\n\n```text\nv-show\n```\n\n```text\ndisplay: none;\n```\n\n```text\nv-if\n```\n\n```text\nv-show\n```\n\n```text\nv-if\n```\n\n```text\ntrue\n```\n\n========================================\n\nComments:\n- I changed my question a little now. I want to change just `Account` by the `sso`(in `login.vue`) => `pageSso`(in `store.js' and`Lnb.vue`) value.\n- And I thought that `pageSso` will be saved at `submit` in `login.vue` and we can use the saved value anywhere in the project. Maybe this is not true\n- Yes, pageSso in the store is defined when you defined it, and it is available across the project. In your current setup, you define pageSso as 0 until changed by the action dispatched in submit method. The way you have it now, you always see the \n- Account until pageSso changes to 1 in the store. I hope you understand the console.log you have in your Lnb.vue/mounted will run only once and when it runs, it will be zero yet because you haven't yet called submit at that moment.\n- If you want to log pageSso changes into console, you have to either move the console.log into your computed, or use a watch. You may also use the Vuex tab in the Vue developer toolbar instead of logging to the console.\n- Oh sorry I missed out of that submit button. Now I wrote the source to here too and it's from original source what didn't work. I called submit when I clicked the button, but it didn't change. Anyway thank you for telling me the Vuex tab way I'll try use it","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":29,"totalLines":354,"estimatedTokens":1461}}942{"id":"stack-60971116","source":"stackoverflow","questionId":60971116,"title":"Nuxt mixin - Property or method is not defined on the instance but referenced during render","tags":["javascript","vue.js","nuxt.js","mixins"],"text":"Title: Nuxt mixin - Property or method is not defined on the instance but referenced during render\nTags: javascript, vue.js, nuxt.js, mixins\nSource: Stack Overflow\n\nQuestion:\nI'm creating a Nuxt application, where a specific menu should be hidden on mobile. So i've created a mixin plugin that has the property `isSmallScreen` which can be `false` or true.\n\n**mixins.client.js**\n\n```\nimport Vue from 'vue'\nimport styles from '@/assets/styles/base/globals/_responsive.scss'\n\nconst debug = true\n\nlet breakpoint = parseInt(styles.breakpoint, 10)\n\nVue.mixin({\n data: function() {\n return {\n isSmallScreen: null\n }\n },\n created() {\n this.isSmallScreen = (window.innerWidth I've registered the mixins plugin in `nuxt.config.js`\n\n```\nplugins: [\n '~/plugins/base/global/mixins.client.js',\n]\n```\n\nNow I expect `isSmallScreen` to be globally available. When I console.log `this.isSmallScreen` in the mounted hook in `layouts/default.vue`, it returns `true` for small screens, and `false` for bigger screens. That seems to work fine.\n\n**The problem** \n\nMy default.vue layout template looks like\n\n```\n\n \n \n \n \n \n \n\n \n \n \n \n\n```\n\nI expect the `f-nav-top` component do appear on large screens, and hide on small screens. Which also seems to work.\n\n**But ..**\n\nEven though the functionality does what it should I still get the warning as shown below.\n\n`Property or method \"isSmallScreen\" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.`\n\nI've been looking for a solution for a while now, but can't find the solution. Does anyone see what I'm doing wrong here?\n\nThanks in advance\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\nimport styles from '@/assets/styles/base/globals/_responsive.scss'\n\nconst debug = true\n\nlet breakpoint = parseInt(styles.breakpoint, 10)\n\nVue.mixin({\n data: function() {\n return {\n isSmallScreen: null\n }\n },\n created() {\n this.isSmallScreen = (window.innerWidth <= breakpoint)\n }\n})\n```\n\n```text\nplugins: [\n '~/plugins/base/global/mixins.client.js',\n]\n```\n\n```html\n<template>\n<div>\n\n <client-only>\n <div class=\"nav-container\">\n <f-nav-admin />\n <f-nav-top v-if=\"!isSmallScreen\"/>\n </div>\n </client-only>\n\n <!-- page content -->\n <div class=\"page-content-container\">\n <nuxt />\n </div>\n\n</div>\n</template>\n```\n\n```text\nisSmallScreen\n```\n\n```text\nfalse\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nisSmallScreen\n```\n\n```text\nthis.isSmallScreen\n```\n\n```text\nlayouts/default.vue\n```\n\n```text\ntrue\n```\n\n```text\nfalse\n```\n\n```text\nf-nav-top\n```\n\n```text\nProperty or method \"isSmallScreen\" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.\n```\n\n```text\n<nuxt/>\n```\n\n```text\nisSmallScreen\n```\n\n```text\nmixins.client.js\n```\n\n```text\nfile.client.js\n```\n\n```text\nfile.server.js\n```\n\n```text\nmixins.js\n```\n\n========================================\n\nComments:\n- I have just built your example and it works (\"nuxt\": \"^2.12.1\")","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":183,"estimatedTokens":794}}943{"id":"stack-60698553","source":"stackoverflow","questionId":60698553,"title":"How to incorporate SQL Server in a Nuxt.js app","tags":["sql-server","nuxt.js"],"text":"Title: How to incorporate SQL Server in a Nuxt.js app\nTags: sql-server, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to use SQL Server with a Nuxt app, and incorporate some basic CRUD functionality with tables. Does anybody have any insight or examples on this? I understand (I think) that the calls to the db would be exposed in an api folder and registered as a serverMiddleware. Any examples would be appreciated! I'm currently using the node-mssql package as it seems to be the popular choice.\n\n========================================\n\nCode:\n```js\nmodule.exports = {\n // ...\n serverMiddleware: ['~/api/index.js'],\n env: {\n DB_HOST: process.env.DB_HOST || 'db-host',\n DB_DATABASE: process.env.DB_DATABASE || 'db-database',\n DB_USER: process.env.DB_USER || 'db-user',\n DB_PASS: process.env.DB_PASS || 'db-pass'\n },\n // ...\n}\n```\n\n```js\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize(DB_DATABASE, DB_USER, DB_PASS, {\n host: DB_HOST,\n dialect: 'mssql',\n logging: process.env.NODE_ENV !== 'production' ? console.log : false, // eslint-disable-line no-console\n pool: {\n max: 5,\n min: 0,\n idle: 10000,\n },\n define: {\n engine: 'InnoDB',\n collate: 'latin1_swedish_ci',\n },\n dialectOptions: {\n // stream: proxyConnection,\n options: {\n encrypt: true,\n requestTimeout: 300000,\n enableArithAbort: false,\n },\n },\n});\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nserverMiddleware\n```\n\n```text\n/api\n```\n\n```text\ntedious\n```\n\n========================================\n\nComments:\n- Thanks so much! This is exactly what I was looking for. Had never heard of Sequelize until now. Glad it exists!","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":71,"estimatedTokens":436}}944{"id":"stack-59500064","source":"stackoverflow","questionId":59500064,"title":"vue + nuxt.js - How to have different styles based on domain?","tags":["javascript","css","vue.js","nuxt.js"],"text":"Title: vue + nuxt.js - How to have different styles based on domain?\nTags: javascript, css, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a multi-domain site with a single vue + nuxt app which needs to have different styles for each site. Any idea or suggestion how I can load different styles for a domain?\n\nMy first approach was to use a \"global\" function in a plugin js but it turned out to be too slow, respectively it get too late evaluated. This means the page is almost finished loaded until the class get evaluated. This leads to side effect that the elements get first wrongly displayed in its size or colours and later on correct displayed. This is confusing for a professional page. \n\ni.e. plugins/helper.js\n\n```\nconst domainHelper = {\n isDomain(domain) {\n if (process.client) {\n return window.location.hostname.includes(domain);\n }\n return false;\n },\n```\n\ninside a component / template \n\n```\n\n \n ...\n \n \n div.aaa { color: red }\n div.bbb { color: blue }\n \n```\n\n========================================\n\nCode:\n```text\nconst domainHelper = {\n isDomain(domain) {\n if (process.client) {\n return window.location.hostname.includes(domain);\n }\n return false;\n },\n```\n\n```text\n<template>\n <div :class=\"$domainHelper.isDomain('aaa') ? 'aaa' : 'bbb'\">\n ...\n </template>\n <style>\n div.aaa { color: red }\n div.bbb { color: blue }\n </style>\n```\n\n```js\nimport Vue from \"vue\";\n\nexport default ({ req }, inject) => {\n const host = process.server ? req.headers.host : window.location.host;\n\n Vue.prototype.$isDomain = string => {\n // implement your detection using host variable defined earlier\n };\n};\n```\n\n```js\nexport default {\n plugins: ['~/plugins/domainDetectorPlugin.js']\n}\n```\n\n```html\n<template>\n <div :class=\"$isDomain('aaa') ? 'aaa' : 'bbb'\">\n ...\n</template>\n<style>\n div.aaa { color: red }\n div.bbb { color: blue }\n</style>\n```\n\n```text\nfalse\n```\n\n```text\n~/plugins/domainDetectorPlugin.js\n```\n\n```text\nnuxt.config.js\n```\n\n========================================\n\nComments:\n- You say it's a single app but how do you deploy? One copy or multiple (for each domain) ?\n- one copy of the app. Domains are pointing to the same app instance\n- Thank you, but how can I access the \"request\" object inside a plugin? I like to have it offered as a central function which I don't have to copy and paste across all the pages and components","metadata":{"transformedAt":"2026-08-18T18:33:07.904Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":105,"estimatedTokens":601}}945{"id":"stack-69822526","source":"stackoverflow","questionId":69822526,"title":"How to get started with the @jsplumb/browser-ui in the Vuejs/Nuxtjs application?","tags":["javascript","vue.js","nuxt.js","jsplumb"],"text":"Title: How to get started with the @jsplumb/browser-ui in the Vuejs/Nuxtjs application?\nTags: javascript, vue.js, nuxt.js, jsplumb\nSource: Stack Overflow\n\nQuestion:\nI am trying to integrate the `@jsplumb/browser-ui` community edition into my application. As per the recommendation from `jsplumb` team, I am using the `@jsplumb/browser-ui` but I am not understanding how to start integrating it into my `Vue/Nuxtjs application`.\n\nFollowing are the steps I am following:\n\n- Install the `@jsplumb/browser-ui` using `npm install @jsplumb/browser-ui --save`.\n\n- Include the libraries in the `nuxt-config.js` as part of `script`:\n\n```\nscript: [\n {\n src:\"node_modules/@jsplumb/core/js/jsplumb.core.umd.js\",\n mode: 'client'\n },\n {\n src:\"node_modules/@jsplumb/browser-ui/js/jsplumb.browser-ui.umd.js\",\n mode: 'client'\n }\n ]\n```\n\n- I have the code as follows:\n\n```\n\n \n \n \n \n \n\nif (process.browser) {\n const jsPlumbBrowserUI = require('node_modules/@jsplumb/browser-ui/js/jsplumb.browser-ui.umd.js')\n const instance = jsPlumbBrowserUI.newInstance({\n container: document.getElementById('diagram')\n })\n console.log(instance)\n}\n\nexport default {\n mounted () {\n if (process.browser) {\n console.log('MOUNTED BLOCK')\n }\n }\n}\n\n```\n\nI am not understanding how to integrate it within my application. The documentation does not provide a complete example with regards to `Vue/Nuxtjs`\n\n========================================\n\nTop Answer:\nFollowing worked for me based on @kissu comments:\n\n```\n\n \n \n \n \n \n\nexport default {\n async mounted () {\n if (process.browser) {\n const jsPlumbBrowserUI = await import('@jsplumb/browser-ui')\n\n const instance = jsPlumbBrowserUI.newInstance({\n container: this.$refs.diagram\n })\n console.log(instance)\n }\n }\n}\n\n```\n\n========================================\n\nCode:\n```js\nscript: [\n {\n src:\"node_modules/@jsplumb/core/js/jsplumb.core.umd.js\",\n mode: 'client'\n },\n {\n src:\"node_modules/@jsplumb/browser-ui/js/jsplumb.browser-ui.umd.js\",\n mode: 'client'\n }\n ]\n```\n\n```html\n<template>\n <div class=\"row\">\n <div class=\"col-md-12\">\n <div id=\"diagram\" style=\"position: relative\" />\n </div>\n </div>\n</template>\n\n<script>\nif (process.browser) {\n const jsPlumbBrowserUI = require('node_modules/@jsplumb/browser-ui/js/jsplumb.browser-ui.umd.js')\n const instance = jsPlumbBrowserUI.newInstance({\n container: document.getElementById('diagram')\n })\n console.log(instance)\n}\n\nexport default {\n mounted () {\n if (process.browser) {\n console.log('MOUNTED BLOCK')\n }\n }\n}\n</script>\n```\n\n```text\n@jsplumb/browser-ui\n```\n\n```text\njsplumb\n```\n\n```text\n@jsplumb/browser-ui\n```\n\n```text\nVue/Nuxtjs application\n```\n\n```text\n@jsplumb/browser-ui\n```\n\n```text\nnpm install @jsplumb/browser-ui --save\n```\n\n```text\nnuxt-config.js\n```\n\n```text\nscript\n```\n\n```text\nVue/Nuxtjs\n```\n\n```text\n$refs\n```\n\n```html\n<template>\n <div class=\"row\">\n <div class=\"col-md-12\">\n <div id=\"diagram\" ref=\"diagram\" style=\"position: relative\" />\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n async mounted () {\n if (process.browser) {\n const jsPlumbBrowserUI = await import('@jsplumb/browser-ui')\n\n const instance = jsPlumbBrowserUI.newInstance({\n container: this.$refs.diagram\n })\n console.log(instance)\n }\n }\n}\n</script>\n```\n\n========================================\n\nComments:\n- Since we're in a modern browser context, I do recommend only imports and use a plugin or a local dynamic import: stackoverflow.com/a/67825061/8816585 On top of that, I'm not even sure that you can make a script from node_modules but this is probably not the way to go, especially if you only need it locally.\n- I've removed the node.js since it's not related to node in any way.\n- Also, don't use querySelectors but rather a `$ref` and in `mounted` to await for the DOM being mounted properly. You could even use `$nextTick` if it does not work accordingly. vuejs.org/v2/guide/…\n- Also, you may look into injecting your script from a plugin since it's still the way of doing things for scripts that are not plugged to the Vue ecosystem: stackoverflow.com/a/68485267/8816585\n- @kissu Thanks a lot for your response. I was able to make it work based on your first comment. Thanks a lot for it.","metadata":{"transformedAt":"2026-08-18T18:33:07.905Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":201,"estimatedTokens":1071}}946{"id":"stack-65154418","source":"stackoverflow","questionId":65154418,"title":"import single Vuetify component in Nuxt.js?","tags":["javascript","vue.js","nuxt.js","vuetify.js"],"text":"Title: import single Vuetify component in Nuxt.js?\nTags: javascript, vue.js, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nI use Vuetify in nuxt.js.\nHow to use this only in dashboard layout?\nin nuxt.config.js\n\n```\nmodules: [\n //['nuxt-leaflet', { /* module options */}],\n 'bootstrap-vue/nuxt',\n '@nuxtjs/axios',\n '@nuxtjs/pwa',\n '@nuxtjs/auth',\n '@nuxtjs/toast',\n ['@nuxtjs/vuetify', {rtl: true}],\n // 'nuxt-i18n',\n ],\n```\n\n========================================\n\nTop Answer:\nIf you are using NuxtJS Vuetify Module (It seems that you are), I assume that your `package.json` does not have `vuetify` listed there, because it is the `@nuxtjs/vuetify` that imports it. Thus, you can't import it using only the module name. I suggest you to import it with it's complete path like the following:\n\n```\nimport { VCard } from '~/node_modules/vuetify/lib';\n```\n\nThen register the component, of course.\n\n========================================\n\nCode:\n```text\nmodules: [\n //['nuxt-leaflet', { /* module options */}],\n 'bootstrap-vue/nuxt',\n '@nuxtjs/axios',\n '@nuxtjs/pwa',\n '@nuxtjs/auth',\n '@nuxtjs/toast',\n ['@nuxtjs/vuetify', {rtl: true}],\n // 'nuxt-i18n',\n ],\n```\n\n```text\nimport { VTextField } from 'vuetify/lib';\n```\n\n```text\ncomponents: { VTextField }\n```\n\n```text\n{\n buildModules: [\n // Simple usage\n '@nuxtjs/vuetify',\n\n // With options\n ['@nuxtjs/vuetify', { /* module options */ }]\n ]\n}\n```\n\n```text\n.vue\n```\n\n```text\ntreeShake\n```\n\n```text\nNuxt >= 2.9.0\n```\n\n```text\nimport { VCard } from '~/node_modules/vuetify/lib';\n```\n\n```text\npackage.json\n```\n\n```text\nvuetify\n```\n\n```text\n@nuxtjs/vuetify\n```\n\n========================================\n\nComments:\n- ok. but styles change. vuetify/style/src/_reset.scss . and conflict by bootstrap\n- Please try import {VTextField} from 'vuetify/lib' and add components: { VTextField }","metadata":{"transformedAt":"2026-08-18T18:33:07.905Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":102,"estimatedTokens":477}}947{"id":"stack-59510939","source":"stackoverflow","questionId":59510939,"title":"How do I handle passport js redirects from Nuxt SSR?","tags":["vue.js","vuejs2","passport.js","nuxt.js"],"text":"Title: How do I handle passport js redirects from Nuxt SSR?\nTags: vue.js, vuejs2, passport.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am using Nuxt SSR with express session and I have a passport JS redirect from the server side\n\n```\n/**\n * POST /signup\n * Create a new local account.\n */\nexports.postSignup = (req, res, next) => {\n const validationErrors = [];\n if (!validator.isEmail(req.body.email)) validationErrors.push({ msg: 'Please enter a valid email address.' });\n if (!validator.isLength(req.body.password, { min: 8 })) validationErrors.push({ msg: 'Password must be at least 8 characters long' });\n if (req.body.password !== req.body.confirmPassword) validationErrors.push({ msg: 'Passwords do not match' });\n\n if (validationErrors.length) {\n req.flash('errors', validationErrors);\n return res.redirect('/signup');\n }\n req.body.email = validator.normalizeEmail(req.body.email, { gmail_remove_dots: false });\n\n const user = new User({\n email: req.body.email,\n password: req.body.password\n });\n\n User.findOne({ email: req.body.email }, (err, existingUser) => {\n if (err) { return next(err); }\n if (existingUser) {\n req.flash('errors', { msg: 'Account with that email address already exists.' });\n return res.redirect('/signup');\n }\n user.save((err) => {\n if (err) { return next(err); }\n req.logIn(user, (err) => {\n if (err) {\n return next(err);\n }\n res.redirect('/');\n });\n });\n });\n};\n```\n\nIf I call the redirect method? it would reload the page and clear Vuex state right?\nHow do I do this redirect from passport such that Vuex state is kept intact and client page does not refresh\n\n========================================\n\nCode:\n```text\n/**\n * POST /signup\n * Create a new local account.\n */\nexports.postSignup = (req, res, next) => {\n const validationErrors = [];\n if (!validator.isEmail(req.body.email)) validationErrors.push({ msg: 'Please enter a valid email address.' });\n if (!validator.isLength(req.body.password, { min: 8 })) validationErrors.push({ msg: 'Password must be at least 8 characters long' });\n if (req.body.password !== req.body.confirmPassword) validationErrors.push({ msg: 'Passwords do not match' });\n\n if (validationErrors.length) {\n req.flash('errors', validationErrors);\n return res.redirect('/signup');\n }\n req.body.email = validator.normalizeEmail(req.body.email, { gmail_remove_dots: false });\n\n const user = new User({\n email: req.body.email,\n password: req.body.password\n });\n\n User.findOne({ email: req.body.email }, (err, existingUser) => {\n if (err) { return next(err); }\n if (existingUser) {\n req.flash('errors', { msg: 'Account with that email address already exists.' });\n return res.redirect('/signup');\n }\n user.save((err) => {\n if (err) { return next(err); }\n req.logIn(user, (err) => {\n if (err) {\n return next(err);\n }\n res.redirect('/');\n });\n });\n });\n};\n```\n\n========================================\n\nComments:\n- It seams you are using form submit for signup, you must use asynchronous signup using axios or something similar and generate positive response like `res.json({success:true})` instead of `res.redirect('/')`","metadata":{"transformedAt":"2026-08-18T18:33:07.905Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":99,"estimatedTokens":795}}948{"id":"stack-60745051","source":"stackoverflow","questionId":60745051,"title":"TypeError: (intermediate value).flat is not a function - Deploying Nuxt.js to Netlify","tags":["javascript","nuxt.js","netlify"],"text":"Title: TypeError: (intermediate value).flat is not a function - Deploying Nuxt.js to Netlify\nTags: javascript, nuxt.js, netlify\nSource: Stack Overflow\n\nQuestion:\nI'm deploying a website built with Nuxt.js to Netlify. I've run the `run npm generate` command locally and it works. But running the same command on Netlify fails with the error below. The full log is linked at the end of the question. How can I fix this?\n\n```\n1:26:30 PM: FATAL (intermediate value).flat is not a function\n1:26:30 PM: at prepareFonts (node_modules/nuxt-font-loader-strategy/lib/utils/fontFace.js:56:8)\n1:26:30 PM: at process._tickCallback (internal/process/next_tick.js:68:7)\n1:26:30 PM: at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)\n1:26:30 PM: at startup (internal/bootstrap/node.js:283:19)\n1:26:30 PM: at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)\n1:26:30 PM: ╭────────────────────────────────────────────────────────────╮\n1:26:30 PM: │ │\n1:26:30 PM: │ ✖ Nuxt Fatal Error │\n1:26:30 PM: │ │\n1:26:30 PM: │ TypeError: (intermediate value).flat is not a function │\n1:26:30 PM: │ │\n1:26:30 PM: ╰────────────────────────────────────────────────────────────╯\n```\n\nI've located that .js file but I can't see anything wrong with it. \n\n`\n\n```\nimport { extname } from 'path'\nimport { paramCase, snakeCase } from 'change-case'\n\n// Font-Face\n\nconst FONTFACE_PROPERTIES = {\n fontFamily: null,\n fontUnicodeRange: null,\n fontVariant: 'normal',\n fontFeatureSettings: 'normal',\n fontStretch: 'normal',\n fontWeight: 'normal',\n fontStyle: 'normal',\n fontDisplay: 'swap'\n}\n\nconst DEFAULT_FONT_EXTENSIONS = ['woff2', 'woff']\n\nconst DEFAULT_CLASS_PATTERN = '[family]_[variant]_[featureSettings]_[stretch]_[weight]_[style]'\n\nexport function getFontClasses (pattern, set, properties) {\n pattern = pattern || DEFAULT_CLASS_PATTERN\n const className = Object.keys(properties).reduce((result, key) => {\n let name = key.replace(/^font/, '')\n name = name.replace(/^.{1}/, name[0].toLowerCase())\n let value = properties[String(key)]\n if (name === 'family') {\n value = set\n }\n result = result.replace(`[${name}]`, value)\n return result\n }, pattern)\n return [`font_${set}`, `font_${className}`]\n}\n\nexport async function prepareFonts (options, resolve, kebabCaseProps = true) {\n const { fonts, classPattern } = options\n return (await Promise.all(fonts.map((font) => {\n const fileExtensions = getFileExtensions(font)\n return font.fontFaces.map((face) => {\n const sources = prepareSrc(face.src, fileExtensions, resolve)\n const properties = getProperties(\n Object.assign({ fontFamily: `${font.fontFamily}` }, face),\n kebabCaseProps ? paramCase : name => name\n )\n const set = snakeCase(font.fontFamily)\n return {\n classes: getFontClasses(classPattern, set, properties),\n properties,\n sources,\n set,\n preload: face.preload || false,\n local: [].concat(face.local || [])\n }\n })\n }))).flat() /*This is where the error is reported to be on Netlify*/\n}\n\nexport function createFontFace (font, baseUrl) {\n const props = font.properties\n const options = {\n display: props.fontDisplay,\n style: props.fontStyle,\n weight: props.fontWeight,\n unicodeRange: props.fontUnicodeRange,\n variant: props.fontVariant,\n featureSettings: props.fontFeatureSettings,\n stretch: props.fontStretch\n }\n const src = `url(${baseUrl + font.sources[0].path})`\n return new FontFace(props.fontFamily.replace(/'/g, ''), src, options)\n}\n\nfunction getFileExtensions (font) {\n if (Array.isArray(font.fileExtensions) && font.fileExtensions.length > 0) {\n return font.fileExtensions\n } else {\n return DEFAULT_FONT_EXTENSIONS\n }\n}\nfunction getFormat (path) {\n return extname(path).replace(/^\\./, '')\n}\n\nfunction getProperties (face, transform = paramCase) {\n return Object.keys(FONTFACE_PROPERTIES).reduce((result, prop) => {\n const value = face[prop] || FONTFACE_PROPERTIES[prop]\n if (value) {\n result[transform(prop)] = value\n }\n return result\n }, {})\n}\n\nfunction prepareSrc (src, fileExtensions, pathResolve) {\n return fileExtensions.map((fileExtension) => {\n const filePath = src + '.' + fileExtension\n return {\n path: pathResolve(filePath),\n format: getFormat(filePath)\n }\n })\n}\n```\n\nFull log:\n\n```\n1:25:50 PM: Build ready to start\n1:25:55 PM: build-image version: 2dbd444fcdce00cf06325060a8238d5ae3e86774\n1:25:55 PM: build-image tag: v3.3.7\n1:25:55 PM: buildbot version: 11918e084194721d200458438c92ff8180b3b56c\n1:25:55 PM: Fetching cached dependencies\n1:25:55 PM: Starting to download cache of 254.9KB\n1:25:55 PM: Finished downloading cache in 64.114893ms\n1:25:55 PM: Starting to extract cache\n1:25:55 PM: Failed to fetch cache, continuing with build\n1:25:55 PM: Starting to prepare the repo for build\n1:25:55 PM: No cached dependencies found. Cloning fresh repo\n1:25:55 PM: git clone https://github.com/simeon9696/indecisivefoodie-v2\n1:25:56 PM: Preparing Git Reference refs/heads/master\n1:25:57 PM: Starting build script\n1:25:57 PM: Installing dependencies\n1:25:58 PM: v10.19.0 is already installed.\n1:25:59 PM: Now using node v10.19.0 (npm v6.13.4)\n1:25:59 PM: Attempting ruby version 2.6.2, read from environment\n1:26:01 PM: Using ruby version 2.6.2\n1:26:01 PM: Using PHP version 5.6\n1:26:01 PM: Started restoring cached node modules\n1:26:01 PM: Finished restoring cached node modules\n1:26:01 PM: Installing NPM modules using NPM version 6.13.4\n1:26:22 PM: > fibers@4.0.2 install /opt/build/repo/node_modules/fibers\n1:26:22 PM: > node build.js || nodejs build.js\n1:26:22 PM: `linux-x64-64-glibc` exists; testing\n1:26:22 PM: Binary is fine; exiting\n1:26:22 PM: > core-js@2.6.11 postinstall /opt/build/repo/node_modules/core-js\n1:26:22 PM: > node -e \"try{require('./postinstall')}catch(e){}\"\n1:26:22 PM: Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling \nJavaScript standard library!\n1:26:22 PM: The project needs your help! Please consider supporting of core-js on Open Collective \nor Patreon: \n1:26:22 PM: > https://opencollective.com/core-js \n1:26:22 PM: > https://www.patreon.com/zloirock \n1:26:22 PM: Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job \n -)\n1:26:22 PM: > ejs@2.7.4 postinstall /opt/build/repo/node_modules/ejs\n1:26:22 PM: > node ./postinstall.js\n1:26:23 PM: Thank you for installing EJS: built with the Jake JavaScript build tool \n(https://jakejs.com/)\n1:26:23 PM: > nuxt@2.11.0 postinstall /opt/build/repo/node_modules/nuxt\n1:26:23 PM: > opencollective || exit 0\n1:26:23 PM: :-:\n1:26:23 PM: .==-+:\n1:26:23 PM: .==. :+- .-=-\n1:26:23 PM: .==. :==++-+=.\n1:26:23 PM: :==. -**: :+=.\n1:26:23 PM: :+- :*+++. .++.\n1:26:23 PM: :+- -*= .++: .=+.\n1:26:23 PM: -+: =*- .+*: .=+:\n1:26:23 PM: -+: .=*- .=*- =+:\n1:26:23 PM: .==: .+*: -*- -+-\n1:26:23 PM: .=+:.....:+*-.........:=*=..=*-\n1:26:23 PM: .-=------=++============++====:\n1:26:23 PM: Thanks for installing nuxtjs\n1:26:23 PM: Please consider donating to our open collective\n1:26:23 PM: to help us maintain this package.\n1:26:23 PM: Number of contributors: 229\n1:26:23 PM: Number of backers: 308\n1:26:23 PM: Annual budget: $75,947\n1:26:23 PM: Current balance: $23,984\n1:26:23 PM: Donate: https://opencollective.com/nuxtjs/donate\n1:26:25 PM: npm\n1:26:25 PM: WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.11 \n(node_modules/watchpack/node_modules/fsevents):\n1:26:25 PM: npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for \nfsevents@1.2.11: wanted {\"os\":\"darwin\",\"arch\":\"any\"} (current: {\"os\":\"linux\",\"arch\":\"x64\"})\n1:26:25 PM: npm WARN\n1:26:25 PM: optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules/fsevents):\n1:26:25 PM: npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for \nfsevents@2.1.2: wanted {\"os\":\"darwin\",\"arch\":\"any\"} (current: {\"os\":\"linux\",\"arch\":\"x64\"})\n1:26:25 PM: added 1141 packages from 517 contributors and audited 11182 packages in 22.508s\n1:26:26 PM: 39 packages are looking for funding\n1:26:26 PM: run `npm fund` for details\n1:26:26 PM: found 18 moderate severity vulnerabilities\n1:26:26 PM: run `npm audit fix` to fix them, or `npm audit` for details\n1:26:26 PM: NPM modules installed\n1:26:26 PM: Started restoring cached go cache\n1:26:26 PM: Finished restoring cached go cache\n1:26:26 PM: unset GOOS;\n1:26:26 PM: unset GOARCH;\n1:26:26 PM: export GOROOT='/opt/buildhome/.gimme/versions/go1.12.linux.amd64';\n1:26:26 PM: export PATH=\"/opt/buildhome/.gimme/versions/go1.12.linux.amd64/bin:${PATH}\";\n1:26:26 PM: go version >&2;\n1:26:26 PM: export GIMME_ENV='/opt/buildhome/.gimme/env/go1.12.linux.amd64.env';\n1:26:26 PM: go version go1.12 linux/amd64\n1:26:26 PM: Installing missing commands\n1:26:26 PM: Verify run directory\n1:26:27 PM: Executing user command: npm run generate\n1:26:27 PM: > indecisive-foodie@1.0.0 generate /opt/build/repo\n1:26:27 PM: > nuxt generate\n1:26:30 PM: WARN No .env file found in /opt/build/repo.\n1:26:30 PM: FATAL (intermediate value).flat is not a function\n1:26:30 PM: at prepareFonts (node_modules/nuxt-font-loader-strategy/lib/utils/fontFace.js:56:8)\n1:26:30 PM: at process._tickCallback (internal/process/next_tick.js:68:7)\n1:26:30 PM: at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)\n1:26:30 PM: at startup (internal/bootstrap/node.js:283:19)\n1:26:30 PM: at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)\n1:26:30 PM: ╭────────────────────────────────────────────────────────────╮\n1:26:30 PM: │ │\n1:26:30 PM: │ ✖ Nuxt Fatal Error │\n1:26:30 PM: │ │\n1:26:30 PM: │ TypeError: (intermediate value).flat is not a function │\n1:26:30 PM: │ │\n1:26:30 PM: ╰────────────────────────────────────────────────────────────╯\n1:26:30 PM: npm\n1:26:30 PM: ERR! code\n1:26:30 PM: ELIFECYCLE\n1:26:30 PM: npm\n1:26:30 PM: ERR!\n1:26:30 PM: errno 1\n1:26:30 PM: npm\n1:26:30 PM: ERR! indecisive-foodie@1.0.0 generate: `nuxt generate`\n1:26:30 PM: npm\n1:26:30 PM: ERR! Exit status 1\n1:26:30 PM: npm\n1:26:30 PM: ERR!\n1:26:30 PM: npm ERR! Failed at the indecisive-foodie@1.0.0 generate script.\n1:26:30 PM: npm ERR!\n1:26:30 PM: This is probably not a problem with npm. There is likely additional logging output \nabove.\n1:26:31 PM: npm\n1:26:31 PM: ERR! A complete log of this run can be found in:\n1:26:31 PM: npm ERR! /opt/buildhome/.npm/_logs/2020-03-18T17_26_30_664Z-debug.log\n1:26:31 PM: Skipping functions preparation step: no functions directory set\n1:26:31 PM: Caching artifacts\n1:26:31 PM: Started saving node modules\n1:26:31 PM: Finished saving node modules\n1:26:31 PM: Started saving pip cache\n1:26:32 PM: Finished saving pip cache\n1:26:32 PM: Started saving emacs cask dependencies\n1:26:32 PM: Finished saving emacs cask dependencies\n1:26:32 PM: Started saving maven dependencies\n1:26:32 PM: Finished saving maven dependencies\n1:26:32 PM: Started saving boot dependencies\n1:26:32 PM: Finished saving boot dependencies\n1:26:32 PM: Started saving go dependencies\n1:26:32 PM: Finished saving go dependencies\n1:26:36 PM: Error running command: Build script returned non-zero exit code: 1\n1:26:36 PM: Failing build: Failed to build site\n1:26:36 PM: failed during stage 'building site': Build script returned non-zero exit code: 1\n1:26:36 PM: Finished processing build request in 41.011761064s\n```\n\n========================================\n\nCode:\n```text\n1:26:30 PM: FATAL (intermediate value).flat is not a function\n1:26:30 PM: at prepareFonts (node_modules/nuxt-font-loader-strategy/lib/utils/fontFace.js:56:8)\n1:26:30 PM: at process._tickCallback (internal/process/next_tick.js:68:7)\n1:26:30 PM: at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)\n1:26:30 PM: at startup (internal/bootstrap/node.js:283:19)\n1:26:30 PM: at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)\n1:26:30 PM: ╭────────────────────────────────────────────────────────────╮\n1:26:30 PM: │ │\n1:26:30 PM: │ ✖ Nuxt Fatal Error │\n1:26:30 PM: │ │\n1:26:30 PM: │ TypeError: (intermediate value).flat is not a function │\n1:26:30 PM: │ │\n1:26:30 PM: ╰────────────────────────────────────────────────────────────╯\n```\n\n```text\nimport { extname } from 'path'\nimport { paramCase, snakeCase } from 'change-case'\n\n// Font-Face\n\nconst FONTFACE_PROPERTIES = {\n fontFamily: null,\n fontUnicodeRange: null,\n fontVariant: 'normal',\n fontFeatureSettings: 'normal',\n fontStretch: 'normal',\n fontWeight: 'normal',\n fontStyle: 'normal',\n fontDisplay: 'swap'\n}\n\nconst DEFAULT_FONT_EXTENSIONS = ['woff2', 'woff']\n\nconst DEFAULT_CLASS_PATTERN = '[family]_[variant]_[featureSettings]_[stretch]_[weight]_[style]'\n\nexport function getFontClasses (pattern, set, properties) {\n pattern = pattern || DEFAULT_CLASS_PATTERN\n const className = Object.keys(properties).reduce((result, key) => {\n let name = key.replace(/^font/, '')\n name = name.replace(/^.{1}/, name[0].toLowerCase())\n let value = properties[String(key)]\n if (name === 'family') {\n value = set\n }\n result = result.replace(`[${name}]`, value)\n return result\n }, pattern)\n return [`font_${set}`, `font_${className}`]\n}\n\nexport async function prepareFonts (options, resolve, kebabCaseProps = true) {\n const { fonts, classPattern } = options\n return (await Promise.all(fonts.map((font) => {\n const fileExtensions = getFileExtensions(font)\n return font.fontFaces.map((face) => {\n const sources = prepareSrc(face.src, fileExtensions, resolve)\n const properties = getProperties(\n Object.assign({ fontFamily: `${font.fontFamily}` }, face),\n kebabCaseProps ? paramCase : name => name\n )\n const set = snakeCase(font.fontFamily)\n return {\n classes: getFontClasses(classPattern, set, properties),\n properties,\n sources,\n set,\n preload: face.preload || false,\n local: [].concat(face.local || [])\n }\n })\n }))).flat() /*This is where the error is reported to be on Netlify*/\n}\n\nexport function createFontFace (font, baseUrl) {\n const props = font.properties\n const options = {\n display: props.fontDisplay,\n style: props.fontStyle,\n weight: props.fontWeight,\n unicodeRange: props.fontUnicodeRange,\n variant: props.fontVariant,\n featureSettings: props.fontFeatureSettings,\n stretch: props.fontStretch\n }\n const src = `url(${baseUrl + font.sources[0].path})`\n return new FontFace(props.fontFamily.replace(/'/g, ''), src, options)\n}\n\nfunction getFileExtensions (font) {\n if (Array.isArray(font.fileExtensions) && font.fileExtensions.length > 0) {\n return font.fileExtensions\n } else {\n return DEFAULT_FONT_EXTENSIONS\n }\n}\nfunction getFormat (path) {\n return extname(path).replace(/^\\./, '')\n}\n\nfunction getProperties (face, transform = paramCase) {\n return Object.keys(FONTFACE_PROPERTIES).reduce((result, prop) => {\n const value = face[prop] || FONTFACE_PROPERTIES[prop]\n if (value) {\n result[transform(prop)] = value\n }\n return result\n }, {})\n}\n\nfunction prepareSrc (src, fileExtensions, pathResolve) {\n return fileExtensions.map((fileExtension) => {\n const filePath = src + '.' + fileExtension\n return {\n path: pathResolve(filePath),\n format: getFormat(filePath)\n }\n })\n}\n```\n\n```text\n1:25:50 PM: Build ready to start\n1:25:55 PM: build-image version: 2dbd444fcdce00cf06325060a8238d5ae3e86774\n1:25:55 PM: build-image tag: v3.3.7\n1:25:55 PM: buildbot version: 11918e084194721d200458438c92ff8180b3b56c\n1:25:55 PM: Fetching cached dependencies\n1:25:55 PM: Starting to download cache of 254.9KB\n1:25:55 PM: Finished downloading cache in 64.114893ms\n1:25:55 PM: Starting to extract cache\n1:25:55 PM: Failed to fetch cache, continuing with build\n1:25:55 PM: Starting to prepare the repo for build\n1:25:55 PM: No cached dependencies found. Cloning fresh repo\n1:25:55 PM: git clone https://github.com/simeon9696/indecisivefoodie-v2\n1:25:56 PM: Preparing Git Reference refs/heads/master\n1:25:57 PM: Starting build script\n1:25:57 PM: Installing dependencies\n1:25:58 PM: v10.19.0 is already installed.\n1:25:59 PM: Now using node v10.19.0 (npm v6.13.4)\n1:25:59 PM: Attempting ruby version 2.6.2, read from environment\n1:26:01 PM: Using ruby version 2.6.2\n1:26:01 PM: Using PHP version 5.6\n1:26:01 PM: Started restoring cached node modules\n1:26:01 PM: Finished restoring cached node modules\n1:26:01 PM: Installing NPM modules using NPM version 6.13.4\n1:26:22 PM: > fibers@4.0.2 install /opt/build/repo/node_modules/fibers\n1:26:22 PM: > node build.js || nodejs build.js\n1:26:22 PM: `linux-x64-64-glibc` exists; testing\n1:26:22 PM: Binary is fine; exiting\n1:26:22 PM: > core-js@2.6.11 postinstall /opt/build/repo/node_modules/core-js\n1:26:22 PM: > node -e \"try{require('./postinstall')}catch(e){}\"\n1:26:22 PM: Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling \nJavaScript standard library!\n1:26:22 PM: The project needs your help! Please consider supporting of core-js on Open Collective \nor Patreon: \n1:26:22 PM: > https://opencollective.com/core-js \n1:26:22 PM: > https://www.patreon.com/zloirock \n1:26:22 PM: Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job \n -)\n1:26:22 PM: > ejs@2.7.4 postinstall /opt/build/repo/node_modules/ejs\n1:26:22 PM: > node ./postinstall.js\n1:26:23 PM: Thank you for installing EJS: built with the Jake JavaScript build tool \n(https://jakejs.com/)\n1:26:23 PM: > nuxt@2.11.0 postinstall /opt/build/repo/node_modules/nuxt\n1:26:23 PM: > opencollective || exit 0\n1:26:23 PM: :-:\n1:26:23 PM: .==-+:\n1:26:23 PM: .==. :+- .-=-\n1:26:23 PM: .==. :==++-+=.\n1:26:23 PM: :==. -**: :+=.\n1:26:23 PM: :+- :*+++. .++.\n1:26:23 PM: :+- -*= .++: .=+.\n1:26:23 PM: -+: =*- .+*: .=+:\n1:26:23 PM: -+: .=*- .=*- =+:\n1:26:23 PM: .==: .+*: -*- -+-\n1:26:23 PM: .=+:.....:+*-.........:=*=..=*-\n1:26:23 PM: .-=------=++============++====:\n1:26:23 PM: Thanks for installing nuxtjs\n1:26:23 PM: Please consider donating to our open collective\n1:26:23 PM: to help us maintain this package.\n1:26:23 PM: Number of contributors: 229\n1:26:23 PM: Number of backers: 308\n1:26:23 PM: Annual budget: $75,947\n1:26:23 PM: Current balance: $23,984\n1:26:23 PM: Donate: https://opencollective.com/nuxtjs/donate\n1:26:25 PM: npm\n1:26:25 PM: WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.11 \n(node_modules/watchpack/node_modules/fsevents):\n1:26:25 PM: npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for \nfsevents@1.2.11: wanted {\"os\":\"darwin\",\"arch\":\"any\"} (current: {\"os\":\"linux\",\"arch\":\"x64\"})\n1:26:25 PM: npm WARN\n1:26:25 PM: optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules/fsevents):\n1:26:25 PM: npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for \nfsevents@2.1.2: wanted {\"os\":\"darwin\",\"arch\":\"any\"} (current: {\"os\":\"linux\",\"arch\":\"x64\"})\n1:26:25 PM: added 1141 packages from 517 contributors and audited 11182 packages in 22.508s\n1:26:26 PM: 39 packages are looking for funding\n1:26:26 PM: run `npm fund` for details\n1:26:26 PM: found 18 moderate severity vulnerabilities\n1:26:26 PM: run `npm audit fix` to fix them, or `npm audit` for details\n1:26:26 PM: NPM modules installed\n1:26:26 PM: Started restoring cached go cache\n1:26:26 PM: Finished restoring cached go cache\n1:26:26 PM: unset GOOS;\n1:26:26 PM: unset GOARCH;\n1:26:26 PM: export GOROOT='/opt/buildhome/.gimme/versions/go1.12.linux.amd64';\n1:26:26 PM: export PATH=\"/opt/buildhome/.gimme/versions/go1.12.linux.amd64/bin:${PATH}\";\n1:26:26 PM: go version >&2;\n1:26:26 PM: export GIMME_ENV='/opt/buildhome/.gimme/env/go1.12.linux.amd64.env';\n1:26:26 PM: go version go1.12 linux/amd64\n1:26:26 PM: Installing missing commands\n1:26:26 PM: Verify run directory\n1:26:27 PM: Executing user command: npm run generate\n1:26:27 PM: > indecisive-foodie@1.0.0 generate /opt/build/repo\n1:26:27 PM: > nuxt generate\n1:26:30 PM: WARN No .env file found in /opt/build/repo.\n1:26:30 PM: FATAL (intermediate value).flat is not a function\n1:26:30 PM: at prepareFonts (node_modules/nuxt-font-loader-strategy/lib/utils/fontFace.js:56:8)\n1:26:30 PM: at process._tickCallback (internal/process/next_tick.js:68:7)\n1:26:30 PM: at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)\n1:26:30 PM: at startup (internal/bootstrap/node.js:283:19)\n1:26:30 PM: at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)\n1:26:30 PM: ╭────────────────────────────────────────────────────────────╮\n1:26:30 PM: │ │\n1:26:30 PM: │ ✖ Nuxt Fatal Error │\n1:26:30 PM: │ │\n1:26:30 PM: │ TypeError: (intermediate value).flat is not a function │\n1:26:30 PM: │ │\n1:26:30 PM: ╰────────────────────────────────────────────────────────────╯\n1:26:30 PM: npm\n1:26:30 PM: ERR! code\n1:26:30 PM: ELIFECYCLE\n1:26:30 PM: npm\n1:26:30 PM: ERR!\n1:26:30 PM: errno 1\n1:26:30 PM: npm\n1:26:30 PM: ERR! indecisive-foodie@1.0.0 generate: `nuxt generate`\n1:26:30 PM: npm\n1:26:30 PM: ERR! Exit status 1\n1:26:30 PM: npm\n1:26:30 PM: ERR!\n1:26:30 PM: npm ERR! Failed at the indecisive-foodie@1.0.0 generate script.\n1:26:30 PM: npm ERR!\n1:26:30 PM: This is probably not a problem with npm. There is likely additional logging output \nabove.\n1:26:31 PM: npm\n1:26:31 PM: ERR! A complete log of this run can be found in:\n1:26:31 PM: npm ERR! /opt/buildhome/.npm/_logs/2020-03-18T17_26_30_664Z-debug.log\n1:26:31 PM: Skipping functions preparation step: no functions directory set\n1:26:31 PM: Caching artifacts\n1:26:31 PM: Started saving node modules\n1:26:31 PM: Finished saving node modules\n1:26:31 PM: Started saving pip cache\n1:26:32 PM: Finished saving pip cache\n1:26:32 PM: Started saving emacs cask dependencies\n1:26:32 PM: Finished saving emacs cask dependencies\n1:26:32 PM: Started saving maven dependencies\n1:26:32 PM: Finished saving maven dependencies\n1:26:32 PM: Started saving boot dependencies\n1:26:32 PM: Finished saving boot dependencies\n1:26:32 PM: Started saving go dependencies\n1:26:32 PM: Finished saving go dependencies\n1:26:36 PM: Error running command: Build script returned non-zero exit code: 1\n1:26:36 PM: Failing build: Failed to build site\n1:26:36 PM: failed during stage 'building site': Build script returned non-zero exit code: 1\n1:26:36 PM: Finished processing build request in 41.011761064s\n```\n\n```text\nrun npm generate\n```\n\n========================================\n\nComments:\n- Thanks. Is this screenshot from the `NX Console` vscode extension? (formerly `Angular Console`)\n- @KyleVassella no, it's from the Netlify console app.netlify.com/sites//settings/…","metadata":{"transformedAt":"2026-08-18T18:33:07.905Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":561,"estimatedTokens":5835}}949{"id":"stack-61125111","source":"stackoverflow","questionId":61125111,"title":"CryptoJS AES 256 ECB Decrypt","tags":["javascript","vue.js","nuxt.js","cryptojs"],"text":"Title: CryptoJS AES 256 ECB Decrypt\nTags: javascript, vue.js, nuxt.js, cryptojs\nSource: Stack Overflow\n\nQuestion:\nI already tried aes-ecb-js and now im trying cryptoJS if it can solve my problem. I already read a few topics and googled a lot but I am not able to decrypt a HEX String with AES ECB 256.\n\nWhen using an online decoder it works just fine: \nhttps://i.sstatic.net/vpI5O.png\n\nI tried with the following code according to the documentation (https://cryptojs.gitbook.io/docs/#ciphers)\n\n```\nconsole.log('decrypt: ' + result)\n const dec = CryptoJS.AES.decrypt(result, key)\n console.log(dec)\n console.log(CryptoJS.enc.Utf8.stringify(dec))\n```\n\n\"key\" in this case is a String which looks similar to this: `34AKDASFA12312ADSFKLSDK2`\n\nThe output is sadly undefined when trying to stringily the word array in var \"dec\"\n\n========================================\n\nCode:\n```text\nconsole.log('decrypt: ' + result)\n const dec = CryptoJS.AES.decrypt(result, key)\n console.log(dec)\n console.log(CryptoJS.enc.Utf8.stringify(dec))\n```\n\n```text\n34AKDASFA12312ADSFKLSDK2\n```\n\n```text\nfunction decrypt(encodedString) {\n const crypto = require('crypto')\n const algorithm = 'aes-256-ecb'\n const dateKey = Buffer.from(\n '<YOUR_KEY>',\n 'binary'\n )\n\n const decipher = crypto.createDecipheriv(\n algorithm,\n dateKey.toString('binary'),\n ''\n )\n decipher.setAutoPadding(false)\n let dec = decipher.update(encodedString, 'hex', 'utf8')\n dec += decipher.final('utf8')\n return dec\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.905Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":57,"estimatedTokens":377}}950{"id":"stack-59897864","source":"stackoverflow","questionId":59897864,"title":"Nuxt vendor.app is too big,font awesome too big","tags":["vue.js","webpack","nuxt.js"],"text":"Title: Nuxt vendor.app is too big,font awesome too big\nTags: vue.js, webpack, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHi Im using Nuxt JS for my project and I noticed that my js files are getting rather big\n\nAnd my question is how can I make it smaller or split vendor or js files that are over 1mb\n\nAlso I have seen that font-awesome is also taking a lot of space \n\nhttps://i.sstatic.net/1nDE7.png\n\nHow can I remove all of this unecessary libraries and make js files smaller ?\n\nFont awesome is: 200KB\nfree-solid-svg-icons: 194KB\nvendor.app: 1MB\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\n\nimport { library, config } from '@fortawesome/fontawesome-svg-core'\nimport { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'\n\nimport { faGem } from '@fortawesome/free-regular-svg-icons/faGem'\nimport { faFacebookF } from '@fortawesome/free-brands-svg-icons/faFacebookF'\nimport { faUser } from '@fortawesome/free-solid-svg-icons/faUser'\n\nlibrary.add(faGem, faFacebookF, faUser)\n\nVue.component('font-awesome-icon', FontAwesomeIcon)\n```\n\n```text\n// ...\n\n plugins: [\n { src: '~/plugins/font_awesome_icons.js', mode: 'client' }\n ],\n\n// ...\n```\n\n```text\n<template>\n <font-awesome-icon :icon=\"['fab', 'facebook-f']\" />\n</template>\n\n<script>\nexport default {\n\n}\n</script>\n\n<style>\n\n</style>\n```\n\n```text\nnuxt-fontawesome\n```\n\n```text\nlibrary\n```\n\n```text\nfont_awesome_icons.js\n```\n\n```text\nnuxt-config.js\n```\n\n```text\nindex.vue\n```\n\n========================================\n\nComments:\n- Thanks, helped a lot. I was forgetting to remove original font awesome settings from nuxt config and that was causing to load everything instead just the config components.","metadata":{"transformedAt":"2026-08-18T18:33:07.905Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":87,"estimatedTokens":423}}951{"id":"stack-58533961","source":"stackoverflow","questionId":58533961,"title":"How to clone vue element with functions in nuxt?","tags":["javascript","html","vue.js","nuxt.js"],"text":"Title: How to clone vue element with functions in nuxt?\nTags: javascript, html, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have the template like this \n\n```\n\n \n \n \n \n\n \n\n```\n\nThe user can append the element into the list, so I have some function like this:\n\n```\nsomeFunc(){\nconst hidden = document.querySelector('#hiddenElement')\nconst target = document.querySelector('#appendElementsHere')\ntarget.innerHtml += hidden.outerHtml\n}\n```\n\nThe element is cloned can append to the `#appendElementsHere` successfully,\nbut the click function is not working. I think that maybe the click function in the vue element, not the html. How can I clone the element as vue-element, not html only? Or any idea to create vue element in the script (method) and then append to the dom ??\n\n========================================\n\nCode:\n```text\n<template>\n<div>\n <div id=\"hiddenElement\">\n <MyElement v-for='...' @click=\"...\">\n </MyElement>\n </div>\n\n <div id=\"appendElementsHere\" />\n</div<\n</template>\n```\n\n```text\nsomeFunc(){\nconst hidden = document.querySelector('#hiddenElement')\nconst target = document.querySelector('#appendElementsHere')\ntarget.innerHtml += hidden.outerHtml\n}\n```\n\n```text\n#appendElementsHere\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.905Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":58,"estimatedTokens":304}}952{"id":"stack-64829113","source":"stackoverflow","questionId":64829113,"title":"Methods missing from Javascript Class inside Vuex state","tags":["javascript","oop","nuxt.js","vuex"],"text":"Title: Methods missing from Javascript Class inside Vuex state\nTags: javascript, oop, nuxt.js, vuex\nSource: Stack Overflow\n\nQuestion:\nI'm using Nuxt framework alongside Vuex to store data in my web site but I'm facing trouble when I want to use a class directly in the state.\n\nWith a model `cart.js` defined like this:\n\n```\nexport class Cart {\n\n constructor(ownedID) {\n this._created = new Date();\n this._lastUpdated = new Date();\n this._ownerID = ownedID || 'visitor'\n this._items = []\n }\n\n getItem (articleNumber) {\n console.log(this._items)\n }\n\n ...\n}\n```\n\nAnd my store's module `cart.js`\n\n```\nimport { Cart } from \"~/models/cart\";\n\nconst state = () => ({\n cart: new Cart()\n})\n\nconst mutations = {\n ADD_ITEM(state, newItem) {\n console.log(state.cart)\n }\n}\n\n...\n```\n\nWhen the `ADD_ITEM(state, newItem)` mutation is called the `getItem(articleNumber)` function is missing and thus I receive the `TypeError: state.cart.getItem is not a function` error.\n\nThis is the result of the `console.log`:\n\n```\n__ob__: Object { value: {…}, dep: {…}, vmCount: 0 }\n\n _created: \n _item:\n _lastUpdated:\n _ownerID:\n```\n\nThis is a sandbox link of my setup.\n\nNuxt vuex sandbox error\n\nDoes anyone have a clue about my issue.\n\nThank you.\n\n========================================\n\nCode:\n```text\nexport class Cart {\n\n constructor(ownedID) {\n this._created = new Date();\n this._lastUpdated = new Date();\n this._ownerID = ownedID || 'visitor'\n this._items = []\n }\n\n getItem (articleNumber) {\n console.log(this._items)\n }\n\n ...\n}\n```\n\n```text\nimport { Cart } from \"~/models/cart\";\n\nconst state = () => ({\n cart: new Cart()\n})\n\nconst mutations = {\n ADD_ITEM(state, newItem) {\n console.log(state.cart)\n }\n}\n\n...\n```\n\n```text\n__ob__: Object { value: {…}, dep: {…}, vmCount: 0 }\n\n _created: \n _item:\n _lastUpdated:\n _ownerID:\n```\n\n```text\ncart.js\n```\n\n```text\ncart.js\n```\n\n```text\nADD_ITEM(state, newItem)\n```\n\n```text\ngetItem(articleNumber)\n```\n\n```text\nTypeError: state.cart.getItem is not a function\n```\n\n```text\nconsole.log\n```\n\n```text\nprototype\n```\n\n```text\nclass\n```\n\n```text\n(__proto__)\n```\n\n```text\ngetItem\n```\n\n```text\nplain objects\n```\n\n========================================\n\nComments:\n- I have changed the post with the sandbox link as requested. The issue is still there. I simply used dispatch to trigger an action which triggers my mutation.\n- according to this post you cannot put class instances in vuex store stackoverflow.com/questions/62006376/…\n- Your code works fine in Vue/Vuex, but not Nuxt. For some reason Nuxt strips the prototypal inheritance info out of state objects, which means it can't find the prototype method created by the class. (In Vue/Vuex without Nuxt, there's no `TypeError` and `getItem` works.)\n- @ggirodda according to that link `You can absolutely store class instances in the store state.` ?\n- It works ok in Vue/Vuex, just not Nuxt, so this explanation isn't quite right.\n- @Dan Yeah you're right, It worked for met too, But It mentioned in the Vue Documentation. I think this is also wrong. isn't it?\n- The doc link discusses reactivity, not existence/accessibility. It means only that prototype properties won't be reactive, which is *mostly* true. What they don't mention is that the prototype properties are at least accessible and can be used in a template, just like the prototype method `getItem`. In Nuxt they're not even accessible and don't exist, because Nuxt seems to unlink the prototype of its state objects, removing all prototypal inheritance.\n- Does anyone have any more information why it isn't working in Nuxt? Is this a bug or intentional?\n- @RolfB I think it's related to this discussion: github.com/vuex-orm/vuex-orm/issues/255","metadata":{"transformedAt":"2026-08-18T18:33:07.905Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":168,"estimatedTokens":940}}953{"id":"stack-64692095","source":"stackoverflow","questionId":64692095,"title":"How to deploy nuxt SSR app to AWS Amplify with git","tags":["amazon-web-services","vue.js","nuxt.js","aws-amplify"],"text":"Title: How to deploy nuxt SSR app to AWS Amplify with git\nTags: amazon-web-services, vue.js, nuxt.js, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI have been trying to deploy nuxt SSR app to AWS Amplify.\nMy directory structure looks like this\n\n```\nmy-nuxt-app\n|-.nuxt(contains view, dist etc.)\n|-assets\n|-components\n|-layouts\n|-pages\n|-plugins\n|-static\n|-store\n|-.gitignore\n|-nuxt.config.js\n|-package.json\n|-package-lock.json\n|-secrets.json(has my env configs)\n```\n\nWhat I am trying to do is to manage my-nuxt-app folder as a git repository and deploy the repository through AWS Amplify. I've been searching ways to deploy the app to AWS and seemed like no one actually described on full walkthrough.\n\nWhat I've done so far:\n\nI tried amplify.yml\nto\n`baseDirectory: dist`\nlike most instructions said.\ngot `'dist' not found`\n\nI tried amplify.yml\nto\n`baseDirectory: .nuxt/dist`\ngot\n`2020-11-05T06:00:05.617Z [ERROR]: !!! Build failed 2020-11-05T06:00:05.617Z [ERROR]: !!! Non-Zero Exit Code detected`\n\nI tried changing buildDir and making it a separate git repo.\n(copied package.json manually into the folder)\nIt built fine and confirmed but the URL would show 502 error page\n\n`The Lambda function result failed validation: The function tried to add, delete, or change a read-only header. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner. If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.`\n\nI don't know what I am missing, and how I should manage nuxt project with a git properly.\n\n========================================\n\nTop Answer:\nI was able to deploy using npm:\n\n```\nversion: 1\nfrontend:\n phases:\n preBuild:\n commands:\n - npm ci\n build:\n commands:\n - npm run generate\n artifacts:\n # IMPORTANT - Please verify your build output directory\n baseDirectory: dist\n files:\n - '**/*'\n cache:\n paths:\n - node_modules/**/*\n```\n\n========================================\n\nCode:\n```text\nmy-nuxt-app\n|-.nuxt(contains view, dist etc.)\n|-assets\n|-components\n|-layouts\n|-pages\n|-plugins\n|-static\n|-store\n|-.gitignore\n|-nuxt.config.js\n|-package.json\n|-package-lock.json\n|-secrets.json(has my env configs)\n```\n\n```text\nbaseDirectory: dist\n```\n\n```text\n'dist' not found\n```\n\n```text\nbaseDirectory: .nuxt/dist\n```\n\n```text\n2020-11-05T06:00:05.617Z [ERROR]: !!! Build failed 2020-11-05T06:00:05.617Z [ERROR]: !!! Non-Zero Exit Code detected\n```\n\n```text\nThe Lambda function result failed validation: The function tried to add, delete, or change a read-only header. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner. If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.\n```\n\n```yml\nversion: 1\nfrontend:\n phases:\n preBuild:\n commands:\n - yarn install\n build:\n commands:\n - yarn generate\n artifacts:\n # IMPORTANT - Please verify your build output directory\n baseDirectory: dist/\n files:\n - '**/*'\n cache:\n paths:\n - node_modules/**/*\n```\n\n```text\nversion: 1\nfrontend:\n phases:\n preBuild:\n commands:\n - npm ci\n build:\n commands:\n - npm run generate\n artifacts:\n # IMPORTANT - Please verify your build output directory\n baseDirectory: dist\n files:\n - '**/*'\n cache:\n paths:\n - node_modules/**/*\n```\n\n```text\nversion: 1\nfrontend:\n phases:\n preBuild:\n commands:\n - yarn install\n build:\n commands:\n - yarn build\n artifacts:\n baseDirectory: .amplify-hosting\n files:\n - '**/*'\n cache:\n paths:\n - node_modules/**/*\n```\n\n```text\nbuild\n```\n\n```text\ngenerate\n```\n\n```text\n.amplify-hosting\n```\n\n```text\nRedirects and Rewrites\n```\n\n========================================\n\nComments:\n- I think the post describes about deploying static nuxt spa app to amplify. not ssr?\n- SSR on Amplify seems to be very new. I haven't figured out how to get it working as well, but I'm working with AWS support to hopefully get an answer on how to do it\n- Im looking for some help/guidence to setup Amplify + Nuxt SSR(!) since september 2020. No luck yet.\n- @Tebe same thing! I found article where Amplify team says that they added SSR (next/nuxt) support, but didn't provide clear instructions to do that\n- Same here looking forward, I am planning to publish my project as SPA then convert it to SSR. Hopefully, someone publishes a way to do it in the near future.\n- You should use npm ci instead of npm install :)","metadata":{"transformedAt":"2026-08-18T18:33:07.905Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":198,"estimatedTokens":1203}}954{"id":"stack-51985279","source":"stackoverflow","questionId":51985279,"title":"Nuxt.js custom store folder","tags":["vue.js","vuex","nuxt.js"],"text":"Title: Nuxt.js custom store folder\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI tried to change vuex store path that is used by nuxt.js by default. I want my store path to be 'modules/my-module/store/store.js'. Is there any way I can do this? Or maybe I can somehow add my module store to existing store from nuxt module file?\n\n========================================\n\nCode:\n```text\nimport store from './store'; //import your module store\nexport default {\n name: 'my-module',\n computed: {\n ...\n },\n created() {\n this.$store.registerModule('myModuleStore', store);\n },\n mounted() {\n this.$store.dispatch('myModuleStore/someAction'); //example of action for your module's store\n },\n};\n```\n\n```text\nregisterModule\n```\n\n```text\nindex.vue\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.905Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":33,"estimatedTokens":194}}955{"id":"stack-52242049","source":"stackoverflow","questionId":52242049,"title":"IntelliJ IDEA Is Not Detecting Vuetify Components In Nuxt.js Project","tags":["intellij-idea","vuetify.js","nuxt.js"],"text":"Title: IntelliJ IDEA Is Not Detecting Vuetify Components In Nuxt.js Project\nTags: intellij-idea, vuetify.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have an issue with IntelliJ IDEA. \nyesterday I started a Nuxt.js Project With Vuetify as UI framework.\nBut IntelliJ IDEA It not detecting Vuetify Components. it Showing them as an Unknown HTML tag. And When I use the idea's Autocomplete It Importing That Component, although Vuetify Is Already Registered As Global COmponent.\n\n========================================\n\nTop Answer:\n**It is a bug in IntelliJ Idea**\n\nFor a temporary workaround, download The js file and paste it in your Vuetify project dir. [Note: No Need To Reference The js File.]\n\nhttps://raw.githubusercontent.com/vuetifyjs/api-generator/master/dist/fakeComponents.js\n\nRef:\n\nhttps://youtrack.jetbrains.com/issue/WEB-32886\nhttps://github.com/vuetifyjs/vuetify/issues/4590#issuecomment-414300395\n\nEDIT: THE Problem is fixed. just upgrade the ide\n\n========================================\n\nComments:\n- Thank You! I Got A Temporary Fix From The Post.","metadata":{"transformedAt":"2026-08-18T18:33:07.905Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":29,"estimatedTokens":267}}956{"id":"stack-76014443","source":"stackoverflow","questionId":76014443,"title":"Nuxt 3 - setup Redis using runtime configuration","tags":["redis","nuxt.js","nuxt3.js"],"text":"Title: Nuxt 3 - setup Redis using runtime configuration\nTags: redis, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nUsing Nuxt 3.3.2 I have Redis integration implemented as shown in Nuxt 3 docs:\nhttps://nuxt.com/docs/guide/directory-structure/server#example-using-redis\n\nIt works, only the connection is hard-coded in `nuxt.config.ts`. Is it possible to make it configurable using Nuxt runtime config variables?\n\nI managed to this:\n\n```\nredis: {\n driver: 'redis',\n host: process.env.REDIS_HOST,\n port: process.env.REDIS_PORT,\n password: process.env.REDIS_PASS\n}\n```\n\nbut those are underlying system env variables, not the Nuxt ones. So it is an option, but not the ideal one.\n\nI also tried `useRuntimeConfig()`, but got error it is undefined when used inside `nuxt.config.ts`\n\nThe question was originally asked at Nuxt GitHub forum, but no answer yet.\n\n========================================\n\nCode:\n```text\nredis: {\n driver: 'redis',\n host: process.env.REDIS_HOST,\n port: process.env.REDIS_PORT,\n password: process.env.REDIS_PASS\n}\n```\n\n```text\nnuxt.config.ts\n```\n\n```text\nuseRuntimeConfig()\n```\n\n```text\nnuxt.config.ts\n```\n\n```js\nimport redis from \"unstorage/drivers/redis\";\n\nexport default defineNitroPlugin(() => {\n const storage = useStorage();\n storage.mount(\n \"/redis\",\n redis({\n // useRuntimeConfig() is available here\n })\n );\n});\n```\n\n```text\nserver/plugins\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.905Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":68,"estimatedTokens":350}}957{"id":"stack-51308555","source":"stackoverflow","questionId":51308555,"title":"Redirecting to the same page but switched language url, using Nuxt.js and Vue-i18n","tags":["regex","vue.js","nuxt.js","vue-i18n"],"text":"Title: Redirecting to the same page but switched language url, using Nuxt.js and Vue-i18n\nTags: regex, vue.js, nuxt.js, vue-i18n\nSource: Stack Overflow\n\nQuestion:\nI am trying to redirect the user through a method when he clicks on specific buttons to change the language of the application. \n\nThese buttons are part of the standard layout of which all the pages of the project are part of so the url can differ based on which `.vue` page the user is on but the buttons are always the same which means that the redirecting has to be dynamic.\n\nFor example the url :\n\n```\nlocalhost/about\n```\n\nShould be redirected through the method (by pressing the specific button) to :\n\n```\nlocalhost/bg/about\n```\n\nIn the project the pages are inside a folder `_locale` and imported also from the .vue files outside of this folder as suggested in the Nuxt documentation for localization with Vue-i18n https://nuxtjs.org/examples/i18n/\n\n The same way are implemented the `nuxt.config.js` , `i18n.js` middleware, `i18n.js` plugin and `index.js` store files.\n\nSince it is a `Nuxt.js` application and not just a `Vue.js` one, just committing the mutation of the store through a page changing the `locale` (the language) doesn't also actually change the language and even if it did ( using `this.$i18n.locale = 'bg'` for example ) it only changes it for the specific page and with the next navigation it uses again the `fallback locale` instead, so I am trying to solve it with redirecting which does use then the correct `.json` file of the language based on the url. I am just trying to find a way for this redirecting to be more dynamic instead of nagigating only back to the `home` page of each language.\n\nIf needed the github repo : https://github.com/alexgil1994/logistics-gls\n\nSteps needed :\n\n```\nnpm install\nnpm run dev\n```\n\nCould it be done in some better way? Is there any example of Regex for such a situation? Is there an easier way than Regex?\n\nAll suggestions are welcome.\n\n========================================\n\nCode:\n```text\nlocalhost/about\n```\n\n```text\nlocalhost/bg/about\n```\n\n```text\nnpm install\nnpm run dev\n```\n\n```text\n.vue\n```\n\n```text\n_locale\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ni18n.js\n```\n\n```text\ni18n.js\n```\n\n```text\nindex.js\n```\n\n```text\nNuxt.js\n```\n\n```text\nVue.js\n```\n\n```text\nlocale\n```\n\n```text\nthis.$i18n.locale = 'bg'\n```\n\n```text\nfallback locale\n```\n\n```text\n.json\n```\n\n```text\nhome\n```\n\n```text\nchangeLanguage(locale) {\n // -- Getting the path before starting\n var beforePath = this.$nuxt.$router.history.current.path\n\n // -- Removing the previous locale from the url\n var result = ''\n result = beforePath.replace( \"/bg\", \"\" )\n result = result.replace( \"/gr\", \"\" )\n\n // -- Redirecting to the same page but in the desired language\n if ( locale == 'gr' || locale == 'bg' ) {\n this.$nuxt.$router.replace({ path: '/' + locale + result })\n } else {\n if ( result == '/' ) {\n this.$nuxt.$router.replace({ path: '/' + locale })\n } else {\n this.$nuxt.$router.replace({ path: '/' + locale + result })\n }\n }\n }\n```\n\n```text\nNuxt\n```\n\n```text\nvue-i18n\n```\n\n```text\nlocale\n```\n\n```text\n$nuxt.$router\n```\n\n```text\nnuxt\n```\n\n```text\nnuxt-i18n\n```\n\n```text\nswitchLocalePath\n```\n\n========================================\n\nComments:\n- Thank you very much for the answer! He is very helpful\n- Glad it helped you :) In case you instead use Nuxt with `nuxt-i18n` the `switchLocalePath` does work pretty well, I have just tested it for a project. For farther informations about it look into the documentation at nuxt-i18n documentation.","metadata":{"transformedAt":"2026-08-18T18:33:07.905Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":24,"totalLines":164,"estimatedTokens":925}}958{"id":"stack-68458750","source":"stackoverflow","questionId":68458750,"title":"Why won't this nuxt-socket-io emitter trigger its action?","tags":["websocket","socket.io","nuxt.js","vuex"],"text":"Title: Why won't this nuxt-socket-io emitter trigger its action?\nTags: websocket, socket.io, nuxt.js, vuex\nSource: Stack Overflow\n\nQuestion:\nI am trying to get nuxt-socket-io working on my NuxtJS application, but my emit functions do not seem to trigger the actions in my vuex store.\n\nnuxt.config.js has the following code:\n\n```\nmodules: [\n '@nuxtjs/axios',\n 'nuxt-socket-io'\n ],\n io: {\n sockets: [\n {\n name: 'main',\n url: process.env.WS_URL || 'http://localhost:3000',\n default: true,\n vuex: {\n mutations: [],\n actions: [ \"subscribeToMirror\" ],\n emitBacks: []\n },\n },\n ]\n },\n```\n\nThat subscribeToMirror action is present in my vuex store (in index.js):\n\n```\nexport const actions = {\n async subscribeToMirror() {\n console.log('emit worked');\n try {\n new TopicMessageQuery()\n .setTopicId(state.topicId)\n .setStartTime(0) // TODO: last 3 days\n .subscribe(HederaClient, res => {\n console.log(\"Got response from mirror...\"); \n return res;\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n```\n\nAnd that action should be triggered by the emit in my index.vue script:\n\n```\nmounted() {\n this.socket = this.$nuxtSocket({\n name: 'main',\n reconnection: false\n })\n },\n methods: {\n ...mapMutations([\n 'setEnv',\n 'initHashgraphClient',\n 'setTopicId',\n 'createNewTopicId'\n ]),\n ...mapActions([\n 'createAndSetTopicId'\n ]),\n subscribeToMirror() {\n console.log(\"method worked\");\n return new Promise((res) => {\n this.socket.emit('subscribeToMirror', {}, (resp) => {\n console.log(resp)\n resolve()\n })\n })\n }\n }\n```\n\nWhile I can see the 'method worked' console output from index.vue's subscribeToMirror method, I have never seen the 'emit worked' message. I have played around with this for hours, copying the instructions from this guide but have had no success.\n\nCan anyone spot what I'm doing wrong?\n\nUPDATE: I tried copying the code from this example and was unable to get a response from that heroku page. So it appears that I am completely unable to emit (even though $nuxtSocket appears to be functional and says it's connected). I am able to confirm that the socket itself is up and running, as I was able to get responses from it using the ticks from that example. I'm putting the repo for this project up here for viewing.\n\nUPDATE2: I made a much simpler project here which is also not functioning correctly but should be easier to examine.\n\n========================================\n\nCode:\n```text\nmodules: [\n '@nuxtjs/axios',\n 'nuxt-socket-io'\n ],\n io: {\n sockets: [\n {\n name: 'main',\n url: process.env.WS_URL || 'http://localhost:3000',\n default: true,\n vuex: {\n mutations: [],\n actions: [ \"subscribeToMirror\" ],\n emitBacks: []\n },\n },\n ]\n },\n```\n\n```text\nexport const actions = {\n async subscribeToMirror() {\n console.log('emit worked');\n try {\n new TopicMessageQuery()\n .setTopicId(state.topicId)\n .setStartTime(0) // TODO: last 3 days\n .subscribe(HederaClient, res => {\n console.log(\"Got response from mirror...\"); \n return res;\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n```\n\n```text\nmounted() {\n this.socket = this.$nuxtSocket({\n name: 'main',\n reconnection: false\n })\n },\n methods: {\n ...mapMutations([\n 'setEnv',\n 'initHashgraphClient',\n 'setTopicId',\n 'createNewTopicId'\n ]),\n ...mapActions([\n 'createAndSetTopicId'\n ]),\n subscribeToMirror() {\n console.log(\"method worked\");\n return new Promise((res) => {\n this.socket.emit('subscribeToMirror', {}, (resp) => {\n console.log(resp)\n resolve()\n })\n })\n }\n }\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.905Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":161,"estimatedTokens":906}}959{"id":"stack-53670125","source":"stackoverflow","questionId":53670125,"title":"Nuxt / Vuex / Vue Reactivity Issue Increment","tags":["vue.js","state","vuex","nuxt.js"],"text":"Title: Nuxt / Vuex / Vue Reactivity Issue Increment\nTags: vue.js, state, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHi everyone I am I having some difficulty when working with Nuxt and Vuex.\n\nI am trying to run through the example Vuex / Nuxt Classic Mode. \nhttps://nuxtjs.org/guide/vuex-store/\n\nAfter clicking my increment button I dont see the number go up. My page just stays at 0, I can see within the console that the state knows the number is no longer 0 but not on the screen, as if it doesnt know to be reactive.\n\nMy assumption is that I have miss configured something somewhere and my 0 is not the actual state, but I created some copy of it somehow. \n\nHere is my button within my template.\n\n```\n{{ counter }}\n```\n\nHere is my inc function within my methods.\n\n```\ninc () {\n this.$store.commit('increment')\n},\n```\n\nHere is my computed\n\n```\ncomputed: {\n counter () {\n return this.$store.getters.counter\n }\n}\n```\n\nHere is my Vuex/index.js file contained within the store folder.\n\n```\nimport Vue from 'vue'\nimport Vuex from 'vuex'\nVue.use(Vuex)\n\nconst createStore = () => {\n return new Vuex.Store({\n state: () => ({\n counter: 0\n }),\n getters: {\n counter: state => state.counter\n },\n mutations: {\n increment (state) {\n state.counter++\n }\n }\n })\n}\n\nexport default createStore\n```\n\n**Update:** Included more code snippets, and replied to existing comments.\n\n@Boussadjra Brahim @xaviert, thank you both for weighing in, I appreciate the assistance.\n\n@Boussadjra Brahim - Yes, I had tried using an action that called the mutation, that didnt seem to get me there either. I also tried adjusting the state via the action alone, and wasnt able to make any changes, however that seems correct, as I am under the impression that actions call mutations to make state changes and do not themselves do so, please correct me if you know more. I am 100% open to the idea that I did not attempt it correctly. Below is that action that didnt do anything and the one that called the mutation\n\n```\nactions: {\n increment (state) {\n state.counter++\n }\n},\n```\n\nAnd here is the version with the action calling the mutation.\n\n```\nactions: {\n incrementCounterUp () {\n this.commit('increment')\n }\n},\n```\n\n@xaviert - I have tried starting the server over, and have also tried to see if an nuxt build followed by a firebase serve, to see if maybe that helped. It did not. My normal server start is 'npm run dev'. In hopes that you/anyone else may be able to find my mistake below is my full _id.vue component and also my nuxt.config.js file as maybe that's it. Its still pretty raw and could use a lot of refactoring so hope you can sort through it well enough.\n\n**_.id.vue**\n\n```\n\n \n \n \n \n \n \n \n \n \n \n \n \n {{product.item_name}}\n \n \n \n \n \n \n \n **Brand -** {{product.brand_name}}\n\n \n \n \n **Original Price -**\n \n \n \n **Original Price -**\n ${{product.msrp}}\n \n \n **Sale Price -**\n \n \n \n **Sale Price -**\n ${{product.price}}\n \n \n Quantity x\n \n \n {{ counter }}\n \n \n \n Update\n \n Privacy |\n Terms\n \n\n \n\n// @ is an alias to /src\n\nimport firebase from '@/services/fireinit'\nimport foo from '@/components/foo'\nconst db = firebase.firestore()\nexport default {\n name: 'ProductPage',\n head () {\n return {\n title: this.product.item_name\n }\n },\n components: {\n foo\n },\n data: function () {\n return {\n product: {},\n image: '',\n name: 'Checkout',\n description: '',\n currency: 'USD',\n amount: '',\n msrp: '',\n quantity: 1\n }\n },\n methods: {\n inc () {\n this.$store.dispatch('incrementCounterUp', true)\n },\n updateProduct: function (product) {\n db.collection('products').doc(product.item_id).set(product)\n .then(function () {\n console.log('Document successfully written!')\n })\n .catch(function (error) {\n console.error('Error writing document: ', error)\n })\n },\n updateQuantity () {\n this.product.msrp = (this.quantity * this.product.orgMsrp)\n this.product.msrp = Math.round(100 * this.product.msrp) / 100\n this.product.price = this.quantity * this.product.orgPrice\n this.product.price = Math.round(100 * this.product.price) / 100\n },\n updateTextArea () {\n this.$refs.textarea.style.minHeight = this.$refs.textarea.scrollHeight + 'px'\n this.$refs.textarea2.style.minHeight = this.$refs.textarea2.scrollHeight + 'px'\n }\n },\n async asyncData({app, params, error}) {\n const ref = db.collection(\"products\").doc(params.id)\n let snap\n let thisProduct = {}\n try {\n snap = await ref.get()\n thisProduct = snap.data()\n thisProduct.orgMsrp = thisProduct.msrp\n thisProduct.orgPrice = thisProduct.price\n } catch (e) {\n // TODO: error handling\n console.error(e)\n }\n return {\n product: thisProduct\n }\n },\n mounted () {\n if(this.$refs.textarea) {\n this.$refs.textarea.style.minHeight = this.$refs.textarea.scrollHeight + 'px'\n this.$refs.textarea2.style.minHeight = this.$refs.textarea2.scrollHeight + 'px'\n }\n },\n computed: {\n counter () {\n return this.$store.getters.counter\n }\n }\n}\n\nbody {\n font-family: 'Avenir', Helvetica, Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n color: #2c3e50;\n margin: 0\n}\np{\n margin-top: 1em;\n margin-bottom: 1em;\n}\nhtml, body, #__nuxt, #__layout, .default, .product{\n height: 100%;\n}\n.product {\n justify-content: center;\n display: flex;\n max-width: 1150px;\n margin: 0 auto;\n flex-wrap: wrap;\n align-items: center;\n padding: 0 24px;\n &-price{\n input {\n border: 1px solid;\n padding: 0 .3em;\n text-align: center;\n width: 50px;\n }\n }\n}\n .product-details{\n width: 100%;\n textarea {\n width: 100%;\n font-size: inherit;\n color: inherit;\n font-family: inherit;\n font-weight: inherit;\n height: initial;\n resize: none;\n background-color: transparent;\n border: none;\n }\n h1{\n font-size: 1.9rem;\n margin: 15px 0 20px;\n }\n hr{\n width: 50%;\n margin: .5rem 0px;\n }\n p{\n\n }\n }\n .product-description-text{\n margin: 10px 0;\n }\n .product-image, .product-details-wrapper{\n align-items: center;\n display: flex;\n justify-content: center;\n }\n .product-details-wrapper{\n flex: 0 1 535px;\n }\n .product-image{\n flex: 0 1 535px;\n img{\n width: 100%;\n }\n }\n .product-price{\n .strike{\n text-decoration: line-through;\n }\n button{\n display: flex;\n width: 150px;\n height: 50px;\n border-radius: 5px;\n justify-content: center;\n font-size: 24px;\n margin-top: 20px;\n &:hover{\n cursor: pointer;\n background-color: #f1f1f1;\n box-shadow: 3px 3px 11px -1px rgba(0, 0, 0, 0.48);\n }\n }\n }\n .product-sale-price{\n color: #f30000;\n }\n .footer {\n flex: 1 1 100%;\n text-align: center;\n color: #ccc;\n margin-top: 25px;\n padding: 15px;\n a {\n color: #ccc;\n text-decoration: none;\n &:hover{\n text-decoration: underline;\n }\n }\n }\n .update-product{\n position: absolute;\n top: 0;\n text-align: center;\n }\n\n```\n\n**nuxt.confgs.js**\n\n```\nconst pkg = require('./package')\nconst { STRIPE_TOKEN } = process.env;\n\nmodule.exports = {\n vue: {\n config: {\n productionTip: false,\n devtools: true\n }\n },\n buildDir: './functions/nuxt',\n mode: 'universal',\n\n /*\n ** Headers of the page\n */\n head: {\n title: pkg.name,\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: pkg.description }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n\n /*\n ** Customize the progress-bar color\n */\n loading: { color: '#fff' },\n\n /*\n ** Global CSS\n */\n css: [\n ],\n\n /*\n ** Plugins to load before mounting the App\n */\n\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://github.com/nuxt-community/axios-module#usage\n '@nuxtjs/axios',\n 'nuxt-stripe-module'\n ],\n stripe: {\n version: 'v3',\n publishableKey: 'pk_test_XXX',\n },\n /*\n ** Axios module configuration\n */\n axios: {\n // See https://github.com/nuxt-community/axios-module#options\n },\n\n /*\n ** Build configuration\n */\n build: {\n /*\n ** You can extend webpack config here\n */\n publicPath: '/public/',\n vendor: [],\n extractCSS: true,\n bable: {\n presets: [\n 'es2015',\n 'stage-8'\n ],\n plugins: [\n ['transform-runtime', {\n 'polyfill': true,\n 'regenerator': true\n }]\n ]\n },\n extend (config, { isDev }) {\n if (isDev && process.client) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n },\n router: {\n middleware: 'router-auth'\n }\n },\n plugins: [\n { src: '~/plugins/fireauth', ssr: true }\n ]\n}\n```\n\n**store/index.js**\n\n```\nimport Vue from 'vue'\nimport Vuex from 'vuex'\nVue.use(Vuex)\n\nconst createStore = () => {\n return new Vuex.Store({\n state: () => ({\n counter: 0\n }),\n actions: {\n incrementCounterUp () {\n this.commit('increment')\n }\n },\n getters: {\n counter: state => state.counter\n },\n mutations: {\n increment (state) {\n state.counter++\n }\n }\n })\n}\n\nexport default createStore\n```\n\n========================================\n\nCode:\n```text\n<button @click=\"inc\">{{ counter }}</button>\n```\n\n```text\ninc () {\n this.$store.commit('increment')\n},\n```\n\n```text\ncomputed: {\n counter () {\n return this.$store.getters.counter\n }\n}\n```\n\n```text\nimport Vue from 'vue'\nimport Vuex from 'vuex'\nVue.use(Vuex)\n\nconst createStore = () => {\n return new Vuex.Store({\n state: () => ({\n counter: 0\n }),\n getters: {\n counter: state => state.counter\n },\n mutations: {\n increment (state) {\n state.counter++\n }\n }\n })\n}\n\nexport default createStore\n```\n\n```text\nactions: {\n increment (state) {\n state.counter++\n }\n},\n```\n\n```text\nactions: {\n incrementCounterUp () {\n this.commit('increment')\n }\n},\n```\n\n```text\n<template>\n <div class=\"product\">\n <div class=\"product-image\">\n <div class=\"product-image-img\">\n <img v-bind:src=\"product.image_file\" width=\"450px;\"/>\n </div>\n </div>\n <div class=\"product-details-wrapper\">\n <div class=\"product-details\">\n <h1>\n <div v-if=\"this.$route.query.editPage\">\n <textarea @input=\"updateTextArea\" ref=\"textarea2\" v-model=\"product.item_name\" type=\"text\" />\n </div>\n <div v-else>{{product.item_name}}</div>\n </h1>\n <div class=\"product-description\">\n <div class=\"product-description-text\" v-if=\"this.$route.query.editPage\">\n <textarea @input=\"updateTextArea\" ref=\"textarea\" v-model=\"product.description\" type=\"text\" />\n </div>\n <div class=\"product-description-text\" v-else v-html=\"product.description\"></div>\n </div>\n <p class=\"product-brand\"><strong>Brand - </strong> {{product.brand_name}}</p>\n <hr />\n <div class=\"product-price\">\n <div v-if=\"this.$route.query.editPage\">\n <strong>Original Price - </strong>\n <input v-model=\"product.msrp\" type=\"text\" />\n </div>\n <div v-else class=\"product-msrp\">\n <strong>Original Price - </strong>\n <span class=\"strike\">${{product.msrp}}</span>\n </div>\n <div v-if=\"this.$route.query.editPage\">\n <strong>Sale Price - </strong>\n <input v-model=\"product.price\" type=\"text\" />\n </div>\n <div v-else class=\"product-sale-price\">\n <strong>Sale Price - </strong>\n <span class=\"\">${{product.price}}</span>\n </div>\n <div class=\"product-price\">\n Quantity x\n <input @input=\"updateQuantity\" v-model=\"quantity\" min=\"1\" class=\"\" type=\"number\" value=\"1\" />\n </div>\n <button @click=\"inc\">{{ counter }}</button>\n </div>\n </div>\n </div>\n <div v-if=\"this.$route.query.editPage\" class=\"update-product\"> <button @click=\"updateProduct(product)\">Update</button></div>\n <div class=\"footer\">\n <router-link to=\"/privacy-policy\" target=\"_blank\">Privacy</router-link> |\n <router-link to=\"/terms\" target=\"_blank\">Terms</router-link>\n </div>\n\n </div>\n</template>\n\n<script>\n// @ is an alias to /src\n\nimport firebase from '@/services/fireinit'\nimport foo from '@/components/foo'\nconst db = firebase.firestore()\nexport default {\n name: 'ProductPage',\n head () {\n return {\n title: this.product.item_name\n }\n },\n components: {\n foo\n },\n data: function () {\n return {\n product: {},\n image: '',\n name: 'Checkout',\n description: '',\n currency: 'USD',\n amount: '',\n msrp: '',\n quantity: 1\n }\n },\n methods: {\n inc () {\n this.$store.dispatch('incrementCounterUp', true)\n },\n updateProduct: function (product) {\n db.collection('products').doc(product.item_id).set(product)\n .then(function () {\n console.log('Document successfully written!')\n })\n .catch(function (error) {\n console.error('Error writing document: ', error)\n })\n },\n updateQuantity () {\n this.product.msrp = (this.quantity * this.product.orgMsrp)\n this.product.msrp = Math.round(100 * this.product.msrp) / 100\n this.product.price = this.quantity * this.product.orgPrice\n this.product.price = Math.round(100 * this.product.price) / 100\n },\n updateTextArea () {\n this.$refs.textarea.style.minHeight = this.$refs.textarea.scrollHeight + 'px'\n this.$refs.textarea2.style.minHeight = this.$refs.textarea2.scrollHeight + 'px'\n }\n },\n async asyncData({app, params, error}) {\n const ref = db.collection(\"products\").doc(params.id)\n let snap\n let thisProduct = {}\n try {\n snap = await ref.get()\n thisProduct = snap.data()\n thisProduct.orgMsrp = thisProduct.msrp\n thisProduct.orgPrice = thisProduct.price\n } catch (e) {\n // TODO: error handling\n console.error(e)\n }\n return {\n product: thisProduct\n }\n },\n mounted () {\n if(this.$refs.textarea) {\n this.$refs.textarea.style.minHeight = this.$refs.textarea.scrollHeight + 'px'\n this.$refs.textarea2.style.minHeight = this.$refs.textarea2.scrollHeight + 'px'\n }\n },\n computed: {\n counter () {\n return this.$store.getters.counter\n }\n }\n}\n</script>\n\n\n<style lang=\"less\">\nbody {\n font-family: 'Avenir', Helvetica, Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n color: #2c3e50;\n margin: 0\n}\np{\n margin-top: 1em;\n margin-bottom: 1em;\n}\nhtml, body, #__nuxt, #__layout, .default, .product{\n height: 100%;\n}\n.product {\n justify-content: center;\n display: flex;\n max-width: 1150px;\n margin: 0 auto;\n flex-wrap: wrap;\n align-items: center;\n padding: 0 24px;\n &-price{\n input {\n border: 1px solid;\n padding: 0 .3em;\n text-align: center;\n width: 50px;\n }\n }\n}\n .product-details{\n width: 100%;\n textarea {\n width: 100%;\n font-size: inherit;\n color: inherit;\n font-family: inherit;\n font-weight: inherit;\n height: initial;\n resize: none;\n background-color: transparent;\n border: none;\n }\n h1{\n font-size: 1.9rem;\n margin: 15px 0 20px;\n }\n hr{\n width: 50%;\n margin: .5rem 0px;\n }\n p{\n\n }\n }\n .product-description-text{\n margin: 10px 0;\n }\n .product-image, .product-details-wrapper{\n align-items: center;\n display: flex;\n justify-content: center;\n }\n .product-details-wrapper{\n flex: 0 1 535px;\n }\n .product-image{\n flex: 0 1 535px;\n img{\n width: 100%;\n }\n }\n .product-price{\n .strike{\n text-decoration: line-through;\n }\n button{\n display: flex;\n width: 150px;\n height: 50px;\n border-radius: 5px;\n justify-content: center;\n font-size: 24px;\n margin-top: 20px;\n &:hover{\n cursor: pointer;\n background-color: #f1f1f1;\n box-shadow: 3px 3px 11px -1px rgba(0, 0, 0, 0.48);\n }\n }\n }\n .product-sale-price{\n color: #f30000;\n }\n .footer {\n flex: 1 1 100%;\n text-align: center;\n color: #ccc;\n margin-top: 25px;\n padding: 15px;\n a {\n color: #ccc;\n text-decoration: none;\n &:hover{\n text-decoration: underline;\n }\n }\n }\n .update-product{\n position: absolute;\n top: 0;\n text-align: center;\n }\n\n</style>\n```\n\n```text\nconst pkg = require('./package')\nconst { STRIPE_TOKEN } = process.env;\n\nmodule.exports = {\n vue: {\n config: {\n productionTip: false,\n devtools: true\n }\n },\n buildDir: './functions/nuxt',\n mode: 'universal',\n\n /*\n ** Headers of the page\n */\n head: {\n title: pkg.name,\n meta: [\n { charset: 'utf-8' },\n { name: 'viewport', content: 'width=device-width, initial-scale=1' },\n { hid: 'description', name: 'description', content: pkg.description }\n ],\n link: [\n { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }\n ]\n },\n\n /*\n ** Customize the progress-bar color\n */\n loading: { color: '#fff' },\n\n /*\n ** Global CSS\n */\n css: [\n ],\n\n /*\n ** Plugins to load before mounting the App\n */\n\n /*\n ** Nuxt.js modules\n */\n modules: [\n // Doc: https://github.com/nuxt-community/axios-module#usage\n '@nuxtjs/axios',\n 'nuxt-stripe-module'\n ],\n stripe: {\n version: 'v3',\n publishableKey: 'pk_test_XXX',\n },\n /*\n ** Axios module configuration\n */\n axios: {\n // See https://github.com/nuxt-community/axios-module#options\n },\n\n /*\n ** Build configuration\n */\n build: {\n /*\n ** You can extend webpack config here\n */\n publicPath: '/public/',\n vendor: [],\n extractCSS: true,\n bable: {\n presets: [\n 'es2015',\n 'stage-8'\n ],\n plugins: [\n ['transform-runtime', {\n 'polyfill': true,\n 'regenerator': true\n }]\n ]\n },\n extend (config, { isDev }) {\n if (isDev && process.client) {\n config.module.rules.push({\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/\n })\n }\n },\n router: {\n middleware: 'router-auth'\n }\n },\n plugins: [\n { src: '~/plugins/fireauth', ssr: true }\n ]\n}\n```\n\n```text\nimport Vue from 'vue'\nimport Vuex from 'vuex'\nVue.use(Vuex)\n\nconst createStore = () => {\n return new Vuex.Store({\n state: () => ({\n counter: 0\n }),\n actions: {\n incrementCounterUp () {\n this.commit('increment')\n }\n },\n getters: {\n counter: state => state.counter\n },\n mutations: {\n increment (state) {\n state.counter++\n }\n }\n })\n}\n\nexport default createStore\n```\n\n========================================\n\nComments:\n- did you try actions instead of the direct mutations?\n- Your example seems to work fine. Did you try restarting the Nuxt webserver? Alternatively, post the actual Vue component file, perhaps something silly is missing.\n- Couple of things you could try. In your action have a destructured commit as a parameter like this `incrementCounterUp ({commit}) { commit('increment') }` and maybe not pass the parameter 'true' in your inc method. Just `this.$store.dispatch('incrementCounterUp')`","metadata":{"transformedAt":"2026-08-18T18:33:07.906Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":948,"estimatedTokens":4691}}960{"id":"stack-58644834","source":"stackoverflow","questionId":58644834,"title":"How can I transition between two nuxt pages, while first waiting on a child component transition/animation to finish?","tags":["javascript","vue.js","transition","nuxt.js"],"text":"Title: How can I transition between two nuxt pages, while first waiting on a child component transition/animation to finish?\nTags: javascript, vue.js, transition, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a question regarding transitions. When transitioning from one page to the other, is it possible to wait for a child transition/animation (extra file, extra component) to finish and then transition to the next page?\n\nExample:\n\n1) Home (Page Component)\n\na) Logo (Vue Component)\n\n2) About (Page Component)\n\nWhen I click on the About one the homepage, I first would like to animate the Logo component, then fade out the whole homepage and then route to the About page.\n\nHere the relevant code:\n\n**Index.vue:**\n\n```\n\n \n \n About\n Homepage\n\n \n\nimport Logo from \"~/components/Logo.vue\";\nimport { TweenMax, CSSPlugin } from \"gsap\";\n\nexport default {\n components: {\n Logo\n },\n data() {\n return {\n showChild: true\n };\n },\n transition: {\n enter(el, done) {\n console.log(\"Enter Parent Home\");\n this.showChild = true;\n TweenLite.to(el, 1, {\n opacity: 1,\n onComplete: done\n });\n },\n leave(el, done) {\n this.showChild = false;\n TweenLite.to(el, 1, {\n opacity: 0,\n onComplete: done\n });\n console.log(\"Leave Parent Home\");\n console.log(\"Child Visible: \" + this.showChild);\n },\n appear: true,\n css: false\n }\n};\n\n```\n\n**Logo.vue**\n\n```\n\n \n \n \n \n \n\nexport default {\n props: {\n showChild: {\n type: Boolean,\n default: true\n }\n },\n methods: {\n enter(el, done) {\n console.log(\"Enter Child Home\");\n TweenLite.fromTo(el, 1, { x: -100 }, { x: 0, onComplete: done });\n },\n leave(el, done) {\n console.log(\"Leave Child Home\");\n TweenLite.to(el, 1, {\n x: -100,\n onComplete: done\n });\n }\n }\n};\n\n```\n\n**About.vue**\n\n```\n\n \n Home\n About\n\n \n\nexport default {\n transition: {\n enter(el, done) {\n console.log(\"Enter Parent About\");\n TweenLite.to(el, 1, {\n opacity: 1,\n onComplete: done\n });\n },\n leave(el, done) {\n console.log(\"Leave Parent About\");\n TweenLite.to(el, 1, {\n opacity: 0,\n onComplete: done\n });\n },\n appear: true,\n css: false\n }\n};\n\n```\n\nI have also created a sandbox.\n\nhttps://codesandbox.io/s/codesandbox-nuxt-psks0\n\nUnfortunately I am stuck with two problems:\n\n1) The leave transition of the child component (Logo) isn't starting right now.\n\n2) I would like to first finish the Child Component (Logo) transition and then finish the home page transition and then route to the about page. Is that even possible?\n\nThank you very much for your help.\n\nBest regards\nChris\n\n========================================\n\nCode:\n```text\n<template>\n <div class=\"home\" style=\"opacity: 0\">\n <Logo v-show=\"showChild\"/>\n <nuxt-link to=\"/about\">About</nuxt-link>\n <p>Homepage</p>\n </div>\n</template>\n\n<script>\nimport Logo from \"~/components/Logo.vue\";\nimport { TweenMax, CSSPlugin } from \"gsap\";\n\nexport default {\n components: {\n Logo\n },\n data() {\n return {\n showChild: true\n };\n },\n transition: {\n enter(el, done) {\n console.log(\"Enter Parent Home\");\n this.showChild = true;\n TweenLite.to(el, 1, {\n opacity: 1,\n onComplete: done\n });\n },\n leave(el, done) {\n this.showChild = false;\n TweenLite.to(el, 1, {\n opacity: 0,\n onComplete: done\n });\n console.log(\"Leave Parent Home\");\n console.log(\"Child Visible: \" + this.showChild);\n },\n appear: true,\n css: false\n }\n};\n</script>\n```\n\n```text\n<template>\n <transition @enter=\"enter\" @leave=\"leave\" mode=\"out-in\" :css=\"false\">\n <div style=\"display: block; width: 200px; height: 200px;\">\n <img\n style=\"objec-fit: cover; width: 100%; height: 100%\"\n src=\"https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1334&q=80\"\n >\n </div>\n </transition>\n</template>\n\n<script>\nexport default {\n props: {\n showChild: {\n type: Boolean,\n default: true\n }\n },\n methods: {\n enter(el, done) {\n console.log(\"Enter Child Home\");\n TweenLite.fromTo(el, 1, { x: -100 }, { x: 0, onComplete: done });\n },\n leave(el, done) {\n console.log(\"Leave Child Home\");\n TweenLite.to(el, 1, {\n x: -100,\n onComplete: done\n });\n }\n }\n};\n</script>\n```\n\n```text\n<template>\n <div class=\"about\" style=\"opacity: 0\">\n <nuxt-link to=\"/\">Home</nuxt-link>\n <p>About</p>\n </div>\n</template>\n\n<script>\nexport default {\n transition: {\n enter(el, done) {\n console.log(\"Enter Parent About\");\n TweenLite.to(el, 1, {\n opacity: 1,\n onComplete: done\n });\n },\n leave(el, done) {\n console.log(\"Leave Parent About\");\n TweenLite.to(el, 1, {\n opacity: 0,\n onComplete: done\n });\n },\n appear: true,\n css: false\n }\n};\n</script>\n```\n\n```text\n<transition @enter=\"enter\" @leave=\"leave\" mode=\"out-in\" :css=\"false\">\n <client-only>\n <Logo v-if=\"showChild\"/>\n </client-only>\n</transition>\n\n\nexport default {\n data() {\n return {\n showChild: true\n };\n },\n methods: {\n enter(el, done) {\n console.log(\"Enter Child Home\");\n TweenLite.fromTo(el, 1, { x: -100 }, { x: 0, onComplete: done });\n },\n leave(el, done) {\n console.log(\"Leave Child Home\");\n TweenLite.to(el, 1, {\n x: -100,\n onComplete: this.$router.push(\"/about\")\n });\n }\n }\n}\n```\n\n```text\n<button @click=\"showChild = false\" />\n```\n\n```text\nnuxt-link\n```\n\n```text\na\n```\n\n```text\nbutton\n```\n\n```text\nshowChild\n```\n\n```text\nthis.$router.push(\"/about\")\n```\n\n========================================\n\nComments:\n- Welcome to stackoverflow! Please copy the relevant code to your question.\n- Okay thanks. Have updated the question\n- Thank you very much for the tipp with just delaying the start of the route to the onComplete function. I optimized it a bit more by emiting from the child back to the parent. So I can have the start of the route in the parent component. Here is a updated Sandbox: codesandbox.io/s/codesandbox-nuxt-ex24q\n- i am glad that i could help you","metadata":{"transformedAt":"2026-08-18T18:33:07.906Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":329,"estimatedTokens":1511}}961{"id":"stack-79385549","source":"stackoverflow","questionId":79385549,"title":"Why does my icon sometimes fail to display?","tags":["vue.js","ionic-framework","svg","nuxt.js"],"text":"Title: Why does my icon sometimes fail to display?\nTags: vue.js, ionic-framework, svg, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nSo in my code, I use an icon in the following way:\n\n```\n\n \n\nimport IconTeamJournal from '~/components/icon/IconTeamJournal.vue';\n\n```\n\nThe icon is as follows:\n\n```\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n```\n\nThis is how it looks when the icon is shown:\n\nhttps://i.sstatic.net/eAKqLJjv.png\n\nThis is what it looks like when the icon is not being shown:\n\nhttps://i.sstatic.net/8MSQJsQT.png\n\nI use Vue, Nuxt, and Ionic, and sometimes the icon would disappear after refreshing the page multiple times or navigating from another page. The behavior was random, and I couldn’t figure out why. However, I found a fix and want to it.\n\nI fixed the problem by adding the key to the path and the linearGradient as follows:\n\n```\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\nimport { ref } from 'vue';\n\nfunction randomString() {\n return Math.random().toString(36).substring(2, 15);\n}\n\nconst key = ref(randomString());\n\n```\n\nRendered SVG that does not show the icon:\n\n```\n\n```\n\nRendered SVG that does show the icon:\n\n```\n\n```\n\nOkay, now I am interested in why this fixed the problem and what the problem actually is. Could somebody help me explain it?\n\n========================================\n\nCode:\n```text\n<template>\n <IconTeamJournal class=\"w-4 h-4\" />\n</template>\n\n<script setup lang=\"ts\">\nimport IconTeamJournal from '~/components/icon/IconTeamJournal.vue';\n</script>\n```\n\n```text\n<template>\n <svg\n width=\"844\"\n height=\"844\"\n viewBox=\"0 0 844 844\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M843.995 430.44H0.00476076C0.690863 465.408 5.63102 499.333 14.3292 531.72H829.671C838.369 499.333 843.309 465.408 843.995 430.44Z\"\n fill=\"url(#paint0_linear_29_3)\"\n />\n <path\n d=\"M824.755 548.6H19.2449C28.5687 578.28 41.0839 606.548 56.3886 633H787.612C802.916 606.548 815.431 578.28 824.755 548.6Z\"\n fill=\"url(#paint1_linear_29_3)\"\n />\n <path\n d=\"M777.31 649.88H66.6904C82.3345 674.213 100.411 696.834 120.576 717.4H723.424C743.589 696.834 761.666 674.213 777.31 649.88Z\"\n fill=\"url(#paint2_linear_29_3)\"\n />\n <path\n d=\"M705.897 734.28H138.103C163.265 757.16 191.203 777.042 221.353 793.36H622.647C652.797 777.042 680.735 757.16 705.897 734.28Z\"\n fill=\"url(#paint3_linear_29_3)\"\n />\n <path\n d=\"M587.697 810.24H256.303C307.175 831.971 363.182 844 422 844C480.818 844 536.826 831.971 587.697 810.24Z\"\n fill=\"url(#paint4_linear_29_3)\"\n />\n <path\n d=\"M843.995 413.56H0.00476074C0.90267 367.797 9.0866 323.82 23.4446 282.74H820.555C834.914 323.82 843.097 367.797 843.995 413.56Z\"\n fill=\"url(#paint5_linear_29_3)\"\n />\n <path\n d=\"M814.245 265.86C752.16 110.089 599.939 0 422 0C244.061 0 91.8397 110.089 29.7551 265.86H814.245Z\"\n fill=\"url(#paint6_linear_29_3)\"\n />\n <defs>\n <linearGradient\n id=\"paint0_linear_29_3\"\n x1=\"422\"\n y1=\"0\"\n x2=\"422\"\n y2=\"844\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop stop-color=\"#C24CFC\" />\n <stop\n offset=\"1\"\n stop-color=\"#FFD500\"\n />\n </linearGradient>\n <linearGradient\n id=\"paint1_linear_29_3\"\n x1=\"422\"\n y1=\"0\"\n x2=\"422\"\n y2=\"844\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop stop-color=\"#C24CFC\" />\n <stop\n offset=\"1\"\n stop-color=\"#FFD500\"\n />\n </linearGradient>\n <linearGradient\n id=\"paint2_linear_29_3\"\n x1=\"422\"\n y1=\"0\"\n x2=\"422\"\n y2=\"844\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop stop-color=\"#C24CFC\" />\n <stop\n offset=\"1\"\n stop-color=\"#FFD500\"\n />\n </linearGradient>\n <linearGradient\n id=\"paint3_linear_29_3\"\n x1=\"422\"\n y1=\"0\"\n x2=\"422\"\n y2=\"844\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop stop-color=\"#C24CFC\" />\n <stop\n offset=\"1\"\n stop-color=\"#FFD500\"\n />\n </linearGradient>\n <linearGradient\n id=\"paint4_linear_29_3\"\n x1=\"422\"\n y1=\"0\"\n x2=\"422\"\n y2=\"844\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop stop-color=\"#C24CFC\" />\n <stop\n offset=\"1\"\n stop-color=\"#FFD500\"\n />\n </linearGradient>\n <linearGradient\n id=\"paint5_linear_29_3\"\n x1=\"422\"\n y1=\"0\"\n x2=\"422\"\n y2=\"844\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop stop-color=\"#C24CFC\" />\n <stop\n offset=\"1\"\n stop-color=\"#FFD500\"\n />\n </linearGradient>\n <linearGradient\n id=\"paint6_linear_29_3\"\n x1=\"422\"\n y1=\"0\"\n x2=\"422\"\n y2=\"844\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop stop-color=\"#C24CFC\" />\n <stop\n offset=\"1\"\n stop-color=\"#FFD500\"\n />\n </linearGradient>\n </defs>\n </svg>\n</template>\n```\n\n```text\n<template>\n <svg\n width=\"844\"\n height=\"844\"\n viewBox=\"0 0 844 844\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n :key=\"`path0-${key}`\"\n d=\"M843.995 430.44H0.00476076C0.690863 465.408 5.63102 499.333 14.3292 531.72H829.671C838.369 499.333 843.309 465.408 843.995 430.44Z\"\n :fill=\"`url(#paint0_linear_${key})`\"\n />\n <path\n :key=\"`path1-${key}`\"\n d=\"M824.755 548.6H19.2449C28.5687 578.28 41.0839 606.548 56.3886 633H787.612C802.916 606.548 815.431 578.28 824.755 548.6Z\"\n :fill=\"`url(#paint1_linear_${key})`\"\n />\n <path\n :key=\"`path2-${key}`\"\n d=\"M777.31 649.88H66.6904C82.3345 674.213 100.411 696.834 120.576 717.4H723.424C743.589 696.834 761.666 674.213 777.31 649.88Z\"\n :fill=\"`url(#paint2_linear_${key})`\"\n />\n <path\n :key=\"`path3-${key}`\"\n d=\"M705.897 734.28H138.103C163.265 757.16 191.203 777.042 221.353 793.36H622.647C652.797 777.042 680.735 757.16 705.897 734.28Z\"\n :fill=\"`url(#paint3_linear_${key})`\"\n />\n <path\n :key=\"`path4-${key}`\"\n d=\"M587.697 810.24H256.303C307.175 831.971 363.182 844 422 844C480.818 844 536.826 831.971 587.697 810.24Z\"\n :fill=\"`url(#paint4_linear_${key})`\"\n />\n <path\n :key=\"`path5-${key}`\"\n d=\"M843.995 413.56H0.00476074C0.90267 367.797 9.0866 323.82 23.4446 282.74H820.555C834.914 323.82 843.097 367.797 843.995 413.56Z\"\n :fill=\"`url(#paint5_linear_${key})`\"\n />\n <path\n :key=\"`path6-${key}`\"\n d=\"M814.245 265.86C752.16 110.089 599.939 0 422 0C244.061 0 91.8397 110.089 29.7551 265.86H814.245Z\"\n :fill=\"`url(#paint6_linear_${key})`\"\n />\n <defs>\n <linearGradient\n :key=\"`linearGradient0-${key}`\"\n :id=\"`paint0_linear_${key}`\"\n x1=\"422\"\n y1=\"0\"\n x2=\"422\"\n y2=\"844\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop stop-color=\"#C24CFC\" />\n <stop\n offset=\"1\"\n stop-color=\"#FFD500\"\n />\n </linearGradient>\n <linearGradient\n :key=\"`linearGradient1-${key}`\"\n :id=\"`paint1_linear_${key}`\"\n x1=\"422\"\n y1=\"0\"\n x2=\"422\"\n y2=\"844\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop stop-color=\"#C24CFC\" />\n <stop\n offset=\"1\"\n stop-color=\"#FFD500\"\n />\n </linearGradient>\n <linearGradient\n :key=\"`linearGradient2-${key}`\"\n :id=\"`paint2_linear_${key}`\"\n x1=\"422\"\n y1=\"0\"\n x2=\"422\"\n y2=\"844\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop stop-color=\"#C24CFC\" />\n <stop\n offset=\"1\"\n stop-color=\"#FFD500\"\n />\n </linearGradient>\n <linearGradient\n :key=\"`linearGradient3-${key}`\"\n :id=\"`paint3_linear_${key}`\"\n x1=\"422\"\n y1=\"0\"\n x2=\"422\"\n y2=\"844\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop stop-color=\"#C24CFC\" />\n <stop\n offset=\"1\"\n stop-color=\"#FFD500\"\n />\n </linearGradient>\n <linearGradient\n :key=\"`linearGradient4-${key}`\"\n :id=\"`paint4_linear_${key}`\"\n x1=\"422\"\n y1=\"0\"\n x2=\"422\"\n y2=\"844\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop stop-color=\"#C24CFC\" />\n <stop\n offset=\"1\"\n stop-color=\"#FFD500\"\n />\n </linearGradient>\n <linearGradient\n :key=\"`linearGradient5-${key}`\"\n :id=\"`paint5_linear_${key}`\"\n x1=\"422\"\n y1=\"0\"\n x2=\"422\"\n y2=\"844\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop stop-color=\"#C24CFC\" />\n <stop\n offset=\"1\"\n stop-color=\"#FFD500\"\n />\n </linearGradient>\n <linearGradient\n :key=\"`linearGradient6-${key}`\"\n :id=\"`paint6_linear_${key}`\"\n x1=\"422\"\n y1=\"0\"\n x2=\"422\"\n y2=\"844\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop stop-color=\"#C24CFC\" />\n <stop\n offset=\"1\"\n stop-color=\"#FFD500\"\n />\n </linearGradient>\n </defs>\n </svg>\n</template>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue';\n\nfunction randomString() {\n return Math.random().toString(36).substring(2, 15);\n}\n\nconst key = ref(randomString());\n</script>\n```\n\n```text\n<svg data-v-1825e573=\"\" width=\"844\" height=\"844\" viewBox=\"0 0 844 844\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\" class=\"w-4 h-4\"><path d=\"M843.995 430.44H0.00476076C0.690863 465.408 5.63102 499.333 14.3292 531.72H829.671C838.369 499.333 843.309 465.408 843.995 430.44Z\" fill=\"url(#paint0_linear_29_3)\"></path><path d=\"M824.755 548.6H19.2449C28.5687 578.28 41.0839 606.548 56.3886 633H787.612C802.916 606.548 815.431 578.28 824.755 548.6Z\" fill=\"url(#paint1_linear_29_3)\"></path><path d=\"M777.31 649.88H66.6904C82.3345 674.213 100.411 696.834 120.576 717.4H723.424C743.589 696.834 761.666 674.213 777.31 649.88Z\" fill=\"url(#paint2_linear_29_3)\"></path><path d=\"M705.897 734.28H138.103C163.265 757.16 191.203 777.042 221.353 793.36H622.647C652.797 777.042 680.735 757.16 705.897 734.28Z\" fill=\"url(#paint3_linear_29_3)\"></path><path d=\"M587.697 810.24H256.303C307.175 831.971 363.182 844 422 844C480.818 844 536.826 831.971 587.697 810.24Z\" fill=\"url(#paint4_linear_29_3)\"></path><path d=\"M843.995 413.56H0.00476074C0.90267 367.797 9.0866 323.82 23.4446 282.74H820.555C834.914 323.82 843.097 367.797 843.995 413.56Z\" fill=\"url(#paint5_linear_29_3)\"></path><path d=\"M814.245 265.86C752.16 110.089 599.939 0 422 0C244.061 0 91.8397 110.089 29.7551 265.86H814.245Z\" fill=\"url(#paint6_linear_29_3)\"></path><defs><linearGradient id=\"paint0_linear_29_3\" x1=\"422\" y1=\"0\" x2=\"422\" y2=\"844\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C24CFC\"></stop><stop offset=\"1\" stop-color=\"#FFD500\"></stop></linearGradient><linearGradient id=\"paint1_linear_29_3\" x1=\"422\" y1=\"0\" x2=\"422\" y2=\"844\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C24CFC\"></stop><stop offset=\"1\" stop-color=\"#FFD500\"></stop></linearGradient><linearGradient id=\"paint2_linear_29_3\" x1=\"422\" y1=\"0\" x2=\"422\" y2=\"844\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C24CFC\"></stop><stop offset=\"1\" stop-color=\"#FFD500\"></stop></linearGradient><linearGradient id=\"paint3_linear_29_3\" x1=\"422\" y1=\"0\" x2=\"422\" y2=\"844\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C24CFC\"></stop><stop offset=\"1\" stop-color=\"#FFD500\"></stop></linearGradient><linearGradient id=\"paint4_linear_29_3\" x1=\"422\" y1=\"0\" x2=\"422\" y2=\"844\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C24CFC\"></stop><stop offset=\"1\" stop-color=\"#FFD500\"></stop></linearGradient><linearGradient id=\"paint5_linear_29_3\" x1=\"422\" y1=\"0\" x2=\"422\" y2=\"844\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C24CFC\"></stop><stop offset=\"1\" stop-color=\"#FFD500\"></stop></linearGradient><linearGradient id=\"paint6_linear_29_3\" x1=\"422\" y1=\"0\" x2=\"422\" y2=\"844\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C24CFC\"></stop><stop offset=\"1\" stop-color=\"#FFD500\"></stop></linearGradient></defs></svg>\n```\n\n```text\n<svg data-v-1825e573=\"\" width=\"844\" height=\"844\" viewBox=\"0 0 844 844\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\" class=\"w-4 h-4\"><path d=\"M843.995 430.44H0.00476076C0.690863 465.408 5.63102 499.333 14.3292 531.72H829.671C838.369 499.333 843.309 465.408 843.995 430.44Z\" fill=\"url(#paint0_linear_29_3)\"></path><path d=\"M824.755 548.6H19.2449C28.5687 578.28 41.0839 606.548 56.3886 633H787.612C802.916 606.548 815.431 578.28 824.755 548.6Z\" fill=\"url(#paint1_linear_29_3)\"></path><path d=\"M777.31 649.88H66.6904C82.3345 674.213 100.411 696.834 120.576 717.4H723.424C743.589 696.834 761.666 674.213 777.31 649.88Z\" fill=\"url(#paint2_linear_29_3)\"></path><path d=\"M705.897 734.28H138.103C163.265 757.16 191.203 777.042 221.353 793.36H622.647C652.797 777.042 680.735 757.16 705.897 734.28Z\" fill=\"url(#paint3_linear_29_3)\"></path><path d=\"M587.697 810.24H256.303C307.175 831.971 363.182 844 422 844C480.818 844 536.826 831.971 587.697 810.24Z\" fill=\"url(#paint4_linear_29_3)\"></path><path d=\"M843.995 413.56H0.00476074C0.90267 367.797 9.0866 323.82 23.4446 282.74H820.555C834.914 323.82 843.097 367.797 843.995 413.56Z\" fill=\"url(#paint5_linear_29_3)\"></path><path d=\"M814.245 265.86C752.16 110.089 599.939 0 422 0C244.061 0 91.8397 110.089 29.7551 265.86H814.245Z\" fill=\"url(#paint6_linear_29_3)\"></path><defs><linearGradient id=\"paint0_linear_29_3\" x1=\"422\" y1=\"0\" x2=\"422\" y2=\"844\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C24CFC\"></stop><stop offset=\"1\" stop-color=\"#FFD500\"></stop></linearGradient><linearGradient id=\"paint1_linear_29_3\" x1=\"422\" y1=\"0\" x2=\"422\" y2=\"844\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C24CFC\"></stop><stop offset=\"1\" stop-color=\"#FFD500\"></stop></linearGradient><linearGradient id=\"paint2_linear_29_3\" x1=\"422\" y1=\"0\" x2=\"422\" y2=\"844\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C24CFC\"></stop><stop offset=\"1\" stop-color=\"#FFD500\"></stop></linearGradient><linearGradient id=\"paint3_linear_29_3\" x1=\"422\" y1=\"0\" x2=\"422\" y2=\"844\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C24CFC\"></stop><stop offset=\"1\" stop-color=\"#FFD500\"></stop></linearGradient><linearGradient id=\"paint4_linear_29_3\" x1=\"422\" y1=\"0\" x2=\"422\" y2=\"844\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C24CFC\"></stop><stop offset=\"1\" stop-color=\"#FFD500\"></stop></linearGradient><linearGradient id=\"paint5_linear_29_3\" x1=\"422\" y1=\"0\" x2=\"422\" y2=\"844\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C24CFC\"></stop><stop offset=\"1\" stop-color=\"#FFD500\"></stop></linearGradient><linearGradient id=\"paint6_linear_29_3\" x1=\"422\" y1=\"0\" x2=\"422\" y2=\"844\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C24CFC\"></stop><stop offset=\"1\" stop-color=\"#FFD500\"></stop></linearGradient></defs></svg>\n```\n\n========================================\n\nComments:\n- Did you inspect how it disappeared? Did the component not render, was the SVG missing, did the gradients not work leaving you with a black-on-black image?\n- I inspected it, and the component did render. I can see it inside the inspector as the rendered SVG. When I compare the displayed SVG to the one that isn't showing, they have the same content, but it seems that the linear gradient doesn't use a color for some reason and appears black. ``` ``` even when it has the correct color.\n- Does it still occur when you put the `defs` ahead of the `path`s? Shouldn't make a difference, but maybe it does?\n- Yes it is still happenning even after moving\n- You are right—the problem was that the ID wasn’t unique. I first tried using a static ID with a dynamic key, but it didn’t render. When I switched to a static key and a dynamic ID, it rendered correctly. I also tried adding icons, and they worked. I found that each time I navigated to a page with an icon, the old page didn’t get destroyed. Instead, a new one was generated, which made the ID non-unique. This likely caused the first ID to render, while the others were skipped.\n- The first matching gradient ID is used, and paths without a gradient stay uncolored . The path only defines where the linear gradient color should go. Without it, the path remains black. The reason is that Ionic caches pages by their path. Since I use [id].vue, a new page is generated each time, leading to multiple identical IDs and causing this issue.\n- Thank you! Thanks to you, I managed to solve this.\n- @PeterPlevko Yes, it's a sneaky one, especially considering the fact that some frameworks could also keep their pages alive, use transitions etc etc...quite a sneaky one to troubleshoot but makes sense once you found out about it!","metadata":{"transformedAt":"2026-08-18T18:33:07.906Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":477,"estimatedTokens":4710}}962{"id":"stack-59181951","source":"stackoverflow","questionId":59181951,"title":"not is not providing internal link like an anchor tag","tags":["vue.js","nuxt.js"],"text":"Title: not is not providing internal link like an anchor tag\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a link defined in nuxt pages like this:\n\n```\nSection X\n```\n\nThe link is actually added to the menu in my global layout file. When I try to click the link from a page different than a root page (/any-path) the link is taking me back to the landing page and displaying the section as expected. But when I try to click the link from the root page (/), it's not performing any navigation. \n\nI tried using anchor tag in the same way: \n\n```\nSection X\n```\n\nThe anchor tag will work fine for the root page internal navigation but when clicked from a different page, it will provide a navigation to the root page but not to the internal link(e.g. #section-x). \n\nIs there any way to use the or tag and providing an internal html navigation too from any pages as it should?\n\n========================================\n\nCode:\n```text\n<NuxtLink to=\"/#section-x\">Section X</NuxtLink>\n```\n\n```text\n<a href=\"/#section-x\">Section X</NuxtLink>\n```\n\n```text\n<nuxt-link\n :to=\"{path: '/', hash: 'section-x'}\" \n v-scroll-to=\"{el: '#section-x'}\n\">\n Section X\n</nuxt-link>\n```\n\n========================================\n\nComments:\n- what version of `nuxt` are you using? Also, i believe the correct \"tag\" should be ``\n- Each vue component can be referenced both by pascal case() and a camel case(). They both represent the same and it's not a new thing in vue/nuxt. :) As per my vue version is, it's v2.8.1.\n- @Vectrobyte i think you ment kebab-case for the `nuxt-link` notation :P\n- Oops my bad, sorry. :D","metadata":{"transformedAt":"2026-08-18T18:33:07.906Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":50,"estimatedTokens":402}}963{"id":"stack-57654022","source":"stackoverflow","questionId":57654022,"title":"How to set up 2 project website in nginx [im using nuxt run diffent port]","tags":["javascript","ubuntu","nginx","nuxt.js"],"text":"Title: How to set up 2 project website in nginx [im using nuxt run diffent port]\nTags: javascript, ubuntu, nginx, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nHere is my structure folder \n\nvar \n\nwww\n\nhtml\n\nbackoffice\n\nfrontend\n\nMy projects are in backoffice and frontend \n\nIm using pm2 to start my server port 3000, 3100\n\n```\nlocation / {\n proxy_pass http://localhost:3000;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection 'upgrade';\n proxy_set_header Host $host;\n proxy_cache_bypass $http_upgrade;\n}\n\nlocation /admin {\n proxy_pass http://localhost:3001/admin;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection 'upgrade';\n proxy_set_header Host $host;\n proxy_cache_bypass $http_upgrade;\n}\n```\n\nthe path / is fine . The problem is in my /admin It's turn into white screen \n\nIn nuxt when I npm run build It will compile into .nuxt folder\n\nthe problem are here when I run /admin path It run at port 3001\n\nI try to debug by inspect element my js path \n\n```\n/_nuxt/921cc8ac0d041c1ae8a6.js\n```\n\nand when I click into link It's \n\n```\n/* script not found */\n```\n\nthe problem are here I think It's run port 3000 in stead of 3100 that's why It cant read any Css in /admin or 3001 port\n\nHow can I fix this\n\n========================================\n\nTop Answer:\nAs for Nuxt3, you can configure `app.baseURL` or set the env variable `NUXT_APP_BASE_URL`.\n\nHere the docs.\n\n========================================\n\nCode:\n```text\nlocation / {\n proxy_pass http://localhost:3000;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection 'upgrade';\n proxy_set_header Host $host;\n proxy_cache_bypass $http_upgrade;\n}\n\nlocation /admin {\n proxy_pass http://localhost:3001/admin;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection 'upgrade';\n proxy_set_header Host $host;\n proxy_cache_bypass $http_upgrade;\n}\n```\n\n```text\n/_nuxt/921cc8ac0d041c1ae8a6.js\n```\n\n```text\n/* script not found */\n```\n\n```text\nrouter: {\n base: '/admin/'\n}\n```\n\n```text\napp.baseURL\n```\n\n```text\nNUXT_APP_BASE_URL\n```\n\n========================================\n\nComments:\n- Please the package.json, nuxt.config.js file to inspect the issue.","metadata":{"transformedAt":"2026-08-18T18:33:07.906Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":119,"estimatedTokens":577}}964{"id":"stack-55850891","source":"stackoverflow","questionId":55850891,"title":"How can I dynamically export components in index.js?","tags":["javascript","node.js","vue.js","nuxt.js","atomic-design"],"text":"Title: How can I dynamically export components in index.js?\nTags: javascript, node.js, vue.js, nuxt.js, atomic-design\nSource: Stack Overflow\n\nQuestion:\nI'm working on a project with nuxt.js and I want to implement the atomic design methodology\n\nso I currently import the components like this\n\n```\nimport ButtonStyled from '@/components/atoms/ButtonStyled.vue'\nimport TextLead from '@/components/atoms/TextLead.vue'\nimport InputSearch from '@/components/atoms/InputSearch.vue'\n```\n\nbut I need to import like this\n\n```\nimport {\n ButtonStyled,\n TextLead,\n InputSearch\n} from '@/components/atoms'\n```\n\nthe closer I got was that,\n\n```\n/atoms/index.js\n```\n\n```\nconst req = require.context('./', true, /\\.vue$/)\n\nconst modules = {}\n\nreq.keys().forEach(fileName => {\n const componentName = fileName.replace(/^.+\\/([^/]+)\\.vue/, '$1')\n modules[componentName] = req(fileName).default\n})\n\nexport const { ButtonStyled, TextLead } = modules\n```\n\nbut I'm still defining the export variable names statically, I need to define dynamics based on the components inside the folder\n\nNOTE: I can not use\n\n```\nexport default modules\n```\n\nif I use the above code snippet I will not be able to import the way I need it, which is:\n\n```\nimport { ButtonStyled } from \"@/components/atoms\"\n```\n\n========================================\n\nTop Answer:\n`require.context` is a quite obscure function in Webpack, you will have issues while running unit tests. But, to solve your problem; You will need to import the index.js file in the `main.js` of your project.\n\nThis is how I do it:\n\n_globals.js\n\n```\n// Globally register all base components prefixed with _base for convenience, because they\n// will be used very frequently. Components are registered using the\n// PascalCased version of their file name.\nimport Vue from 'vue'\nimport upperFirst from 'lodash/upperFirst'\nimport camelCase from 'lodash/camelCase'\n\nconst requireComponent = require.context('.', true, /_base-[\\w-]+\\.vue$/)\n\nrequireComponent.keys().forEach(fileName => {\n const componentConfig = requireComponent(fileName)\n\n const componentName = upperFirst(\n camelCase(fileName.replace(/^\\.\\/_base/, '').replace(/\\.\\w+$/, ''))\n )\n\n Vue.component(componentName, componentConfig.default || componentConfig)\n})\n```\n\ncomponents/index.js\n\n```\n//...\nimport './_globals'\n//...\n```\n\nmain.js\n\n```\n//...\nimport './components' // This imports in the index.js\n//...\n```\n\nThis way your components loaded in with `require.context()` gets registered as a vue component and made globally available. I advice to only use global components with components that will be used a lot. Do not load a component globally if you intend to use it only one time.\n\nYou can find a working example here -> https://github.com/IlyasDeckers/vuetiful/tree/master/src\n\nTo get your unit tests working with jest, you will need to mock `require.context()`. This was a true pain, but can be achieved easily by using babel-plugin-transform-require-context\n\n========================================\n\nCode:\n```text\nimport ButtonStyled from '@/components/atoms/ButtonStyled.vue'\nimport TextLead from '@/components/atoms/TextLead.vue'\nimport InputSearch from '@/components/atoms/InputSearch.vue'\n```\n\n```text\nimport {\n ButtonStyled,\n TextLead,\n InputSearch\n} from '@/components/atoms'\n```\n\n```text\n/atoms/index.js\n```\n\n```text\nconst req = require.context('./', true, /\\.vue$/)\n\nconst modules = {}\n\nreq.keys().forEach(fileName => {\n const componentName = fileName.replace(/^.+\\/([^/]+)\\.vue/, '$1')\n modules[componentName] = req(fileName).default\n})\n\nexport const { ButtonStyled, TextLead } = modules\n```\n\n```text\nexport default modules\n```\n\n```text\nimport { ButtonStyled } from \"@/components/atoms\"\n```\n\n```text\n// Globally register all base components prefixed with _base for convenience, because they\n// will be used very frequently. Components are registered using the\n// PascalCased version of their file name.\nimport Vue from 'vue'\nimport upperFirst from 'lodash/upperFirst'\nimport camelCase from 'lodash/camelCase'\n\nconst requireComponent = require.context('.', true, /_base-[\\w-]+\\.vue$/)\n\nrequireComponent.keys().forEach(fileName => {\n const componentConfig = requireComponent(fileName)\n\n const componentName = upperFirst(\n camelCase(fileName.replace(/^\\.\\/_base/, '').replace(/\\.\\w+$/, ''))\n )\n\n Vue.component(componentName, componentConfig.default || componentConfig)\n})\n```\n\n```text\n//...\nimport './_globals'\n//...\n```\n\n```text\n//...\nimport './components' // This imports in the index.js\n//...\n```\n\n```text\nrequire.context\n```\n\n```text\nmain.js\n```\n\n```text\nrequire.context()\n```\n\n```text\nrequire.context()\n```\n\n```text\nconst req = require.context(\"./\", true, /\\.vue$/);\nconst atoms = {};\nreq.keys().forEach(fileName => {\n const componentName = fileName.replace(/^.+\\/([^/]+)\\.vue/, \"$1\");\n atoms[componentName] = req(fileName).default;\n});\nexport default atoms;\n```\n\n```text\nimport k from \"@/components/atoms/index.js\";\nexport default {\n components: {\n test1: k.test1,\n test2: k.test2\n }\n};\n```\n\n```text\nimport test1 from \"./test1.vue\";\nimport test2 from \"./test2.vue\";\n\nexport { test1, test2 };\n```\n\n```text\nimport {test1,test2} from \"@/components/atoms/index.js\";\n\nexport default {\n components: {\n test1,\n test2\n }\n};\n```\n\n========================================\n\nComments:\n- as mentioned in the description of the question, I am using nuxt.js, so I do not have the main.js file and I do not want to register components globally, this has nothing to do with my question. I need to export components in index.js dynamically, export is different from registering globally, sorry for my bad english\n- I updated my question with as close as I got to the solution, take a look please and if I can help\n- still gets very verbose, large, component object, I need a solution like in my question ``` components: { ButtonStyled: atoms.ButtonStyled, TextLead: atoms.TextLead, InputSearch: atoms.InputSearch } ```\n- or you kan use this in your index.js :: import test1 from \"./test1.vue\"; import test2 from \"./test2.vue\"; export { test1, test2 };\n- and I have put the new code at the answer, I have no way to auto export all file under the dir\n- so it is not dynamic export, it is static, fixed\n- I know what you want ,but I think it is no way to do that, exports not require a dynamic name,and exports default only can import all of the object; I have see some util on NPM ,they are use the static way to do that. you may need see the article about export on MDN\n- I updated my question with as close as I got to the solution, take a look please and if I can help\n- I think it is not be allow to do like what you want\n- The link is not found.","metadata":{"transformedAt":"2026-08-18T18:33:07.906Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":252,"estimatedTokens":1667}}965{"id":"stack-52367491","source":"stackoverflow","questionId":52367491,"title":"Add a slask / at the end of every routes in Nuxt.js","tags":["vue.js","nuxt.js","nuxt-edge"],"text":"Title: Add a slask / at the end of every routes in Nuxt.js\nTags: vue.js, nuxt.js, nuxt-edge\nSource: Stack Overflow\n\nQuestion:\nFor a purpose of SEO i've been asked to add a slash at the end of every routes of my nuxt project. For example myapp.com/company should be myapp.com/company/ Is there a clean way to do that in Nuxt ?\n\n========================================\n\nTop Answer:\nI am doing the requirement, too. I do the task with the following method, which I do not know it is right.\n\nTwo steps:\n\nNginx rewrite the url, that is to add slash of '/' to the end of url, which the url isn't ended with a slash. In this case, the http request is sent to the web server.\n\nAt another case, if the request (or link routing) is routed at the front end, that the request does not send http request to the web server. Then add a middleware file called addSlash.js like this:\n\n```\nfunction isThereSlashEnd(path) {\n let isSlash = true\n if (path) {\n let length = path.length\n isSlash = path[length-1] == '/' ? true : false\n console.log('??? path222: ', path, path[length-1], isSlash)\n }\n return isSlash\n}\nexport default function({ req, store, route, redirect }) {\n\n /**\n * Add slash of '/' at the end of url\n */\n let isSlash = isThereSlashEnd(route.fullPath)\n console.log('??? path111: ', isSlash, route.fullPath, process.client)\n if (!isSlash) {\n if (process.client) {\n window.location.href = route.fullPath + '/'\n console.log('??? path: ', isSlash, route.fullPath, process.client, window.location)\n }\n }\n}\n```\n\nWith two steps above, get the task done.\n\n========================================\n\nCode:\n```text\nserverMiddleware: [\"~/servermiddleware/seo.js\"],\n```\n\n```text\nconst redirects = require('../301.json');\nmodule.exports = function (req, res, next) {\n const redirect = redirects.find(r => r.from === req.url);\n if (redirect) {\n console.log(`redirect: ${redirect.from} => ${redirect.to}`);\n res.writeHead(301, { Location: redirect.to });\n res.end();\n } else {\n next();\n }\n}\n```\n\n```text\n[\n { \"from\": \"/company\", \"to\": \"/company/\" }\n]\n```\n\n```text\nfunction isThereSlashEnd(path) {\n let isSlash = true\n if (path) {\n let length = path.length\n isSlash = path[length-1] == '/' ? true : false\n console.log('??? path222: ', path, path[length-1], isSlash)\n }\n return isSlash\n}\nexport default function({ req, store, route, redirect }) {\n\n /**\n * Add slash of '/' at the end of url\n */\n let isSlash = isThereSlashEnd(route.fullPath)\n console.log('??? path111: ', isSlash, route.fullPath, process.client)\n if (!isSlash) {\n if (process.client) {\n window.location.href = route.fullPath + '/'\n console.log('??? path: ', isSlash, route.fullPath, process.client, window.location)\n }\n }\n}\n```\n\n```text\nrouter: {\n trailingSlash: true\n}\n```\n\n```text\nsitemap: {\n hostname: 'https://www.mywebsite.com',\n trailingSlash: true,\n},\n```\n\n========================================\n\nComments:\n- Every url has the redirection of route. Is this a good solution?","metadata":{"transformedAt":"2026-08-18T18:33:07.906Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":116,"estimatedTokens":748}}966{"id":"stack-49166090","source":"stackoverflow","questionId":49166090,"title":"How to handle route param updates in nuxt.js","tags":["vue.js","vue-router","nuxt.js"],"text":"Title: How to handle route param updates in nuxt.js\nTags: vue.js, vue-router, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIf the destination is the same as the current route and only params are changing \n\n```\ngoing from one profile to another /users/1 -> /users/2.\n```\n\nHow can I recognize this and update the component?\n\n========================================\n\nCode:\n```text\ngoing from one profile to another /users/1 -> /users/2.\n```\n\n```text\nwatch\n```\n\n========================================\n\nComments:\n- if you are using the route param in the component already, it will automacally be updated\n- nuxt will automatically take care of this. You need not explicitly do any logic (like introducing \"watch\" as descibed in answer below). it was required in vuejs routing but not in nuxt.","metadata":{"transformedAt":"2026-08-18T18:33:07.906Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":29,"estimatedTokens":197}}967{"id":"stack-65337742","source":"stackoverflow","questionId":65337742,"title":"Nuxt.js - How do I use vue-i18n outside components?","tags":["vue.js","internationalization","nuxt.js","vue-i18n","nuxt-i18n"],"text":"Title: Nuxt.js - How do I use vue-i18n outside components?\nTags: vue.js, internationalization, nuxt.js, vue-i18n, nuxt-i18n\nSource: Stack Overflow\n\nQuestion:\nI'm using the plugin vue-i18n for translations in a Nuxt.js-powered SPA. This allows easy access to messages **within components**, like this:\n\n```\n$t('footer.press')\n```\n\nBut how do I get translations **outside components**? In my specific case, I need them in a store action:\n\n```\nexport const actions = {\n\n async myAction({ commit, state, rootState, rootGetters }, options) {\n\n (...)\n\n const message = $t(\"example.message.key\") // doesn't work, undefined\n const message1 = this.$i18n.t(\"example.message.key\") // doesn't work, undefined\n\n (...)\n\n })\n\n }\n```\n\nThis is how I include the vue-i18n plugin in the project:\n\n**package.json**\n\n```\n…\n \"dependencies\": {\n …\n \"vue-i18n\": \"^8.18.2\",\n …\n },\n…\n```\n\n**nuxt.config.js**\n\n```\n…\nplugins: [\n …\n '~/plugins/i18n',\n …\n ],\n…\n```\n\n========================================\n\nTop Answer:\n```\nthis.$t('logInWongCredentials')\n```\n\n(nuxt)\n\n========================================\n\nCode:\n```text\n$t('footer.press')\n```\n\n```text\nexport const actions = {\n\n async myAction({ commit, state, rootState, rootGetters }, options) {\n\n (...)\n\n const message = $t(\"example.message.key\") // doesn't work, undefined\n const message1 = this.$i18n.t(\"example.message.key\") // doesn't work, undefined\n\n (...)\n\n })\n\n }\n```\n\n```text\n…\n \"dependencies\": {\n …\n \"vue-i18n\": \"^8.18.2\",\n …\n },\n…\n```\n\n```text\n…\nplugins: [\n …\n '~/plugins/i18n',\n …\n ],\n…\n```\n\n```text\nconst message = this.app.i18n.t(\"example.message.key\")\n```\n\n```text\nthis.$t('logInWongCredentials')\n```\n\n========================================\n\nComments:\n- There need to be explain, how you manage to to have `app.i18n` available as it will crash (ErrorType) when call `this.app.i18n`\n- @Osify I added more info to the question, hope this helps.\n- thanks for update, I think, it's not matched to my case, I am using nuxt-i18n module, I write some javascript helper as an util outside the component and which suppose to call it when need in Vue component stuffs, I still cannot make the translation done in the helper js, either via this.app, via Vue.i18n etc.\n- @Osify To leverage reactivity system, your helper must return a i18n key identifier which will be used inside the downstream component. Therefore, when the current locale change at runtime, you get instantly new translations !\n- I can't get this working, can you provide more info about `this`?\n- You missed the \"outside component\" part","metadata":{"transformedAt":"2026-08-18T18:33:07.906Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":126,"estimatedTokens":655}}968{"id":"stack-74337462","source":"stackoverflow","questionId":74337462,"title":"@nuxtjs/google-fonts ignoring other weights, works only for 400","tags":["vue.js","fonts","nuxt.js","google-font-api"],"text":"Title: @nuxtjs/google-fonts ignoring other weights, works only for 400\nTags: vue.js, fonts, nuxt.js, google-font-api\nSource: Stack Overflow\n\nQuestion:\nI am using google font Nuxt module to use 2 fonts in my website.\n\nI set it correctly but it does not work and downloads only 1 font, the one it finds first in the \"Families\" object and does not download all weights, but only the lowest.\n\n```\nbuildModules: [\n ['@nuxtjs/google-fonts',],\n ],\n\n googleFonts: {\n families: { \n Montserrat: {\n wght: [400, 600, 700],\n },\n 'Work+Sans': {\n wght: [400, 600, 700],\n },\n },\n subsets: ['latin'],\n display: 'swap',\n prefetch: false,\n preconnect: false,\n preload: false,\n download: true,\n base64: false,\n },\n```\n\nAnd this is what the folder `assets/css/fonts.css` looks like\n\n```\n/* cyrillic-ext */\n@font-face {\n font-family: 'Montserrat';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('~assets/fonts/Montserrat-400-cyrillic-ext1.woff2') format('woff2');\n unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;\n}\n/* cyrillic */\n@font-face {\n font-family: 'Montserrat';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('~assets/fonts/Montserrat-400-cyrillic2.woff2') format('woff2');\n unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;\n}\n/* vietnamese */\n@font-face {\n font-family: 'Montserrat';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('~assets/fonts/Montserrat-400-vietnamese3.woff2') format('woff2');\n unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;\n}\n/* latin-ext */\n@font-face {\n font-family: 'Montserrat';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('~assets/fonts/Montserrat-400-latin-ext4.woff2') format('woff2');\n unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;\n}\n/* latin */\n@font-face {\n font-family: 'Montserrat';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('~assets/fonts/Montserrat-400-latin5.woff2') format('woff2');\n unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;\n}\n```\n\nPS: more info on @font-face.\n\n========================================\n\nCode:\n```js\nbuildModules: [\n ['@nuxtjs/google-fonts',],\n ],\n\n googleFonts: {\n families: { \n Montserrat: {\n wght: [400, 600, 700],\n },\n 'Work+Sans': {\n wght: [400, 600, 700],\n },\n },\n subsets: ['latin'],\n display: 'swap',\n prefetch: false,\n preconnect: false,\n preload: false,\n download: true,\n base64: false,\n },\n```\n\n```css\n/* cyrillic-ext */\n@font-face {\n font-family: 'Montserrat';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('~assets/fonts/Montserrat-400-cyrillic-ext1.woff2') format('woff2');\n unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;\n}\n/* cyrillic */\n@font-face {\n font-family: 'Montserrat';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('~assets/fonts/Montserrat-400-cyrillic2.woff2') format('woff2');\n unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;\n}\n/* vietnamese */\n@font-face {\n font-family: 'Montserrat';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('~assets/fonts/Montserrat-400-vietnamese3.woff2') format('woff2');\n unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;\n}\n/* latin-ext */\n@font-face {\n font-family: 'Montserrat';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('~assets/fonts/Montserrat-400-latin-ext4.woff2') format('woff2');\n unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;\n}\n/* latin */\n@font-face {\n font-family: 'Montserrat';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('~assets/fonts/Montserrat-400-latin5.woff2') format('woff2');\n unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;\n}\n```\n\n```text\nassets/css/fonts.css\n```\n\n```json\n\"@nuxtjs/google-fonts\": \"^3.0.0-1\",\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- Regarding my previous answer on that subject, I'm not sure that you even need the `googleFonts` key before `families` here. At least, this is the main difference with my answer + it seems quite unnecessary since we're already using \"Google\" fonts module here.\n- @kissu nothing change... It doesn't work.\n- Got a public github repo? Or a simple minimal reproducible example? Pretty sure it does work.\n- @kissu whimsical-kheer-e12fd4.netlify.app this is the live preview of the site. The nuxt.config.js is up on the post. I did the npm add module... I don't know why it doesn't work\n- The result as a hosted app will not help us debug that unfortunately.\n- github.com/Dimi2000/Adapto this is the repo @kissu\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:07.906Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":182,"estimatedTokens":1317}}969{"id":"stack-74810422","source":"stackoverflow","questionId":74810422,"title":"What is the proper way to query with NuxtApollo in Nuxt3","tags":["nuxt.js","vuejs3","vue-composition-api","nuxt3.js","vue-apollo"],"text":"Title: What is the proper way to query with NuxtApollo in Nuxt3\nTags: nuxt.js, vuejs3, vue-composition-api, nuxt3.js, vue-apollo\nSource: Stack Overflow\n\nQuestion:\nI have been using Nuxt2 and NuxtApollo for several years, but now I am trying to start a new project in Nuxt3 and seem to have some trouble adjusting to the new logic.\n\nI have a minimal Nuxt3 installation with just the latest NuxtApollo package installed, as instructed in the documentation (https://apollo.nuxtjs.org/getting-started/quick-start). The @next version installed currently is 5.0.0-alpha.5.\n\nUsing the composables (https://apollo.nuxtjs.org/getting-started/composables) of NuxtApollo, I have no trouble with useAsyncQuery nor useLazyAsyncQuery.\n\nThings start go south when I try fetch with the useQuery composable, which is recommended as the main way of querying:\n\n**useQuery:**\nThis is the primary method of querying your GraphQL server, unlike useAsyncQuery which is best used for initially fetching data in SSR applications, useQuery can comfortably be used in any scenario.\n\nThe useQuery composable does not return a promise. In my -probably incorrect- approach, this introduces the problem of not knowing when the query has returned without using a watcher.\n\nFor example this one returns undefined:\n\n```\nconst myVal = ref()\n\n const testQuery = () => {\n const { result } = useQuery(query, variables)\n myVal.value = result.value\n console.log(result.value) // undefined\n }\n```\n\nUsing a watcher works but seems terribly wrong for several reasons:\n\n```\nconst testQuery = () => {\n const { result } = useQuery(query, variables)\n watch(result, () => {\n if(result.value){\n myVal.value = result.value\n console.log(result.value) // valid value\n }\n })\n }\n```\n\nThe closest I have got to a proper usage is moving the query to setup and enabling it later:\n\n```\nconst queryEnabled = ref(false)\n const { result } = useQuery(query, null ,{enabled: queryEnabled})\n\n const test = () => {\n queryEnabled.value = true\n }\n```\n\nBut again, if I needed to process or assign the returned value to a variable of my choice, I would need to utilize a watcher.\n\nI suppose none of these problems would exist if the useQuery composable returned a promise that we could await.\n\nI would much appreciate it if you could point me in the right direction as I have a very strong feeling that I'm missing something fundamental here.\n\n========================================\n\nCode:\n```text\nconst myVal = ref()\n\n const testQuery = () => {\n const { result } = useQuery(query, variables)\n myVal.value = result.value\n console.log(result.value) // undefined\n }\n```\n\n```text\nconst testQuery = () => {\n const { result } = useQuery(query, variables)\n watch(result, () => {\n if(result.value){\n myVal.value = result.value\n console.log(result.value) // valid value\n }\n })\n }\n```\n\n```text\nconst queryEnabled = ref(false)\n const { result } = useQuery(query, null ,{enabled: queryEnabled})\n\n const test = () => {\n queryEnabled.value = true\n }\n```\n\n```js\n/**\n * `myVal` - it's your ref, it's value will be undefined first,\n * after query you will get a result there.\n */\nconst { result: myVal } = useQuery(query, variables)\n```\n\n```js\nconst myVal = ref()\n\nconst { onResult, onError } = useQuery(query, variables);\n\nonResult((result) => (myVal.value = result.data));\nonError((err) => (myVal.value = err));\n```\n\n```js\nconst myVal = ref()\n\n// Async function\nconst test = async () => {\n const { data } = await useAsyncQuery(query, { ...variables })\n \n myVal.value = data\n}\n\ntest()\n```\n\n```text\nresult.value\n```\n\n```text\n<script setup>\n```\n\n```text\nonResult\n```\n\n```text\n<script setup>\n```\n\n```text\n<script setup>\n```\n\n========================================\n\nComments:\n- Hi, George what happened? I am also trying to do the same. Please consider sharing the solution. And I will do the same also.\n- Still on the look, will certainly post the answer and let you know when there's progress.\n- Question answered, nice and simple.\n- Yeah, I also solved the Login authentication as I have two working computers and didn't open this StackOverflow for 22 days in this one, thankyou you for giving your time.\n- Thank you, Aleksandr. I did find out about the onResult handler earlier, but the first approach is quite simple and elegant as well.","metadata":{"transformedAt":"2026-08-18T18:33:07.906Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":153,"estimatedTokens":1097}}970{"id":"stack-75298254","source":"stackoverflow","questionId":75298254,"title":"Why is scroll-margin not working in Nuxt?","tags":["css","nuxt.js"],"text":"Title: Why is scroll-margin not working in Nuxt?\nTags: css, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am working in a Nuxt app and using CSS based smooth scrolling to anchor links. The smooth scroll itself works but the `scroll-margin` property is achieving nothing... it is seemingly completely ignored. The exact same code works fine outside of the Nuxt app so I wonder whether it is something to do with Nuxt.\n\nSlimmed down version of the code is as follows and I have also created a (working) non-Nuxt codepen to show the code in action outside of Nuxt.\n\nFor the sake of clarity, I want to use CSS only to achieve smooth scrolling with a scroll margin in Nuxt. I do not want to use JavaScript or built in Vue / Nuxt features. If I have to I will but, at the very least, I'd like to know why `scroll-margin` is not doing anything.\n\nHTML\n\n```\n\n Fixed header\n\n Click this link to scroll to a section further down the page and show the targeted state. Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem iste fuga quae fugit molestiae accusamus dolorum ea doloremque veritatis totam! Eum exercitationem nostrum nam doloribus, blanditiis quidem inventore perspiciatis ullam?\n \n Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum architecto explicabo accusamus! Ab fuga fugiat hic recusandae, quo, dignissimos tempore velit aliquam facere, accusamus explicabo pariatur at enim modi doloremque.\n\n Lorem ipsum dolor sit amet adipisicing elit. Quidem iste fuga quae fugit molestiae accusamus dolorum ea doloremque veritatis totam! Eum exercitationem nostrum nam doloribus, blanditiis quidem inventore perspiciatis ullam?\n\n **Check out the space between this block and the header 👆 The block is clear of the header thanks to the `scroll-margin` property. The block was blue before you clicked the link and this text wasn't here either.** Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum architecto explicabo accusamus! Ab fuga fugiat hic recusandae, quo, dignissimos tempore velit aliquam facere, accusamus explicabo pariatur at enim modi doloremque.\n\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum architecto explicabo accusamus! Ab fuga fugiat hic recusandae, quo, dignissimos tempore velit aliquam facere, accusamus explicabo pariatur at enim modi doloremque.\n\n Lorem ipsum dolor sit amet adipisicing elit. Quidem iste fuga quae fugit molestiae accusamus dolorum ea doloremque veritatis totam! Eum exercitationem nostrum nam doloribus, blanditiis quidem inventore perspiciatis ullam?\n\n```\n\nSCSS\n\n```\n* {\n box-sizing: border-box;\n font-family: helvetica;\n margin-inline: 0;\n line-height:1.5;\n}\n\nhtml {\n scroll-behavior: smooth;\n}\n\nheader {\n position: fixed;\n display: grid;\n place-content: center;\n inset-block-start: 0;\n inset-inline-start: 0;\n width: 100%;\n height: 3rem;\n background: #ed6a5a;\n font-size: 1.5rem;\n}\n\nsection {\n background: #9bc1bc; \n padding: 50px 30px;\n \n &:nth-child(2n) {\n background: #f4f1bb;\n }\n \n &:first-of-type {\n padding-block-start: 20vh;\n }\n}\n\nstrong {\n font-size: 1.2em;\n}\n\ncode {\n font-family: monospace;\n}\n\n:target {\n scroll-margin: 5rem;\n background: #F2D7EE;\n \n .show-on-target {\n display: block;\n margin-block-end: 20px;\n }\n}\n\n.show-on-target {\n display: none;\n}\n```\n\n**What I tried:**\n\nUsing the code above to create a CSS-only smooth-scroll including a scroll-margin. I also tried tweaking the code above to use `section`, `[id]`, `section[id]` and `#myAnchor` in place of `:target` but to no avail.\n\n**What I was expecting:**\n\nPage to scroll smoothly to the anchor leaving a 5 rem margin above it.\n\n**What actually happens:**\n\nPage scrolls smoothly to the anchor but with no margin above it\n\n========================================\n\nCode:\n```text\n<main>\n <header>Fixed header</header>\n\n <section><a href=\"#scroll-section\">Click this link to scroll to a section further down the page and show the targeted state</a>. Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem iste fuga quae fugit molestiae accusamus dolorum ea doloremque veritatis totam! Eum exercitationem nostrum nam doloribus, blanditiis quidem inventore perspiciatis ullam?</section>\n \n <section>Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum architecto explicabo accusamus! Ab fuga fugiat hic recusandae, quo, dignissimos tempore velit aliquam facere, accusamus explicabo pariatur at enim modi doloremque.</section>\n\n <section>Lorem ipsum dolor sit amet adipisicing elit. Quidem iste fuga quae fugit molestiae accusamus dolorum ea doloremque veritatis totam! Eum exercitationem nostrum nam doloribus, blanditiis quidem inventore perspiciatis ullam?</section>\n\n <section id=\"scroll-section\"> <strong class=\"show-on-target\">Check out the space between this block and the header 👆 The block is clear of the header thanks to the <code>scroll-margin</code> property. The block was blue before you clicked the link and this text wasn't here either.</strong> Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum architecto explicabo accusamus! Ab fuga fugiat hic recusandae, quo, dignissimos tempore velit aliquam facere, accusamus explicabo pariatur at enim modi doloremque.</section>\n\n <section>Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum architecto explicabo accusamus! Ab fuga fugiat hic recusandae, quo, dignissimos tempore velit aliquam facere, accusamus explicabo pariatur at enim modi doloremque.</section>\n\n <section>Lorem ipsum dolor sit amet adipisicing elit. Quidem iste fuga quae fugit molestiae accusamus dolorum ea doloremque veritatis totam! Eum exercitationem nostrum nam doloribus, blanditiis quidem inventore perspiciatis ullam?</section>\n</main>\n```\n\n```text\n* {\n box-sizing: border-box;\n font-family: helvetica;\n margin-inline: 0;\n line-height:1.5;\n}\n\nhtml {\n scroll-behavior: smooth;\n}\n\nheader {\n position: fixed;\n display: grid;\n place-content: center;\n inset-block-start: 0;\n inset-inline-start: 0;\n width: 100%;\n height: 3rem;\n background: #ed6a5a;\n font-size: 1.5rem;\n}\n\nsection {\n background: #9bc1bc; \n padding: 50px 30px;\n \n &:nth-child(2n) {\n background: #f4f1bb;\n }\n \n &:first-of-type {\n padding-block-start: 20vh;\n }\n}\n\nstrong {\n font-size: 1.2em;\n}\n\ncode {\n font-family: monospace;\n}\n\n:target {\n scroll-margin: 5rem;\n background: #F2D7EE;\n \n .show-on-target {\n display: block;\n margin-block-end: 20px;\n }\n}\n\n.show-on-target {\n display: none;\n}\n```\n\n```text\nscroll-margin\n```\n\n```text\nscroll-margin\n```\n\n```text\nsection\n```\n\n```text\n[id]\n```\n\n```text\nsection[id]\n```\n\n```text\n#myAnchor\n```\n\n```text\n:target\n```\n\n```text\nimport type { RouterConfig } from \"@nuxt/schema\";\n\nexport default <RouterConfig>{\n scrollBehavior(to, from, savedPosition) {\n if (to && to.hash) {\n return {\n el: to.hash,\n top: 81, // Add here the padding or margin top that you want\n behavior: \"smooth\",\n };\n } else {\n return { top: 0, left: 0, behavior: \"smooth\" };\n }\n },\n};\n```\n\n```text\n/app/router.options.ts\n```\n\n========================================\n\nComments:\n- I've answered plenty of those questions before. Please give some of them a read: stackoverflow.com/search?q=user%3A8816585+scroll Yours will probably have a solution in there (depending on your Nuxt version, other packages, syntax etc...).\n- thanks, @kissu , but none of those seem to be pure css solutions or explain why scroll-margin does not work. I found various related questions / answers (probably including yours) but nothing I've found answers these specific questions.\n- There are some pure CSS solutions that are solving exactly your use-case. And there can be several solutions for that one, hence why I recommend one of my already-posted answers.\n- I've been through all of those posts looking for an answer as to why scroll-margin is not working inside Nuxt when it works elsewhere. I see no explanation. If you know the answer please post it as an answer here.\n- thanks. you probably already know but as others reading this may not... scroll-margin not working was a bug that was resolved as part of the v2.16 update. v.2.16 had breaking changes in it though so @FahDev's solution is perfect for projects using < v.2.16","metadata":{"transformedAt":"2026-08-18T18:33:07.907Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":244,"estimatedTokens":2078}}971{"id":"stack-74702522","source":"stackoverflow","questionId":74702522,"title":"Swiper Vue component event handlers not working in Nuxt","tags":["vue.js","nuxt.js","swiper.js","nuxt3.js"],"text":"Title: Swiper Vue component event handlers not working in Nuxt\nTags: vue.js, nuxt.js, swiper.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am using **Swiper.js** in my **Nuxt** project. I am using the default code the docs provided. I am trying to log the swiper instance but it's not working.\nIn the console, it gives me the following error\n\nhttps://i.sstatic.net/sOBcR.png\n\nHere is my template code and `onSwiper` function\n\n```\n\n \n\n### Slider\n\n \n\n \n \n \n \n\n \n Next Slide\n\n \n\nimport {\n Swiper,\n SwiperSlide,\n useSwiper\n} from 'swiper/vue';\nimport SwiperCore, {\n Navigation\n} from 'swiper';\nimport 'swiper/css';\nimport \"swiper/css/navigation\";\n\nSwiperCore.use([Navigation]);\n\nexport default {\n name: \"Slider\",\n components: {\n Swiper,\n SwiperSlide,\n },\n setup() {\n const onSwiper = (swiper) => {\n console.log(swiper);\n };\n },\n data() {\n return {\n images: [\n \"https://cdn.pixabay.com/photo/2015/12/12/15/24/amsterdam-1089646_1280.jpg\",\n \"https://cdn.pixabay.com/photo/2016/02/17/23/03/usa-1206240_1280.jpg\",\n \"https://cdn.pixabay.com/photo/2022/02/09/03/48/oriental-garden-lizard-7002565_960_720.jpg\",\n \"https://cdn.pixabay.com/photo/2016/12/04/19/30/berlin-cathedral-1882397_1280.jpg\",\n \"https://cdn.pixabay.com/photo/2015/12/12/15/24/amsterdam-1089646_1280.jpg\"\n ],\n \n\n };\n },\n \n\n};\n\n```\n\nPackage.json\n\n```\n{\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\",\n \"postinstall\": \"nuxt prepare\"\n },\n \"devDependencies\": {\n \"autoprefixer\": \"^10.4.13\",\n \"nuxt\": \"3.0.0\",\n \"postcss\": \"^8.4.19\",\n \"tailwindcss\": \"^3.2.4\"\n },\n \"dependencies\": {\n \"@nuxtjs/google-fonts\": \"^2.0.0\",\n \"@pinia/nuxt\": \"^0.4.6\",\n \"@tailwindcss/typography\": \"^0.5.8\",\n \"swiper\": \"^8.4.5\"\n }\n}\n```\n\n**Nuxt Config**\n\n```\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n css: [\"~/assets/css/tailwind.css\"],\n modules: [\"@pinia/nuxt\"],\n postcss: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n },\n});\n```\n\n========================================\n\nCode:\n```html\n<template>\n <h1>Slider</h1>\n <div class=\"container\">\n\n <swiper @swiper=\"onSwiper\" :navigation=\"true\" :slides-per-view=\"3\" :space-between=\"89\" :loop=\"true\"\n :loopFillGroupWithBlank=\"true\">\n <swiper-slide v-for=\"image in images\" :key=\"image\">\n <card :image=\"image\" />\n </swiper-slide>\n\n </swiper>\n <button @click=\"slideTo(4)\" class=\"bg-primary btn-primary\"> Next Slide</button>\n\n </div>\n</template>\n\n<script>\nimport {\n Swiper,\n SwiperSlide,\n useSwiper\n} from 'swiper/vue';\nimport SwiperCore, {\n Navigation\n} from 'swiper';\nimport 'swiper/css';\nimport \"swiper/css/navigation\";\n\nSwiperCore.use([Navigation]);\n\nexport default {\n name: \"Slider\",\n components: {\n Swiper,\n SwiperSlide,\n },\n setup() {\n const onSwiper = (swiper) => {\n console.log(swiper);\n };\n },\n data() {\n return {\n images: [\n \"https://cdn.pixabay.com/photo/2015/12/12/15/24/amsterdam-1089646_1280.jpg\",\n \"https://cdn.pixabay.com/photo/2016/02/17/23/03/usa-1206240_1280.jpg\",\n \"https://cdn.pixabay.com/photo/2022/02/09/03/48/oriental-garden-lizard-7002565_960_720.jpg\",\n \"https://cdn.pixabay.com/photo/2016/12/04/19/30/berlin-cathedral-1882397_1280.jpg\",\n \"https://cdn.pixabay.com/photo/2015/12/12/15/24/amsterdam-1089646_1280.jpg\"\n ],\n \n\n };\n },\n \n\n};\n</script>\n```\n\n```json\n{\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\",\n \"postinstall\": \"nuxt prepare\"\n },\n \"devDependencies\": {\n \"autoprefixer\": \"^10.4.13\",\n \"nuxt\": \"3.0.0\",\n \"postcss\": \"^8.4.19\",\n \"tailwindcss\": \"^3.2.4\"\n },\n \"dependencies\": {\n \"@nuxtjs/google-fonts\": \"^2.0.0\",\n \"@pinia/nuxt\": \"^0.4.6\",\n \"@tailwindcss/typography\": \"^0.5.8\",\n \"swiper\": \"^8.4.5\"\n }\n}\n```\n\n```js\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n css: [\"~/assets/css/tailwind.css\"],\n modules: [\"@pinia/nuxt\"],\n postcss: {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n },\n});\n```\n\n```text\nonSwiper\n```\n\n```js\nsetup() {\n const onSwiper = (swiper) => {\n console.log(swiper);\n }\n\n return {\n onSwiper\n }\n}\n```\n\n```text\nreturn\n```\n\n```text\nscript setup\n```\n\n========================================\n\nComments:\n- Please the whole SFC file and not a part of it since it looks like that is the issue. Also, can you confirm that you're using Nuxt3? Since it's the only version compatible with Swiper v8.\n- Updated the question with package.json and nuxt config file.","metadata":{"transformedAt":"2026-08-18T18:33:07.907Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":248,"estimatedTokens":1199}}972{"id":"stack-72506911","source":"stackoverflow","questionId":72506911,"title":"cache issue with updating old codes","tags":["vue.js","nuxt.js"],"text":"Title: cache issue with updating old codes\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm having extremely annoying and deal breaker issues with all the js caching that nuxt js does, all the codes get executed as they were cached before and not being implemented on website unless the user clears the browser cache for the website manually!\n\nI searched for solutions to delete caches automatically and didn't found such solution.\nnow I have recently upgraded my website and changed a `get` method axios command to `post` but whenever I or anyone else opens the website it gets the data via old get method and throwing errors unless you clear caches manually.\n\nI had same issues before when changing UI of website completely and it showing old codes when you enter website, like showing some content which are completely removed in new code but not disappering unless I clear caches.\n\nis there any solutions to get around these kind of problems?\n\n========================================\n\nCode:\n```text\nget\n```\n\n```text\npost\n```\n\n```text\n// update.js\n export default async (context) => {\n const workbox = await window.$workbox\n\n if (!workbox) {\n console.debug(\"Workbox couldn't be loaded.\")\n return\n }\n\n workbox.addEventListener('installed', (event) => {\n if (!event.isUpdate) {\n console.debug('The PWA is on the latest version.')\n return\n }\n\n console.debug('There is an update for the PWA, reloading...')\n window.location.reload()\n })\n }\n```\n\n```text\n// nuxt.config.js\n\n // ...\n\n plugins: [\n { src: '@/plugins/update.js', mode: 'client' },\n ],\n\n // ...\n```\n\n```text\nversion\n```\n\n```text\npackage.json\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.907Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":66,"estimatedTokens":431}}973{"id":"stack-72395317","source":"stackoverflow","questionId":72395317,"title":"Nuxt 3 use composable in middleware","tags":["nuxt.js","vue-router","vuejs3","middleware","nuxt3.js"],"text":"Title: Nuxt 3 use composable in middleware\nTags: nuxt.js, vue-router, vuejs3, middleware, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI want to guard a route by checking if the user is logged in, but:\n\n- I can't read the composable value,\n\n- I am unsure if my middleware got the right body.\n\nMy composable:\n\n```\n// composable/useAuth.js\nconst useAuth = () => {\n\n // user login, sign out, sign up logic\n\n const isLoggedIn = () => {\n return !!user.value\n }\n\n return {\n isLoggedIn\n }\n}\n\nexport default useAuth\n```\n\nMy middleware:\n\n```\n// middleware/check-admin.js\nexport default defineNuxtRouteMiddleware((to, from) => {\n const { isLoggedIn } = useAuth()\n\n console.log(isLoggedIn); // My console logs a method body. But I expected a falsy or truthy value:\nhttps://i.sstatic.net/vNmMo.png\n\n### Problems:\n\n- How can I read a boolean value from my composables to pass the test inside the middleware?\n\n- It is okay to use `navigateTo` to abort the routing, if the user got no credentials? The docs says, I can use `abortNavigation()`\n\n========================================\n\nCode:\n```js\n// composable/useAuth.js\nconst useAuth = () => {\n\n // user login, sign out, sign up logic\n\n const isLoggedIn = () => {\n return !!user.value\n }\n\n return {\n isLoggedIn\n }\n}\n\nexport default useAuth\n```\n\n```js\n// middleware/check-admin.js\nexport default defineNuxtRouteMiddleware((to, from) => {\n const { isLoggedIn } = useAuth()\n\n console.log(isLoggedIn); // <- Screenshot\n\n if (isLoggedIn) {\n return navigateTo(`/albums/${to.params.id}/edit`)\n } else {\n return navigateTo('/')\n }\n})\n```\n\n```text\nnavigateTo\n```\n\n```text\nabortNavigation()\n```\n\n```js\nexport default defineNuxtRouteMiddleware((to, from) => {\n const { isLoggedIn } = useAuth()\n\n console.log(isLoggedIn()); // <- Screenshot\n // `from.name === login` will trigger rediraction for example if user want to login but he is already logged in.\n // form.name will be necesery if you use suffix `.global` in file name.\n if (isLoggedIn() && to.params.id && !from.params.id && from.name === `login`) {\n return navigateTo(`/albums/${to.params.id}/edit`)\n }\n if (!isLoggedIn() && form.params.id) {\n return abortNavigation()\n }\n})\n```\n\n```html\n<script setup>\ndefinePageMeta({\n middleware: [\"auth\"]\n // or middleware: 'auth'\n})\n</script>\n```\n\n```text\n()\n```\n\n```text\nto\n```\n\n```text\n.global\n```\n\n========================================\n\nComments:\n- Thanks, you're right with the init. But I got this warning: `[Vue Router warn]: Detected an infinite redirection in a navigation guard when going from \"/albums/4\" to \"/albums/4/edit\"`\n- This is why you need to use `(to, from)` values in `if` statements.\n- If he is already in `/albums/${to.params.id}/edit` navigation will navigate user again because it's triggering every time user navigate somewhere.\n- You have functions to abort navigation, use them if user is already in a route where he should be.\n- @wittgenstein I don't know what you want to achieve, but code should look like mine.\n- It gets me closer. Now if I am unauthorized, I am getting an Error `500 Route navigation aborted: /albums/74/edit`. But that's another topic. First I wanted to get a feeling how I use a composable in a middleware. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:07.907Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":137,"estimatedTokens":819}}974{"id":"stack-72167502","source":"stackoverflow","questionId":72167502,"title":"AsyncData not being called in nuxt","tags":["javascript","vue.js","nuxt.js","asyncdata"],"text":"Title: AsyncData not being called in nuxt\nTags: javascript, vue.js, nuxt.js, asyncdata\nSource: Stack Overflow\n\nQuestion:\nI want to set category data at `asyncData()` hook. But `MainHeader` Page Component never calls `asyncData` even if it is placed in a page. Can you explain why `MainHeader` Page Component does not call `asyncData`?\n\n`MainHeader` is placed inside \"com\" folder which is placed on pages (`/pages/com/MainHeader`)\n\n```\n\n \n \n \n\nimport HeaderNav from '~/components/com/nav/HeaderNav.vue';\nimport CateApi from \"~/util/api/category/cate-api\";\n\nexport default {\n components: {HeaderNav},\n\n async asyncData(){\n const cateList = await CateApi.getDispCateList();\n return{\n cateList,\n }\n },\n\n data() {\n return {\n cateList: [],\n }\n },\n}\n\n```\n\ndefault\n(`/layouts/default`)\n\n```\n\n \n \n\nimport MainHeader from \"~/pages/com/MainHeader.vue\"\nexport default {\n components :{\n MainHeader,\n },\n name: \"defaultLayout\"\n}\n\n```\n\n========================================\n\nCode:\n```html\n<template>\n <div>\n <header-nav :cateList=\"cateList\"/>\n </div>\n</template>\n\n<script>\nimport HeaderNav from '~/components/com/nav/HeaderNav.vue';\nimport CateApi from \"~/util/api/category/cate-api\";\n\nexport default {\n components: {HeaderNav},\n\n async asyncData(){\n const cateList = await CateApi.getDispCateList();\n return{\n cateList,\n }\n },\n\n data() {\n return {\n cateList: [],\n }\n },\n}\n</script>\n```\n\n```html\n<template>\n<div>\n <main-header/>\n <Nuxt/>\n</div>\n</template>\n\n<script>\nimport MainHeader from \"~/pages/com/MainHeader.vue\"\nexport default {\n components :{\n MainHeader,\n },\n name: \"defaultLayout\"\n}\n</script>\n```\n\n```text\nasyncData()\n```\n\n```text\nMainHeader\n```\n\n```text\nasyncData\n```\n\n```text\nMainHeader\n```\n\n```text\nasyncData\n```\n\n```text\nMainHeader\n```\n\n```text\n/pages/com/MainHeader\n```\n\n```text\n/layouts/default\n```\n\n```html\n<template>\n <div>\n <p> main header page</p>\n <header-nav :cate-list=\"cateList\" />\n </div>\n</template>\n\n<script>\nimport HeaderNav from '~/components/com/nav/HeaderNav.vue';\n\nexport default {\n components: { HeaderNav },\n\n async asyncData() {\n console.log(\"check your server if accessing this page directly, otherwise you'll see this one in your browser if client-side navigation\")\n const response = await fetch('https://jsonplaceholder.typicode.com/todos')\n const cateList = await response.json()\n\n return { cateList }\n },\n}\n</script>\n```\n\n```text\n/com/test-page\n```\n\n```text\nconsole.log\n```\n\n```text\nmy-cool-page\n```\n\n```text\nmyCoolPage\n```\n\n```text\nasyncData\n```\n\n```text\n/pages/com/main-header.vue\n```\n\n========================================\n\nComments:\n- Do you have access to the page? Can you add a simple piece of text to the `template`? Also, what if you try a `console.log` in a `mounted()`? No errors in the console? Nothing weird in the Vue devtools?\n- Also, you don't need `data`, `asyncData` will create that one via the `return`.\n- @kissu Thanks to reply! I've tried to console.log in asyncData, created, fetch, mounted. There are no errors in the console. Nothing weired in the devtools. At first request, server only calls created, fetch but not calls asyncData. I remove data but still asyncData not being called","metadata":{"transformedAt":"2026-08-18T18:33:07.907Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":194,"estimatedTokens":802}}975{"id":"stack-73062925","source":"stackoverflow","questionId":73062925,"title":"How to send JSON data from Nuxt Axios to a FastAPI backend through a POST request?","tags":["vue.js","axios","nuxt.js","fastapi"],"text":"Title: How to send JSON data from Nuxt Axios to a FastAPI backend through a POST request?\nTags: vue.js, axios, nuxt.js, fastapi\nSource: Stack Overflow\n\nQuestion:\nI'm trying to send user data from Nuxt.js using Axios via a `POST` request. The data is already provided via a Javascript cdn function that returns an object with `user` parameters, so I wouldn't want to use a `form` since I'm forwarding the `user` data I received as `JSON`.\n\nI wanted to know if the method I'm using is the right way of doing this? I need to send the `user` information in order to send a query in the backend to an external API (requiring a token from both the front and the back end, e.g., user token and app token).\n\nHere is my current iteration:\n\n```\n\nexport default {\n head (){\n return {\n __dangerouslyDisableSanitizers: ['script'],\n script: [\n {\n hid: 'platform-api',\n src: \"https://cdn-sample.app.com/api\",\n type: 'text/javascript',\n defer: true\n },\n ]\n }\n },\n computed: {\n // Change user token parameter according to docs\n // Add Neccessary parameters\n auth_token: {\n get(){\n let userdata = getPlatformContext();\n this.$store.state.user.auth_token = userdata.auth_token;\n return this.$store.state.user.auth_token;\n },\n set(value){\n this.$store.commit(\"item/storeAuthToken\", value)\n }\n },\n // Additional parameters omitted as they extract each parameter in the same way\n // as above.\n methods: {\n // I tried to test it by sending just the user token by clicking a button\n async sendUserToken(auth_token) {\n await this.$axios.post(this.$config.baseURL, user.auth_token);\n },\n // Then i wanted instead to try and send the whole json dict of user data to \n // backend and sort the data over in fastapi according to what i need.\n async sendUserData(user) {\n await this.$axios.post(this.$config.baseURL, user);\n }\n \n },\n \n}\n\n```\n\nSo, if I wanted to send the user data as a `POST` request in `JSON` format, not as a `form`, what would be the best way to do this?\n\n========================================\n\nCode:\n```js\n<script>\nexport default {\n head (){\n return {\n __dangerouslyDisableSanitizers: ['script'],\n script: [\n {\n hid: 'platform-api',\n src: \"https://cdn-sample.app.com/api\",\n type: 'text/javascript',\n defer: true\n },\n ]\n }\n },\n computed: {\n // Change user token parameter according to docs\n // Add Neccessary parameters\n auth_token: {\n get(){\n let userdata = getPlatformContext();\n this.$store.state.user.auth_token = userdata.auth_token;\n return this.$store.state.user.auth_token;\n },\n set(value){\n this.$store.commit(\"item/storeAuthToken\", value)\n }\n },\n // Additional parameters omitted as they extract each parameter in the same way\n // as above.\n methods: {\n // I tried to test it by sending just the user token by clicking a button\n async sendUserToken(auth_token) {\n await this.$axios.post(this.$config.baseURL, user.auth_token);\n },\n // Then i wanted instead to try and send the whole json dict of user data to \n // backend and sort the data over in fastapi according to what i need.\n async sendUserData(user) {\n await this.$axios.post(this.$config.baseURL, user);\n }\n \n },\n \n}\n\n</script>\n```\n\n```text\nPOST\n```\n\n```text\nuser\n```\n\n```text\nform\n```\n\n```text\nuser\n```\n\n```text\nJSON\n```\n\n```text\nuser\n```\n\n```text\nPOST\n```\n\n```text\nJSON\n```\n\n```text\nform\n```\n\n```py\nfrom fastapi import FastAPI, Request, Body\nfrom fastapi.templating import Jinja2Templates\nfrom pydantic import BaseModel\n\napp = FastAPI()\ntemplates = Jinja2Templates(directory=\"templates\")\n\nclass User(BaseModel):\n username: str\n address: str\n \n@app.get(\"/\")\ndef main(request: Request):\n return templates.TemplateResponse(\"index.html\", {\"request\": request})\n \n@app.post(\"/submit\")\ndef main(user: User):\n return user\n```\n\n```html\n<script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js\"></script>\n<script type=\"text/javascript\">\nfunction uploadJSONdata() {\n axios({\n method: 'post',\n url: '/submit',\n data: JSON.stringify({\"username\": \"some name\", \"address\": \"some address\"}),\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n },\n })\n .then(response => {\n console.log(response);\n document.getElementById(\"p1\").innerHTML = JSON.stringify(response.data);\n })\n .catch(error => {\n console.error(error);\n });\n}\n</script>\n<p id=\"p1\"></p>\n<input type=\"button\" value=\"submit\" onclick=\"uploadJSONdata()\">\n```\n\n```js\nthis.$axios.post('/submit', {\n username: 'some name',\n address: 'some address'\n })\n .then(function (response) {\n console.log(response);\n })\n .catch(function (error) {\n console.log(error);\n });\n```\n\n```text\nJSON\n```\n\n```text\nJSON\n```\n\n```text\nJSON.stringify()\n```\n\n```text\nBody\n```\n\n```text\nBody\n```\n\n```text\nBody\n```\n\n========================================\n\nComments:\n- Thank you, this helped me figure out how to implement this. I've decided to store state of a function with the required info and then post the user info to backend.","metadata":{"transformedAt":"2026-08-18T18:33:07.907Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":237,"estimatedTokens":1367}}976{"id":"stack-74051868","source":"stackoverflow","questionId":74051868,"title":"How do I fix a \"Vue packages version mismatch\" error on Vue js 3","tags":["javascript","vue.js","nuxt.js","vuejs3"],"text":"Title: How do I fix a \"Vue packages version mismatch\" error on Vue js 3\nTags: javascript, vue.js, nuxt.js, vuejs3\nSource: Stack Overflow\n\nQuestion:\nWhen I run npm run dev on my nuxt js, I get the following error:\n\n```\nFATAL 14:16:02 \n\nVue packages version mismatch:\n\n- vue@3.2.40\n- vue-server-renderer@2.7.12\n\nThis may cause things to work incorrectly. Make sure to use the same version for both.\n\n Vue packages version mismatch:\n\n - vue@3.2.40\n - vue-server-renderer@2.7.12\n\n This may cause things to work incorrectly. Make sure to use the same version for both.\n\n at Object. (node_modules\\vue-server-renderer\\index.js:8:9)\n at Module._compile (node:internal/modules/cjs/loader:1126:14)\n at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)\n at Module.load (node:internal/modules/cjs/loader:1004:32)\n at Function.Module._load (node:internal/modules/cjs/loader:839:12)\n at Module.require (node:internal/modules/cjs/loader:1028:19)\n at require (node:internal/modules/cjs/helpers:102:18)\n at Object. (node_modules\\@nuxt\\vue-renderer\\dist\\vue-renderer.js:20:27)\n at Module._compile (node:internal/modules/cjs/loader:1126:14)\n at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)\n```\n\ni try to resolve it by delete node modules and npm install, but it seems still not resolve my problem yet,any help on that, its been a while since i try to google it but still not giving me any answer on my problem,this happened when i install github co pilot\nhere is my package.json looks like\n\n```\n{\n \"name\": \"cashier\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/i18n\": \"^7.2.2\",\n \"core-js\": \"^3.15.1\",\n \"dotenv\": \"^16.0.2\",\n \"jwt-decode\": \"^3.1.2\",\n \"nuxt\": \"^2.13.3\",\n \"vue\": \"^3.2.40\",\n \"vue-google-charts\": \"^1.1.0\",\n \"vue-server-renderer\": \"^2.7.12\",\n \"vuetify\": \"^2.5.5\",\n \"vuex-persistedstate\": \"^4.1.0\"\n },\n \"devDependencies\": {\n \"@nuxtjs/vuetify\": \"^1.12.1\",\n \"eslint-config-prettier\": \"^8.3.0\",\n \"prettier\": \"^2.3.2\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\nFATAL 14:16:02 \n\nVue packages version mismatch:\n\n- vue@3.2.40\n- vue-server-renderer@2.7.12\n\nThis may cause things to work incorrectly. Make sure to use the same version for both.\n\n\n\n Vue packages version mismatch:\n\n - vue@3.2.40\n - vue-server-renderer@2.7.12\n\n This may cause things to work incorrectly. Make sure to use the same version for both.\n\n at Object.<anonymous> (node_modules\\vue-server-renderer\\index.js:8:9)\n at Module._compile (node:internal/modules/cjs/loader:1126:14)\n at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)\n at Module.load (node:internal/modules/cjs/loader:1004:32)\n at Function.Module._load (node:internal/modules/cjs/loader:839:12)\n at Module.require (node:internal/modules/cjs/loader:1028:19)\n at require (node:internal/modules/cjs/helpers:102:18)\n at Object.<anonymous> (node_modules\\@nuxt\\vue-renderer\\dist\\vue-renderer.js:20:27)\n at Module._compile (node:internal/modules/cjs/loader:1126:14)\n at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)\n```\n\n```json\n{\n \"name\": \"cashier\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/i18n\": \"^7.2.2\",\n \"core-js\": \"^3.15.1\",\n \"dotenv\": \"^16.0.2\",\n \"jwt-decode\": \"^3.1.2\",\n \"nuxt\": \"^2.13.3\",\n \"vue\": \"^3.2.40\",\n \"vue-google-charts\": \"^1.1.0\",\n \"vue-server-renderer\": \"^2.7.12\",\n \"vuetify\": \"^2.5.5\",\n \"vuex-persistedstate\": \"^4.1.0\"\n },\n \"devDependencies\": {\n \"@nuxtjs/vuetify\": \"^1.12.1\",\n \"eslint-config-prettier\": \"^8.3.0\",\n \"prettier\": \"^2.3.2\"\n }\n}\n```\n\n```text\npackage.json\n```\n\n```text\nvue-server-renderer\n```\n\n```text\neslint-config-prettier\n```\n\n========================================\n\nComments:\n- you need to install `@vue/server-renderer` instead of `vue-server-renderer` ... please note however that `vuetify 2.x` is NOT compatible with vue3 - so you'll need to address that too\n- thanks a lot, but the most safest way for me just rollback to last version from github, i cannot resolve it as it getting more complicated after i remove some of the dependencies, but thanks a lot for ur answer, helping get through new project later on @kissu\n- @JansenStanlie yeah depends on what you already have as of right now. You may need to remove a few things out.","metadata":{"transformedAt":"2026-08-18T18:33:07.907Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":155,"estimatedTokens":1194}}977{"id":"stack-73656407","source":"stackoverflow","questionId":73656407,"title":"useFetch in Nuxt3 keeping cached data","tags":["vue.js","nuxt.js","nuxt3.js"],"text":"Title: useFetch in Nuxt3 keeping cached data\nTags: vue.js, nuxt.js, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI am facing the following issue with nuxt3.\n\n- the dynamic page `[slug].vue` loads the initial slug's data correctly\n\n- when I move away from the page and come back, the new data is not loaded, instead it still shows the old data.\n\n- If I refresh the said page with old data, it works ok.\n\nThis seems to be happening because the new slug's api call was never made.\n\nMy `[slug.vue]` file looks like:\n\n```\n\nimport { ref } from 'vue';\nconst route = useRoute();\n\nconst slug = ref(String(route.params.slug));\nconsole.log(slug.value);\nconst apicall = `https://swapi.dev/api/people/${slug.value}`;\nconst { data: article } = await useFetch(\n `https://swapi.dev/api/people/${slug.value}`\n);\n\n \n Back to Home\n \n {{ `https://swapi.dev/api/people/${slug}` }}\n {{ route.params.slug }}\n {{ article }}\n \n \n\n```\n\nThe entire setup can be seen on stackblitz at: https://stackblitz.com/edit/nuxt-starter-mkgfrw?file=pages%2F[slug].vue,pages%2Findex.vue\n\n========================================\n\nTop Answer:\nYour stackblitz did not work and gave me a 404 page not found '/'.\n\nI think what you should try to do is using router-view component\nand import {useRoute} from 'vue-router';\n\nSo useRoute updates the router-view and you can acces params, thats what solved it for me when i encountered the problem.\n\ngood luck\n\n========================================\n\nCode:\n```text\n<script setup lang=\"ts\">\nimport { ref } from 'vue';\nconst route = useRoute();\n\nconst slug = ref(String(route.params.slug));\nconsole.log(slug.value);\nconst apicall = `https://swapi.dev/api/people/${slug.value}`;\nconst { data: article } = await useFetch(\n `https://swapi.dev/api/people/${slug.value}`\n);\n</script>\n<template>\n <div>\n <NuxtLink to=\"/\">Back to Home</NuxtLink>\n <pre>\n {{ `https://swapi.dev/api/people/${slug}` }}\n {{ route.params.slug }}\n {{ article }}\n </pre>\n </div>\n</template>\n```\n\n```text\n[slug].vue\n```\n\n```text\n[slug.vue]\n```\n\n```text\nconst { data: article, refresh } = await useFetch(\n `https://swapi.dev/api/people/${slug.value}`\n);\n\nwatchEffect(() => {\n refresh();\n});\n```\n\n```text\nconst route = useRoute().params\nconst slug = ref(route.slug)\n\nconst { data: blog } = await useAsyncData(`blog:${slug.value}`, () => queryContent('/blog').find())\n```\n\n```text\nblog:${slug.value}\n```\n\n```text\ninitialCache\n```\n\n```text\nkey: String(Math.random())\n```\n\n========================================\n\nComments:\n- Hm, there is maybe this `useFetch(() => 'https://swapi.dev/api/people/${slug.value}' )` or using a `refresh` option. Not sure about which one exactly. Check the API in the documentation to be sure!\n- I was just about to say thanks and improvements to the answer are more than welcome. Feel free to post as an answer if you'd like.\n- stackblitz link seems to be working OK.\n- Thanks. Do you maybe have an official reference as to why/when it was removed? Like a changelog or some nuxt team member announcing it?\n- There is a PR with comments github.com/nuxt/framework/pull/8885","metadata":{"transformedAt":"2026-08-18T18:33:07.907Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":126,"estimatedTokens":779}}978{"id":"stack-72095972","source":"stackoverflow","questionId":72095972,"title":"Page transition library similar to Flutter Hero for Vue?","tags":["vue.js","nuxt.js","css-animations"],"text":"Title: Page transition library similar to Flutter Hero for Vue?\nTags: vue.js, nuxt.js, css-animations\nSource: Stack Overflow\n\nQuestion:\nhttps://www.npmjs.com/package/vue-hero-transition\n\nhttps://www.npmjs.com/package/vue-hero\n\nThe Hero animation packages I found are the two listed above.\nBut I think this library is a little lacking in recognition.\n\nIs there a package with the appropriate number of star or npm downloads?","metadata":{"transformedAt":"2026-08-18T18:33:07.907Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":13,"estimatedTokens":106}}979{"id":"stack-70810476","source":"stackoverflow","questionId":70810476,"title":"Nuxt: How to create links in a loop using the data as the link reference","tags":["vue.js","nuxt.js"],"text":"Title: Nuxt: How to create links in a loop using the data as the link reference\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am reading a set of links from a data source (using $content) and would like to generate a list of HTML elements that will link to the respective page.\n\n```\n// test.yaml in content directory\nlinks:\n - id: a\n title: A\n - id: b\n title: B\n - id: p\n title: P\n```\n\nNow, I would like to loop through this data and generate a set of HTML links\n\n```\n\n \n \n {{link.title}}\n \n \n```\n\n```\n// script\n \n export default {\n async asyncData({ $content, params }) {\n const _links = await $content(\"test\").fetch();\n return _links;\n }\n };\n \n```\n\nFor each of the items I would like a link such as:\n\n- For id a, the link should be `/content/a`\n\n- For id b, the link should be `/content/b`\n\nAssume that the slug for the above links exist and the pages work as intended. Thanks\n\n========================================\n\nCode:\n```yaml\n// test.yaml in content directory\nlinks:\n - id: a\n title: A\n - id: b\n title: B\n - id: p\n title: P\n```\n\n```html\n<!-- page.vue in pages directory -->\n <template>\n <div v-for=\"link in this._links\" :key=\"link.id\">\n <NuxtLink to=\"/whatToPutHere\">{{link.title}}</NuxtLink>\n </div>\n </template>\n```\n\n```js\n// script\n <script>\n export default {\n async asyncData({ $content, params }) {\n const _links = await $content(\"test\").fetch();\n return _links;\n }\n };\n </script>\n```\n\n```text\n/content/a\n```\n\n```text\n/content/b\n```\n\n```js\n<NuxtLink :to=\"`/content/${link.id}`\">{{link.title}}</NuxtLink>\n```\n\n```text\nv-bind:tag\n```\n\n```text\n:tag\n```\n\n========================================\n\nComments:\n- I have used `{{link.title}}` and it seems to work. Just wondering if there is a NuxtLink way to achieve the same","metadata":{"transformedAt":"2026-08-18T18:33:07.907Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":108,"estimatedTokens":449}}980{"id":"stack-68940390","source":"stackoverflow","questionId":68940390,"title":"Redirect user based on their role via nuxt middleware","tags":["vue.js","nuxt.js","vue-router","middleware","nuxt-auth"],"text":"Title: Redirect user based on their role via nuxt middleware\nTags: vue.js, nuxt.js, vue-router, middleware, nuxt-auth\nSource: Stack Overflow\n\nQuestion:\n### i want to redirect user based on their role & other attributes via nuxt middleware.\n\n** Redirection happen but got stuck into navigation guard, and page automatically reload again and again (reload ~500 times in second).\n\n#here is my code\n\n`nuxt.config.js`\n\n```\nrouter: {\n middleware: ['role']\n},\n```\n\n`middleware/role.js`\n\n```\nexport default function ({ redirect }) {\n if (!window.localStorage.getItem('auth.token')) {\n return redirect('/auth/login')\n }\n}\n```\n\nthe screenshot of browser console\n\n========================================\n\nCode:\n```js\nrouter: {\n middleware: ['role']\n},\n```\n\n```js\nexport default function ({ redirect }) {\n if (!window.localStorage.getItem('auth.token')) {\n return redirect('/auth/login')\n }\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nmiddleware/role.js\n```\n\n```html\n<script>\nexport default {\n middleware({ app }) {\n if (somethingTrue) { // your condition here\n app.router.push('/')\n }\n },\n}\n</script>\n```\n\n```text\nrouter.push\n```\n\n========================================\n\nComments:\n- Btw, if you plan to work with `localStorage`, I do recommend this solution since `window` will not always be available (SSR context).\n- Thanks for your help. i tried with $router.push(/auth/login). But it says $router is undefined\n- Sir it is perfectly work, when i add this code to individual page and globally (by defining it in nuxt.config.js). But in some pages like login, register it also working there instead of make this middleware to false in those pages. // Login page: export default { role: false; } . How to make this middleware disabled for those specific page?\n- What is `role: false`? Also, do you mind creating a new question for this one? @SouravAdhikary\n- i have created a new question here is the link stackoverflow.com/q/68958010/16759400","metadata":{"transformedAt":"2026-08-18T18:33:07.907Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":80,"estimatedTokens":489}}981{"id":"stack-69852644","source":"stackoverflow","questionId":69852644,"title":"Nuxt & SassError: Undefined variable","tags":["sass","nuxt.js","node-sass","sass-loader"],"text":"Title: Nuxt & SassError: Undefined variable\nTags: sass, nuxt.js, node-sass, sass-loader\nSource: Stack Overflow\n\nQuestion:\nHei there, I cannot find the solution for my error.\n\nHere is the assets structure:\n\n```\n-| assets\n---| scss\n-----| _grid_variables.scss\n-----| ....\n-----| variables.scss\n```\n\nHere is the _grid_variables.scss file:\n\n```\n$mobile-grid: 577px;\n$tablet-grid: 768px;\n$desktop-grid: 1024px;\n```\n\nHere is the variables.scss file:\n\n```\n@import \"_colors_variables\";\n@import \"_grid_variables\";\n@import \"_fonts\";\n@import \"_shadows\";\n```\n\nHere is part of the package.json file:\n\n```\n{\n ...\n \"devDependencies\": {\n ...\n \"node-sass\": \"^4.14.1\",\n \"nodemon\": \"^1.18.9\",\n \"sass\": \"^1.43.4\",\n \"sass-loader\": \"^8.0.2\"\n }\n}\n```\n\n*** I have tried diferent versions of node-sass and sass-loader:\n\n- node-sass@6.0.1 + sass-loader@10.2.0\nnode-sass@6.0.1 + sass-loader@8.0.2\n.... and some other tryings\n\nHere is part of my nuxt.config.js:\n\n```\ncss: [\n '~assets/scss/main.scss'\n ],\n\n styleResources: {\n scss: ['./assets/scss/variables.scss']\n },\n\n build: {\n rules: [\n {\n test: /\\.s[ac]ss$/i,\n use: ['style-loader', 'css-loader', 'sass-loader']\n }\n ],\n extend(config, ctx) {}\n },\n```\n\nAnd here is where I am trying to use the variable:\n\n```\n\n...\n\n@media screen and (max-width: $mobile-grid) {\n .description-row {\n text-align: center;\n }\n}\n\n```\n\nI really hope someone can help me to get out from this error.\n\n========================================\n\nTop Answer:\nYou can try this one. Write the following code inside nuxt.confit.js file. Surely it will work.\n\n```\nstyleResources: {\n scss: [\n '~/assets/scss/variables.scss',\n '~/assets/scss/_grid_variables.scss'\n ]\n}\n```\n\n========================================\n\nCode:\n```text\n-| assets\n---| scss\n-----| _grid_variables.scss\n-----| ....\n-----| variables.scss\n```\n\n```text\n$mobile-grid: 577px;\n$tablet-grid: 768px;\n$desktop-grid: 1024px;\n```\n\n```text\n@import \"_colors_variables\";\n@import \"_grid_variables\";\n@import \"_fonts\";\n@import \"_shadows\";\n```\n\n```text\n{\n ...\n \"devDependencies\": {\n ...\n \"node-sass\": \"^4.14.1\",\n \"nodemon\": \"^1.18.9\",\n \"sass\": \"^1.43.4\",\n \"sass-loader\": \"^8.0.2\"\n }\n}\n```\n\n```text\ncss: [\n '~assets/scss/main.scss'\n ],\n\n styleResources: {\n scss: ['./assets/scss/variables.scss']\n },\n\n build: {\n rules: [\n {\n test: /\\.s[ac]ss$/i,\n use: ['style-loader', 'css-loader', 'sass-loader']\n }\n ],\n extend(config, ctx) {}\n },\n```\n\n```text\n<style lang=\"scss\" scoped>\n\n...\n\n@media screen and (max-width: $mobile-grid) {\n .description-row {\n text-align: center;\n }\n}\n</style>\n```\n\n```text\nstyleResources: {\n scss: [\n '~/assets/scss/variables.scss',\n '~/assets/scss/_grid_variables.scss'\n ]\n}\n```\n\n========================================\n\nComments:\n- Anyone figured out how to do this in Nuxt 3?","metadata":{"transformedAt":"2026-08-18T18:33:07.907Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":190,"estimatedTokens":708}}982{"id":"stack-68998082","source":"stackoverflow","questionId":68998082,"title":"How to set up Axios and Nuxt runtime config for multiple APIs?","tags":["vue.js","axios","environment-variables","nuxt.js"],"text":"Title: How to set up Axios and Nuxt runtime config for multiple APIs?\nTags: vue.js, axios, environment-variables, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI've read through all the docs for Nuxt.js environment variables and the Axios module but I'm still quite confused on how to properly set them up for my use case.\n\nI want to query 2 separate APIs:\n\n- my own backend with user authentication (e.g. JWT) built with Nuxt serverMiddleware\n\n- a public API that requires an account and provides an API key (e.g. TMDB)\n\nMy own backend serves as an \"extension\" of the public API so that I can store additional data for my users.\n\nNow my question is how do I set up my environment variables so that I can safely send dynamic requests to the public API without exposing its private API key? Do I need to use my own backend as a \"proxy\" and forward client side requests to the public API from there? Or can I directly send requests inside asyncData and fetch when running in SSR mode?\n\nI think I need a general explanation on how Nuxt `publicRuntimeConfig` and `privateRuntimeConfig`, and Axios `baseURL` and `browserBaseURL` all work together. The docs didn't explain them clearly enough for me.\n\n========================================\n\nTop Answer:\nYou should send requests only to your private server and it should:\n\n- Perform the logic and send the result if it's your custom endpoint\n\n- Add API KEY to query and forward the query to the public API if it's public API endpoint.\n\n========================================\n\nCode:\n```text\npublicRuntimeConfig\n```\n\n```text\nprivateRuntimeConfig\n```\n\n```text\nbaseURL\n```\n\n```text\nbrowserBaseURL\n```\n\n```text\nprivateRuntimeConfig\n```\n\n```text\nfetch()\n```\n\n```text\nasyncData()\n```\n\n```text\nfetchOnServer: false\n```\n\n```text\naxios\n```\n\n```text\naxios\n```\n\n```text\nserverMiddleware\n```\n\n```text\naxios\n```\n\n```text\npublicRuntimeConfig\n```\n\n```text\nbaseURL\n```\n\n```text\nbrowserBaseURL\n```\n\n```text\nbaseURL\n```\n\n```text\nedge-side rendering\n```\n\n========================================\n\nComments:\n- This doesn't really answer the question of how to configure Nuxt to access two different APIs in both server and client contexts. I get what you're saying about proxying requests from the client through your private API server, but that doesn't address how to configure Nuxt to talk to a *second* API service.\n- So if I'm following along correctly, the recommendation here is to: Use `baseUrl` to configure Nuxt's default axios instance to speak to the OP's \"own backend\" and then configure a *second* axios instance for querying the separate \"public api\", but storing the api key for that external service in the `privateRuntimeConfig` and somehow making that second axios instance only run server-side? I personally could still sure use an example of how all these pieces fit together, like the OP.\n- No, the opposite in terms of axios (the NON `nuxt/axios` one should be in `serverMiddleware`). As for what is run only on the server, there are a few ones like `nuxtServerInit` and `serverMiddleware` (maybe something else?). So not a lot as you can see in the Nuxt lifecycle. Also, I don't have a backend under the hand and I guess that it all depends of your project too so yeah, not worth the time to create a project myself here IMO @beporter","metadata":{"transformedAt":"2026-08-18T18:33:07.907Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":105,"estimatedTokens":822}}983{"id":"stack-68950299","source":"stackoverflow","questionId":68950299,"title":"Unable to import a module from another module in Nuxt","tags":["typescript","vue.js","nuxt.js"],"text":"Title: Unable to import a module from another module in Nuxt\nTags: typescript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nIn my nuxt directory structure I have a folder called `modules` which contains my custom modules. In this example it will contain the modules `foo` and `bar`. In `nuxt.config.js` `foo` is added like so:\n\n```\n// nuxt.config.js\n...\nmodules: [\n ...\n \"~/modules/foo\"\n],\n...\n```\n\nNote `bar` is not added as a module.\nWhen I try to import `bar` in `foo`\n\n```\n// foo/index.ts\n\nimport { bar } from '~/modules/bar';\n\nexport default function fooModule() {\n console.log(bar)\n}\n```\n\n```\n// bar/index.ts\n\nconst bar = 1\nexport { bar };\n\nexport default function barModule() {}\n```\n\nI get `Nuxt Fatal Error`, `Error: Cannot find module '~/modules/bar'`.\nAdding `\"~/modules/bar\"` to `modules` in `nuxt.config.js` seems to make no difference.\n\nAny Idea on how to prevent this?\n\n========================================\n\nCode:\n```js\n// nuxt.config.js\n...\nmodules: [\n ...\n \"~/modules/foo\"\n],\n...\n```\n\n```js\n// foo/index.ts\n\nimport { bar } from '~/modules/bar';\n\nexport default function fooModule() {\n console.log(bar)\n}\n```\n\n```js\n// bar/index.ts\n\nconst bar = 1\nexport { bar };\n\nexport default function barModule() {}\n```\n\n```text\nmodules\n```\n\n```text\nfoo\n```\n\n```text\nbar\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nfoo\n```\n\n```text\nbar\n```\n\n```text\nbar\n```\n\n```text\nfoo\n```\n\n```text\nNuxt Fatal Error\n```\n\n```text\nError: Cannot find module '~/modules/bar'\n```\n\n```text\n\"~/modules/bar\"\n```\n\n```text\nmodules\n```\n\n```text\nnuxt.config.js\n```\n\n```js\nexport default {\n modules: ['@nuxtjs/axios']\n}\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nmodules\n```\n\n========================================\n\nComments:\n- Im not sure I thought plugins where meant to inject functionality into the Vue context (preferably I would like to import `foo` and `bar` using an import statement at the top of the script)? I might be misunderstanding the use of plugins, Ill look into this, thanks!\n- Yeah, the difference between `plugins` and `modules` can be hard to understand at first. Meanwhile, you need to also know that writing it as a plugin will link it globally to the project. If it's not needed, feel free to simply import it per component/page for performance reasons. @DominiqueGarmier\n- If not in `/plugins` where would you put those `.ts` files? Is there a best practice? From what I understand I could put them in `/assets` but the documentation says it's meant for images, styles, fonts etc.\n- @DominiqueGarmier usually, a `/utils/` is an okay directory (at the root of the project), I'm doing it this way and all the people I worked with before with are doing the same.\n- So I moved all my \"utils\" to `/utils`. But the problem remains. I have one module in `/modules` (which needs to be there), it injects a plugin into the Vue-context. And imports from `/utils`, which apparently doesn't exit during the build process. Giving me again `Error: Cannot find module '~/utils/...'`\n- Try with `'@/utils/...'`, `@` being the root of the project.","metadata":{"transformedAt":"2026-08-18T18:33:07.907Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":151,"estimatedTokens":771}}984{"id":"stack-68232751","source":"stackoverflow","questionId":68232751,"title":"Vuetify v-btn in v-bottom-navigation stays active when not pressed","tags":["javascript","vue.js","nuxt.js","vuetify.js"],"text":"Title: Vuetify v-btn in v-bottom-navigation stays active when not pressed\nTags: javascript, vue.js, nuxt.js, vuetify.js\nSource: Stack Overflow\n\nQuestion:\nI am having an issue with a button in my bottom nav in Vuetify. I have defined a bunch of buttons as routes (I am using Nuxtjs), so a button will be active if I am on that page.\n\nThere is a button in the bottom nav bar that is not a route though, and it exists to activate a v-navigation-drawer. When I click this button, the drawer slides out fine. When I click outside the drawer to get it to slide back, though, both the button of the page I am on and the button that activates the drawer are active. I want the button that activates the drawer to never be active.\n\nVisual--\nI am on the app's home page.\n\nHere is what the bottom nav looks like before clicking the button for the v-navigation-drawer\n\nHere is what the bottom nav looks like after I close the v-navigation-drawer. The button furthest to the right is what activates the navigation drawer, and it should never remain active after I close the drawer. Yet it does, and I need to click another button to deactivate it.\n\nI have tried many things suggested on other questions here to fix this, including but not limited to the following: defining a custom active class for this button, using the exact prop, and using a watcher to change the value of the active value in the nav bar. None of these things have worked.\n\nHere is the code where the issue is. I have removed the irrelevant buttons, keeping only the home and profile buttons (the profile is the problem one which stays active undesirably):\n\n```\n\n \n \n mdi-home\n \n \n\n \n \n \n mdi-account-circle\n \n \n\n```\n\nThe profile button stays active after I close the navigation drawer it opens (while another button is active at the same time due to vue's router) and I can only deactivate the profile button by clicking another button.\n\nHow might I eliminate this issue?\n\n**EDIT**\nI think I figured out what was wrong, for any people coming from a search engine. It appears to be a limitation of Vuetify's bottom nav. It is intended specifically for navigation and since this button was on the bottom nav bar without an assigned route (all it did was slide out a navigation drawer, no route change), it associates itself with the current route temporarily until another route is navigated to and the bottom navigation bar's state is modified. This interpretation may be wrong, but it seems to match the behavior.\n\nI was unable to fix the problem though due to my low knowledge of CSS (first time building a website, my day job is mostly data engineering) so I just changed my webapp's design. Apologies for anyone who was hoping for an answer :(\n\n========================================\n\nCode:\n```html\n<v-bottom-navigation\n app\n fluid\n grow\n color=\"primary\"\n class=\"d-flex d-sm-none\"\n>\n <v-btn\n value=\"home\"\n to=\"/home\"\n nuxt\n exact\n >\n <v-icon>\n mdi-home\n </v-icon>\n </v-btn>\n\n \n <v-btn\n value=\"profile\"\n exact\n @click=\"showProfileNavDrawer\"\n >\n <v-icon>\n mdi-account-circle\n </v-icon>\n </v-btn>\n</v-bottom-navigation>\n```\n\n```text\nv-btn\n```\n\n```text\nexact\n```\n\n```text\nexact\n```\n\n========================================\n\nComments:\n- Include the CSS code that changes the button color\n- You probably need to look for your devtools here and inspect the state.\n- This was the solution for me, using `:exact=\"true\"`.","metadata":{"transformedAt":"2026-08-18T18:33:07.908Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":99,"estimatedTokens":877}}985{"id":"stack-68423602","source":"stackoverflow","questionId":68423602,"title":"Nuxt root page (parent) is not rendered for child route despite using in the parent","tags":["vue.js","nuxt.js"],"text":"Title: Nuxt root page (parent) is not rendered for child route despite using in the parent\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a simple setup of files:\n\n**Pages structure:**\n\n```\n./pages/index.vue // root page to be displayed for '/'\n./pages/child.vue // sub-page to be displayed inside index.vue for '/child'\n```\n\n**`index.vue`:**\n\n```\n\n \n This is parent\n\n \n \n \n\n```\n\n**`child.vue`:**\n\n```\n\n \n This is Child\n\n \n\n```\n\nI expect that for `'/'` route the `index.vue` will be displayed and for `'/child'` route `index.vue` with embedded `child.vue` in the `` placeholder. `'/'` route works as expected, however for `'/child'` just `child.vue` is displayed.\n\nWhy? Does `` not work with root page or is there some other problem?\n\n========================================\n\nCode:\n```text\n./pages/index.vue // root page to be displayed for '/'\n./pages/child.vue // sub-page to be displayed inside index.vue for '/child'\n```\n\n```html\n<template>\n <div>\n <p>This is parent</p>\n <some-component-from-components></some-component-from-components>\n <nuxt-child />\n </div>\n</template>\n```\n\n```html\n<template>\n <div>\n <p>This is Child</p>\n </div>\n</template>\n```\n\n```text\nindex.vue\n```\n\n```text\nchild.vue\n```\n\n```text\n'/'\n```\n\n```text\nindex.vue\n```\n\n```text\n'/child'\n```\n\n```text\nindex.vue\n```\n\n```text\nchild.vue\n```\n\n```text\n<nuxt-child />\n```\n\n```text\n'/'\n```\n\n```text\n'/child'\n```\n\n```text\nchild.vue\n```\n\n```text\n<nuxt-child />\n```\n\n```text\nchild\n```\n\n```text\nindex\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.908Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":123,"estimatedTokens":377}}986{"id":"stack-70053468","source":"stackoverflow","questionId":70053468,"title":"Nuxtjs: Vue packages version mismatch: vue@3.2.22 and vue-server-renderer@2.6.14","tags":["vue.js","npm","vuejs2","nuxt.js","element-plus"],"text":"Title: Nuxtjs: Vue packages version mismatch: vue@3.2.22 and vue-server-renderer@2.6.14\nTags: vue.js, npm, vuejs2, nuxt.js, element-plus\nSource: Stack Overflow\n\nQuestion:\nI am developing a `Drawflow` application using `Vuejs/Nuxtjs` based on the code mentioned here. When I install the package `element-plus` and start the application then I get the error:\n\n```\nVue packages version mismatch:\n\n- vue@3.2.22\n- vue-server-renderer@2.6.14\n```\n\nIf I remove that package then everything works fine.\n\nI tried following things based on comments mentioned in various answers:\n\n- Remove `node_modules` and `package-lock.json` and install again with `npm install`.\n\n- Run the `npm audit fix --force`\n\n- Run the `npm update`\n\nBut nothing worked for me. Can someone please let me know what do I need to do so that I don't get this error and make everything work properly?\n\nComplete error from `terminal`:\n\n```\nVue packages version mismatch:\n\n- vue@3.2.22\n- vue-server-renderer@2.6.14\n\nThis may cause things to work incorrectly. Make sure to use the same version for both.\n\n \n Vue packages version mismatch:\n \n - vue@3.2.22\n - vue-server-renderer@2.6.14\n \n This may cause things to work incorrectly. Make sure to use the same version for both.\n \n at Object. (node_modules/vue-server-renderer/index.js:8:9)\n at Module.o._compile (node_modules/jiti/dist/v8cache.js:2:2778)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)\n at Module.load (internal/modules/cjs/loader.js:928:32)\n at Function.Module._load (internal/modules/cjs/loader.js:769:14)\n at Module.require (internal/modules/cjs/loader.js:952:19)\n at n (node_modules/jiti/dist/v8cache.js:2:2472)\n at Object. (node_modules/@nuxt/vue-renderer/dist/vue-renderer.js:19:27)\n at Module.o._compile (node_modules/jiti/dist/v8cache.js:2:2778)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)\n\n ╭────────────────────────────────────────────────────────────────────────────────────────────╮\n │ │\n │ ✖ Nuxt Fatal Error │\n │ │\n │ Error: │\n │ │\n │ Vue packages version mismatch: │\n │ │\n │ - vue@3.2.22 │\n │ - vue-server-renderer@2.6.14 │\n │ │\n │ This may cause things to work incorrectly. Make sure to use the same version for both.\n```\n\nFollowing is my complete `package.json` file:\n\n```\n{\n \"name\": \"my-project\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint:js\": \"eslint --ext \\\".js,.vue\\\" --ignore-path .gitignore .\",\n \"lint\": \"npm run lint:js\"\n },\n \"dependencies\": {\n \"@element-plus/icons\": \"^0.0.11\",\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"bootstrap\": \"^4.6.0\",\n \"bootstrap-vue\": \"^2.21.2\",\n \"core-js\": \"^3.15.1\",\n \"drawflow\": \"^0.0.52\",\n \"element-plus\": \"^1.2.0-beta.3\",\n \"nuxt\": \"^2.15.8\",\n \"url-loader\": \"^4.1.1\",\n \"vue-multiselect\": \"^2.1.6\"\n },\n \"devDependencies\": {\n \"@babel/eslint-parser\": \"^7.14.7\",\n \"@nuxtjs/eslint-config\": \"^6.0.1\",\n \"@nuxtjs/eslint-module\": \"^3.0.2\",\n \"@types/drawflow\": \"^0.0.3\",\n \"eslint\": \"^7.29.0\",\n \"eslint-plugin-nuxt\": \"^2.0.0\",\n \"eslint-plugin-vue\": \"^7.12.1\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\nVue packages version mismatch:\n\n- vue@3.2.22\n- vue-server-renderer@2.6.14\n```\n\n```text\nVue packages version mismatch:\n\n- vue@3.2.22\n- vue-server-renderer@2.6.14\n\nThis may cause things to work incorrectly. Make sure to use the same version for both.\n\n\n \n Vue packages version mismatch:\n \n - vue@3.2.22\n - vue-server-renderer@2.6.14\n \n This may cause things to work incorrectly. Make sure to use the same version for both.\n \n at Object.<anonymous> (node_modules/vue-server-renderer/index.js:8:9)\n at Module.o._compile (node_modules/jiti/dist/v8cache.js:2:2778)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)\n at Module.load (internal/modules/cjs/loader.js:928:32)\n at Function.Module._load (internal/modules/cjs/loader.js:769:14)\n at Module.require (internal/modules/cjs/loader.js:952:19)\n at n (node_modules/jiti/dist/v8cache.js:2:2472)\n at Object.<anonymous> (node_modules/@nuxt/vue-renderer/dist/vue-renderer.js:19:27)\n at Module.o._compile (node_modules/jiti/dist/v8cache.js:2:2778)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)\n\n\n ╭────────────────────────────────────────────────────────────────────────────────────────────╮\n │ │\n │ ✖ Nuxt Fatal Error │\n │ │\n │ Error: │\n │ │\n │ Vue packages version mismatch: │\n │ │\n │ - vue@3.2.22 │\n │ - vue-server-renderer@2.6.14 │\n │ │\n │ This may cause things to work incorrectly. Make sure to use the same version for both.\n```\n\n```json\n{\n \"name\": \"my-project\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"lint:js\": \"eslint --ext \\\".js,.vue\\\" --ignore-path .gitignore .\",\n \"lint\": \"npm run lint:js\"\n },\n \"dependencies\": {\n \"@element-plus/icons\": \"^0.0.11\",\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"bootstrap\": \"^4.6.0\",\n \"bootstrap-vue\": \"^2.21.2\",\n \"core-js\": \"^3.15.1\",\n \"drawflow\": \"^0.0.52\",\n \"element-plus\": \"^1.2.0-beta.3\",\n \"nuxt\": \"^2.15.8\",\n \"url-loader\": \"^4.1.1\",\n \"vue-multiselect\": \"^2.1.6\"\n },\n \"devDependencies\": {\n \"@babel/eslint-parser\": \"^7.14.7\",\n \"@nuxtjs/eslint-config\": \"^6.0.1\",\n \"@nuxtjs/eslint-module\": \"^3.0.2\",\n \"@types/drawflow\": \"^0.0.3\",\n \"eslint\": \"^7.29.0\",\n \"eslint-plugin-nuxt\": \"^2.0.0\",\n \"eslint-plugin-vue\": \"^7.12.1\"\n }\n}\n```\n\n```text\nDrawflow\n```\n\n```text\nVuejs/Nuxtjs\n```\n\n```text\nelement-plus\n```\n\n```text\nnode_modules\n```\n\n```text\npackage-lock.json\n```\n\n```text\nnpm install\n```\n\n```text\nnpm audit fix --force\n```\n\n```text\nnpm update\n```\n\n```text\nterminal\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- Those errors probably mean that you do have an incompatibility of the package required by the NPM package you're trying to install and the version used by Nuxt. There is maybe something that is **only** available with Vue3? (I'm thinking about something like HeadlessUI for example) It is not a package manager issue so far, but really a compatibility issues between the versions of the packages you're using.\n- @kissu Thanks a lot for your response. Yes, this definitely seems like the issue with package versions. Is there a way around for me with this issue? Because I am really stuck at this point. Looking forward to your suggestions.\n- You had a working project before, right? Try to make a diff or to read what the stacktrace is giving you. There is probably a mention of the miss-matching package at some point.\n- If I just install the package `npm install element-plus --save` and start the project using `npm run dev` then I am getting the error mentioned in the question. Without even using it I am getting the error. If I remove this package then everything works fine. I have added the complete `error` response that I am getting in my terminal.","metadata":{"transformedAt":"2026-08-18T18:33:07.908Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":247,"estimatedTokens":1970}}987{"id":"stack-70160953","source":"stackoverflow","questionId":70160953,"title":"Why is vue-splide not working with Nuxt2?","tags":["firebase","vue.js","nuxt.js","splidejs"],"text":"Title: Why is vue-splide not working with Nuxt2?\nTags: firebase, vue.js, nuxt.js, splidejs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to add Vue-Splide to my Nuxt project, after following the Vue-Splide documentation to install the plugin, and registering it as a Nuxt plugin I get the error `Cannot use import statement outside a module`.\n\n`nuxt.config.js`\n\n```\nbuildDir: '../functions/nuxt',\nbuild: {\n publicPath: '/public/',\n vendor: [''],\n extractCSS: true,\n babel: {\n presets: [\n '@babel/preset-env'\n ],\n plugins: [\n [\"@babel/plugin-transform-runtime\"]\n ]\n }\n},\nplugins: [\n { src: '~/plugins/splide.client.js', mode: \"client\" }\n],\n```\n\n`splide.client.js`\n\n```\nimport Vue from 'vue';\nimport VueSplide from '@splidejs/vue-splide';\nimport '@splidejs/splide/dist/css/themes/splide-default.min.css';\n\nVue.use(VueSplide);\n```\n\n`template`\n\n```\n\n \n \n \n\n```\n\nAfter transpiling Vue-Splide I now get the error `window is not defined`, and the stacktrace shows it's happening on `node_modules\\@splidejs\\splide\\dist\\js\\splide.js`, I tried surrounding the splide tags with ``, but that didn't seem to work.\n\nWhat else am I missing here?\n\n**Updating to include my dependencies**\n\n```\n\"dependencies\": {\n \"@nuxtjs/firebase\": \"^7.6.1\",\n \"@splidejs/vue-splide\": \"^0.3.5\",\n \"firebase\": \"^8.9.1\",\n \"isomorphic-fetch\": \"^3.0.0\",\n \"nuxt\": \"^2.0.0\"\n},\n\"devDependencies\": {\n \"@babel/plugin-transform-runtime\": \"^7.15.0\",\n \"@babel/preset-env\": \"^7.15.6\",\n \"@babel/runtime\": \"^7.15.4\",\n \"@nuxtjs/tailwindcss\": \"^4.2.1\",\n \"autoprefixer\": \"^10.4.0\",\n \"babel-eslint\": \"^10.0.1\",\n \"babel-plugin-module-resolver\": \"^4.1.0\",\n \"eslint\": \"^4.19.1\",\n \"eslint-friendly-formatter\": \"^4.0.1\",\n \"eslint-loader\": \"^4.0.2\",\n \"eslint-plugin-vue\": \"^7.19.1\",\n \"firebase-tools\": \"^9.22.0\",\n \"node-sass\": \"^6.0.1\",\n \"postcss\": \"^8.3.11\",\n \"sass-loader\": \"^12.3.0\",\n \"tailwindcss\": \"^2.2.19\"\n}\n```\n\n========================================\n\nTop Answer:\nThe documentation of the vue-splide integration is clearly talking about Vue3 composition API.\n\nChecking in the github issues of vue-splide, I found this one which is referencing a solution that you've linked above. Meanwhile, when trying this, those are the warnings that I do have in my CLI.\n\nThose are also related to Vue3 (which is not compatible with Nuxt2, only Nuxt3 supports Vue3). Looking at the date of all the posts, it looks like it was matching somewhat the time-frame when Vue3 was still in a beta-limbo and probably not adopted by everybody.\n\nAt some point, I guessed that the package maybe lost some retro-compatibility with Vue2 in the next months. I then tried to install the version `0.3.5` of `@splidejs/vue-splide` rather than the latest one and it's working perfectly fine with it!\n\nHere is the whole setup to have it working with Nuxt2\n`nuxt.config.js`\n\n```\nplugins: [{ src: '~/plugins/splide.js', mode: 'client' }],\n```\n\nPS: no need for a `transpile` because this is not the issue at all here\n\n`/plugins/splide.js`\n\n```\nimport Vue from 'vue'\nimport VueSplide from '@splidejs/vue-splide'\nimport '@splidejs/splide/dist/css/themes/splide-default.min.css'\n\nVue.use(VueSplide)\n```\n\n`/pages/index.vue`\n\n```\n\n \n \n \n \n \n \n \n \n \n \n\n```\n\nIt works perfectly fine\n\nI've reported the issue in the github issue, if somebody wants to have more up-to date info or an official answer from the mantainer.\n\nEDIT: we received a confirmation on the non retro-compatibility. Also, the usage of `` is also required to prevent DOM mismatch.\n\n========================================\n\nCode:\n```js\nbuildDir: '../functions/nuxt',\nbuild: {\n publicPath: '/public/',\n vendor: [''],\n extractCSS: true,\n babel: {\n presets: [\n '@babel/preset-env'\n ],\n plugins: [\n [\"@babel/plugin-transform-runtime\"]\n ]\n }\n},\nplugins: [\n { src: '~/plugins/splide.client.js', mode: \"client\" }\n],\n```\n\n```js\nimport Vue from 'vue';\nimport VueSplide from '@splidejs/vue-splide';\nimport '@splidejs/splide/dist/css/themes/splide-default.min.css';\n\nVue.use(VueSplide);\n```\n\n```html\n<splide :options=\"{ rewind: true }\" class=\"banner-container\">\n <splide-slide class=\"slide\" v-for=\"slide in slides\" :key=\"slide.id\">\n <img :src=\"slide.imagen\" :alt=\"slide.tombre\" />\n </splide-slide>\n</splide>\n```\n\n```json\n\"dependencies\": {\n \"@nuxtjs/firebase\": \"^7.6.1\",\n \"@splidejs/vue-splide\": \"^0.3.5\",\n \"firebase\": \"^8.9.1\",\n \"isomorphic-fetch\": \"^3.0.0\",\n \"nuxt\": \"^2.0.0\"\n},\n\"devDependencies\": {\n \"@babel/plugin-transform-runtime\": \"^7.15.0\",\n \"@babel/preset-env\": \"^7.15.6\",\n \"@babel/runtime\": \"^7.15.4\",\n \"@nuxtjs/tailwindcss\": \"^4.2.1\",\n \"autoprefixer\": \"^10.4.0\",\n \"babel-eslint\": \"^10.0.1\",\n \"babel-plugin-module-resolver\": \"^4.1.0\",\n \"eslint\": \"^4.19.1\",\n \"eslint-friendly-formatter\": \"^4.0.1\",\n \"eslint-loader\": \"^4.0.2\",\n \"eslint-plugin-vue\": \"^7.19.1\",\n \"firebase-tools\": \"^9.22.0\",\n \"node-sass\": \"^6.0.1\",\n \"postcss\": \"^8.3.11\",\n \"sass-loader\": \"^12.3.0\",\n \"tailwindcss\": \"^2.2.19\"\n}\n```\n\n```text\nCannot use import statement outside a module\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nsplide.client.js\n```\n\n```text\ntemplate\n```\n\n```text\nwindow is not defined\n```\n\n```text\nnode_modules\\@splidejs\\splide\\dist\\js\\splide.js\n```\n\n```text\n<client-only></client-only>\n```\n\n```text\nbuildDir: '../functions/nuxt'\n```\n\n```text\npublicPath: '/public/'\n```\n\n```text\npublicPath: '/'\n```\n\n```text\nsrc/nuxt.config.js\n```\n\n```text\nfunctions/index.js\n```\n\n```text\nnpm run build\n```\n\n```text\nsrc/.nuxt\n```\n\n```text\nfunctions/nuxt\n```\n\n```text\nsrc/.nuxt/dist/client\n```\n\n```text\nsrc/.nuxt/dist/server\n```\n\n```text\npublic/\n```\n\n```js\nplugins: [{ src: '~/plugins/splide.js', mode: 'client' }],\n```\n\n```js\nimport Vue from 'vue'\nimport VueSplide from '@splidejs/vue-splide'\nimport '@splidejs/splide/dist/css/themes/splide-default.min.css'\n\nVue.use(VueSplide)\n```\n\n```html\n<template>\n <client-only>\n <Splide :options=\"{ rewind: true }\">\n <SplideSlide>\n <img\n src=\"https://images.unsplash.com/photo-1638204958375-4824be216720?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=776&q=80\"\n alt=\"Sample 1\"\n />\n </SplideSlide>\n <SplideSlide>\n <img\n src=\"https://images.unsplash.com/photo-1638176061592-d8475d970c19?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=774&q=80\"\n alt=\"Sample 2\"\n />\n </SplideSlide>\n </Splide>\n </client-only>\n</template>\n```\n\n```text\n0.3.5\n```\n\n```text\n@splidejs/vue-splide\n```\n\n```text\nnuxt.config.js\n```\n\n```text\ntranspile\n```\n\n```text\n/plugins/splide.js\n```\n\n```text\n/pages/index.vue\n```\n\n```text\n<client-only>\n```\n\n========================================\n\nComments:\n- I've edited your question with some highlight and removed `~/plugins/splide.client.js` in favor of `~/plugins/splide.js`, `mode: 'client'` doing already that, there is no point double-telling that we want it only on the client. I've also removed irrelevant parts of code. Feel free to edit it yourself if you find it inappropriate.\n- Also, totally unrelated but could you please give a look to my answer on your other question? I'm still waiting some feedback if it solved your issue or not.\n- @kissu my apologies, I haven't been able to get back on the other issue as I'm now prioritizing this one.\n- I'm still running into the same issue, transpiling vue-splide throws me ` window is not defined `, if I don't I get` Cannot use import statement outside a module`, I already had vue-splide version 0.3.5 installed. I'm updating my post to include my dependencies\n- @Danyx you don't need to transpile it as I told. Also, using the plugin as I showed and wrapping the whole thing into a `client-only` is enough. Tried it with `ssr: true` and it's working fine on my side. Also, be sure that you're using node with a LTS version, I am on `14.18.1`. This may come from here maybe.\n- I have the Splide element wrapped by , and also just upgraded from node v14..17.6 to v.16.13.0 to see if that was the case, still getting `Cannot use import statement outside a module`\n- @Danyx add `\"type\": \"module\"` to your package.json as shown here to fix this issue. Also, are you using TS? I'm not sure where this issue comes from but it's not the first time I see it, do you use a `require` somewhere in your code maybe?\n- already tried adding `\"type\": \"module\"` to the root of my package.json and it also didn't work, I'm not using TypeScript, and have no requires anywhere in my source code.\n- @Danyx I'm not sure how to help more here. Try to narrow down the issue by creating a brand new project and send us the github link, that way we will be able to look at it. Hard to say why this is not working on your side. It's not an issue with the package at least.\n- was just thinking about that, thank you so much for helping with this, I'll set up a new project and go from there\n- Oh, the issue was when deployed. Would have suggested to try to ship it to Netlify if I'd knew.\n- @kissu it was throwing the exception when building locally","metadata":{"transformedAt":"2026-08-18T18:33:07.908Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":351,"estimatedTokens":2253}}988{"id":"stack-68581567","source":"stackoverflow","questionId":68581567,"title":"sh: 1: nuxt: not found (Heroku/Nuxt)","tags":["vue.js","express","heroku","nuxt.js"],"text":"Title: sh: 1: nuxt: not found (Heroku/Nuxt)\nTags: vue.js, express, heroku, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI've got a problem, I'm finally deploying a server-side nuxt app (with an express server) I've created to Heroku. The build succeeds but then when it tries to start it gives me:\n\n```\n2021-07-29T18:13:38.000000+00:00 app[api]: Build succeeded\n2021-07-29T18:13:42.050534+00:00 heroku[web.1]: Process exited with status 1\n2021-07-29T18:13:42.139623+00:00 heroku[web.1]: State changed from starting to crashed\n2021-07-29T18:13:41.793565+00:00 app[web.1]: \n2021-07-29T18:13:41.793587+00:00 app[web.1]: > nuxt-express@1.0.0 start /app\n2021-07-29T18:13:41.793588+00:00 app[web.1]: > nuxt start\n2021-07-29T18:13:41.793588+00:00 app[web.1]:\n2021-07-29T18:13:41.814774+00:00 app[web.1]: sh: 1: nuxt: not found\n2021-07-29T18:13:41.822159+00:00 app[web.1]: npm ERR! code ELIFECYCLE\n2021-07-29T18:13:41.822579+00:00 app[web.1]: npm ERR! syscall spawn\n2021-07-29T18:13:41.822774+00:00 app[web.1]: npm ERR! file sh\n2021-07-29T18:13:41.823001+00:00 app[web.1]: npm ERR! errno ENOENT\n2021-07-29T18:13:41.834748+00:00 app[web.1]: npm ERR! nuxt-express@1.0.0 start: `nuxt start`\n2021-07-29T18:13:41.834966+00:00 app[web.1]: npm ERR! spawn ENOENT\n2021-07-29T18:13:41.835206+00:00 app[web.1]: npm ERR!\n2021-07-29T18:13:41.835433+00:00 app[web.1]: npm ERR! Failed at the nuxt-express@1.0.0 start script.\n```\n\nI'm not sure where i'm going wrong with this. Do I have to build it before deploying with the Heroku cli? Is it a problem with my express server (since it's saying it failed at nuxt-express. I'm just not sure whats going on, if anyone could be of help it would greatly assist me! Thanks!\n\nHere is my **package.json** if it helps:\n\n```\n{\n \"name\": \"p-live\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"heroku-postbuild\": \"npm run build\"\n },\n \"dependencies\": {\n \"@nuxt/http\": \"latest\",\n \"@nuxtjs/firebase\": \"^7.5.0\",\n \"cookie-universal-nuxt\": \"^2.1.5\",\n \"dotenv\": \"^10.0.0\",\n \"express\": \"latest\",\n \"firebase\": \"^8.3.1\",\n \"jsforce\": \"^1.10.1\",\n \"nuxt\": \"latest\"\n },\n \"devDependencies\": {\n \"@nuxtjs/moment\": \"^1.6.1\",\n \"@nuxtjs/pwa\": \"^3.3.5\",\n \"@nuxtjs/tailwindcss\": \"^3.4.2\",\n \"@tailwindcss/custom-forms\": \"^0.2.1\",\n \"@tailwindcss/postcss7-compat\": \"^2.0.3\",\n \"autoprefixer\": \"^9.8.6\",\n \"babel-eslint\": \"^10.1.0\",\n \"eslint\": \"^7.20.0\",\n \"eslint-plugin-nuxt\": \"^2.0.0\",\n \"postcss\": \"^7.0.35\",\n \"tailwindcss\": \"npm:@tailwindcss/postcss7-compat@^2.0.3\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\n2021-07-29T18:13:38.000000+00:00 app[api]: Build succeeded\n2021-07-29T18:13:42.050534+00:00 heroku[web.1]: Process exited with status 1\n2021-07-29T18:13:42.139623+00:00 heroku[web.1]: State changed from starting to crashed\n2021-07-29T18:13:41.793565+00:00 app[web.1]: \n2021-07-29T18:13:41.793587+00:00 app[web.1]: > nuxt-express@1.0.0 start /app\n2021-07-29T18:13:41.793588+00:00 app[web.1]: > nuxt start\n2021-07-29T18:13:41.793588+00:00 app[web.1]:\n2021-07-29T18:13:41.814774+00:00 app[web.1]: sh: 1: nuxt: not found\n2021-07-29T18:13:41.822159+00:00 app[web.1]: npm ERR! code ELIFECYCLE\n2021-07-29T18:13:41.822579+00:00 app[web.1]: npm ERR! syscall spawn\n2021-07-29T18:13:41.822774+00:00 app[web.1]: npm ERR! file sh\n2021-07-29T18:13:41.823001+00:00 app[web.1]: npm ERR! errno ENOENT\n2021-07-29T18:13:41.834748+00:00 app[web.1]: npm ERR! nuxt-express@1.0.0 start: `nuxt start`\n2021-07-29T18:13:41.834966+00:00 app[web.1]: npm ERR! spawn ENOENT\n2021-07-29T18:13:41.835206+00:00 app[web.1]: npm ERR!\n2021-07-29T18:13:41.835433+00:00 app[web.1]: npm ERR! Failed at the nuxt-express@1.0.0 start script.\n```\n\n```json\n{\n \"name\": \"p-live\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"heroku-postbuild\": \"npm run build\"\n },\n \"dependencies\": {\n \"@nuxt/http\": \"latest\",\n \"@nuxtjs/firebase\": \"^7.5.0\",\n \"cookie-universal-nuxt\": \"^2.1.5\",\n \"dotenv\": \"^10.0.0\",\n \"express\": \"latest\",\n \"firebase\": \"^8.3.1\",\n \"jsforce\": \"^1.10.1\",\n \"nuxt\": \"latest\"\n },\n \"devDependencies\": {\n \"@nuxtjs/moment\": \"^1.6.1\",\n \"@nuxtjs/pwa\": \"^3.3.5\",\n \"@nuxtjs/tailwindcss\": \"^3.4.2\",\n \"@tailwindcss/custom-forms\": \"^0.2.1\",\n \"@tailwindcss/postcss7-compat\": \"^2.0.3\",\n \"autoprefixer\": \"^9.8.6\",\n \"babel-eslint\": \"^10.1.0\",\n \"eslint\": \"^7.20.0\",\n \"eslint-plugin-nuxt\": \"^2.0.0\",\n \"postcss\": \"^7.0.35\",\n \"tailwindcss\": \"npm:@tailwindcss/postcss7-compat@^2.0.3\"\n }\n}\n```\n\n```json\n\"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\",\n \"heroku-postbuild\": \"npm run build\"\n },\n```\n\n```json\n\"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"node_modules/nuxt/bin/nuxt.js build -c ./nuxt.config.js\",\n \"start\": \"node_modules/nuxt/bin/nuxt.js start -c ./nuxt.config.js\",\n \"generate\": \"nuxt generate\",\n \"heroku-postbuild\": \"npm run build\"\n },\n```\n\n```text\nnuxt/bin\n```\n\n```text\n-c\n```\n\n```text\nnuxt.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.909Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":159,"estimatedTokens":1292}}989{"id":"stack-68654771","source":"stackoverflow","questionId":68654771,"title":"NuxtJS: routes working in dev but not production (netlify)","tags":["javascript","vue.js","nuxt.js","nuxt-content"],"text":"Title: NuxtJS: routes working in dev but not production (netlify)\nTags: javascript, vue.js, nuxt.js, nuxt-content\nSource: Stack Overflow\n\nQuestion:\nStill very much learning JS, but I'm struggling with this issue.\n\nIn the VS code debug environment, everything works, but when I deploy to Netlify, some routes work only sometimes. For example, this route, along with the other /interests routes, either 404s, loads a blank page, or occasionally just works.\n\nThe code behind those pages is here. The other nuxt-content pages in /posts, /tags, and /wip all work fine.\n\nI get no errors that I can see related to this in the dev environment. I'm still new to js troubleshooting, but when I load up dev tools in Chrome, I sometimes see an error \"DOMException: Failed to execute 'appendChild' on 'Node': This node type does not support this method.\"\n\nI've researched that error leading me to a few posts on the topic:\n\n- Nuxtjs issue\n\n- Vuejs error on client side\n\n- Hydration errors blog pos\n\n- failed to execute 'appendChild' node\n\n- full static mode dynamic pages payload 404 errors\n\nI've tried various solutions from there including replacing v-if with v-show, and cleaning up `` tags, and wrapping various things in `` but the problem persists.\n\nAnyone have insight into what I'm doing wrong?\n\n========================================\n\nCode:\n```text\n<p>\n```\n\n```text\n<client-only>\n```\n\n```html\n<template>\n <div class=\"sidebar\">\n <div\n v-if=\"isPanelOpen\"\n class=\"sidebar-backdrop\"\n @click=\"closeSidebarPanel\"\n />\n <transition name=\"slide\">\n <div v-if=\"isPanelOpen\" class=\"sidebar-panel\">\n <slot />\n </div>\n </transition>\n </div>\n</template>\n```\n\n```html\n<Sidebar>\n <ul class=\"sidebar-panel-nav\" @click=\"closeSidebarPanel\">\n <li>\n •\n <nuxt-link to=\"/interests/film-photography\">\n Film Photography\n </nuxt-link>\n </li>\n </ul>\n</Sidebar>\n```\n\n```html\n<div v-if=\"isPanelOpen\">\n```\n\n```html\n<div v-show=\"isPanelOpen\">\n```\n\n```text\nSidebar.vue\n```\n\n```text\nslot\n```\n\n```text\nlayouts/default.vue\n```\n\n```text\nyarn generate\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nbuild\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.909Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":105,"estimatedTokens":543}}990{"id":"stack-66469447","source":"stackoverflow","questionId":66469447,"title":"Nuxt.js - Globally import custom NPM packages","tags":["javascript","vue.js","npm","nuxt.js"],"text":"Title: Nuxt.js - Globally import custom NPM packages\nTags: javascript, vue.js, npm, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nNuxt's plugins/modules system is extremely complicated and as such I've not been able to accomplish this very simple task, even after looking at some other answers here on SO. I've installed the NPM package `csv-parse` (found here), then I created a file in my project's `plugins` directory named `csv-parse.js`, in which I put the following code:\n\n```\nimport Vue from 'vue';\nimport CsvParse from 'csv-parse';\nVue.use(CsvParse);\n```\n\nThen I added `{ src: \"~/plugins/csv-parse\", mode: \"client\" }` to the plugins array in my `nuxt.config.js` (I only need to use this package client-side).\n\nAs far as Nuxt's documentation and the other SO answers will have you believe, you should now be able to use this package globally in your components, but no one cares to show how to use it in your component. Here's what I've tried:\n\n```\n// @/components/Hospitals/Crud.vue\n...\n\n export default {\n methods: {\n parseFileData() {\n console.log('parser:', CsvParser); // ReferenceError: CsvParser is not defined\n console.log('parser:', $CsvParser); // ReferenceError: $CsvParser is not defined\n console.log('parser:', this.CsvParser); // undefined\n console.log('parser:', this.$CsvParser); // undefined\n }\n }\n }\n\n...\n```\n\nCan someone please clear the mystery of how to globally use custom NPM packages in a Nuxt project?\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue';\nimport CsvParse from 'csv-parse';\nVue.use(CsvParse);\n```\n\n```text\n// @/components/Hospitals/Crud.vue\n...\n<script>\n export default {\n methods: {\n parseFileData() {\n console.log('parser:', CsvParser); // ReferenceError: CsvParser is not defined\n console.log('parser:', $CsvParser); // ReferenceError: $CsvParser is not defined\n console.log('parser:', this.CsvParser); // undefined\n console.log('parser:', this.$CsvParser); // undefined\n }\n }\n }\n</script>\n...\n```\n\n```text\ncsv-parse\n```\n\n```text\nplugins\n```\n\n```text\ncsv-parse.js\n```\n\n```text\n{ src: \"~/plugins/csv-parse\", mode: \"client\" }\n```\n\n```text\nnuxt.config.js\n```\n\n```js\nimport Vue from 'vue'\nimport { ValidationProvider, ValidationObserver } from 'vee-validate'\n\nexport default ({ app }) => {\n Vue.component('ValidationObserver', ValidationObserver)\n Vue.component('ValidationProvider', ValidationProvider)\n}\n```\n\n```html\n<ValidationProvider v-slot=\"v\">\n <input v-model=\"value\" type=\"text\">\n</ValidationProvider>\n```\n\n```js\nvar csv = require('csv');\nvar generator = csv.generate({seed: 1, columns: 2, length: 20});\n```\n\n```text\nvue-vee-validate.js\n```\n\n```text\ncsv-parse.js\n```\n\n========================================\n\nComments:\n- For a quick explanation: modules are official packages (usually well maintained) by the community, and which are plug and play. There is a list here: modules.nuxtjs.org (it probably do not have them all but a good amount still). Plugins provide a way to import any kind of JS code (Vue or vanilla) into your project, before Vue instance is up. It's basically to import any code that is not designed for Nuxt out of the box.\n- Thanks for taking the time. In the end I gave up and just ended up importing it locally. As for executing csv operations in the client - the problem is that I was to perform additional operations on the data set, and the functionality to perform the additional operations is only available on the client and not on the server.","metadata":{"transformedAt":"2026-08-18T18:33:07.909Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":118,"estimatedTokens":878}}991{"id":"stack-61755300","source":"stackoverflow","questionId":61755300,"title":"Fetch only works on refresh","tags":["javascript","vue.js","fetch","nuxt.js"],"text":"Title: Fetch only works on refresh\nTags: javascript, vue.js, fetch, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying the new Nuxt.js Fetch method. Initially, I thought everything was fine. But the data is only fetched and rendered when I refresh the page.\nHowever, if the page is accesses through $fetchState.error equals true and the data is never fetched.\n\nWhat am I doing wrong here?\n\n```\n\n \n \n \n \n Fetching vehicles...\n \n\n \n Error while fetching vehicles\n \n\n \n \n {{ vehicle.Make }}\n \n \n \n Refresh Data\n \n \n\nimport axios from 'axios'\n\nexport default {\n data() {\n return {\n usedVehicles: []\n }\n },\n async fetch() {\n const { data } = await axios.get(\n 'https://random.com/api'\n )\n // `todos` has to be declared in data()\n this.usedVehicles = data.Vehicles\n },\n methods: {\n refresh() {\n this.$fetch()\n }\n }\n}\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <main>\n <div>\n <div>\n <p v-if=\"$fetchState.pending\">\n Fetching vehicles...\n </p>\n <p v-else-if=\"$fetchState.error\">\n Error while fetching vehicles\n </p>\n <div\n v-for=\"(vehicle, index) in usedVehicles\"\n v-else\n :key=\"index\"\n >\n <nuxt-link :to=\"`cars/${vehicle.Id}`\">\n {{ vehicle.Make }}\n </nuxt-link>\n </div>\n </div>\n <button @click=\"$fetch\">Refresh Data</button>\n </div>\n </main>\n</template>\n\n<script>\nimport axios from 'axios'\n\nexport default {\n data() {\n return {\n usedVehicles: []\n }\n },\n async fetch() {\n const { data } = await axios.get(\n 'https://random.com/api'\n )\n // `todos` has to be declared in data()\n this.usedVehicles = data.Vehicles\n },\n methods: {\n refresh() {\n this.$fetch()\n }\n }\n}\n</script>\n```\n\n```text\n<template>\n <main>\n <div>\n <div>\n <p v-if=\"$fetchState.pending\">\n Fetching vehicles...\n </p>\n <p v-else-if=\"$fetchState.error\">\n Error while fetching vehicles\n </p>\n <div\n v-for=\"(vehicle, index) in usedVehicles\"\n v-else\n :key=\"index\"\n >\n <nuxt-link :to=\"`cars/${vehicle.Id}`\">\n {{ vehicle.Make }}\n </nuxt-link>\n </div>\n </div>\n <button @click=\"$fetch\">Refresh Data</button>\n </div>\n </main>\n</template>\n\n<script>\nimport axios from 'axios'\n\nexport default {\n data() {\n return {\n usedVehicles: []\n }\n },\n async asyncData() {\n const { data } = await axios.get(\n 'https://random.com/api'\n )\n\n return { usedVehicles: data.Vehicles }\n }\n async fetch() {\n const { data } = await axios.get(\n 'https://random.com/api'\n )\n // `todos` has to be declared in data()\n this.usedVehicles = data.Vehicles\n },\n methods: {\n refresh() {\n this.$fetch()\n }\n }\n}\n</script>\n```\n\n```text\nfetch\n```\n\n```text\nthis.usedVehicles\n```\n\n```text\nasyncData\n```\n\n```text\nusedVehicles\n```\n\n========================================\n\nComments:\n- fetch may finish after mounted - therefore when you refresh - it may have that data cached. use asyncData if you wish to retain that data on the server render before first mount\n- Thanks for you help. I have figured out the issue may lay in the API i am using. I've tried coping the JSON and hosted it on another server. This seemed to help me. But why, I don't know.\n- feel free to upvote anyway - thx","metadata":{"transformedAt":"2026-08-18T18:33:07.909Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":191,"estimatedTokens":855}}992{"id":"stack-68044585","source":"stackoverflow","questionId":68044585,"title":"How can I use _slug inside another _slug directory in dynamic nuxt.js routing?","tags":["routes","nuxt.js","dynamic-routing"],"text":"Title: How can I use _slug inside another _slug directory in dynamic nuxt.js routing?\nTags: routes, nuxt.js, dynamic-routing\nSource: Stack Overflow\n\nQuestion:\nMy folder structure\n\nhttps://i.sstatic.net/LeRcS.png\n\nShowing this wanning on my console.\n\n```\nDuplicate param keys in route with path: \"/design/:slug?/:slug\"\n```\n\n========================================\n\nTop Answer:\nSo just change the folder name. _slug to _slug2 .\nDifferent name for slug.\n\nhttps://i.sstatic.net/hVKKt.png\n\n========================================\n\nCode:\n```text\nDuplicate param keys in route with path: \"/design/:slug?/:slug\"\n```\n\n```text\ndesign/_slug/_slug\ndesign/_info/_info\n```\n\n```text\ndesign/_slug/_info\ndesign/_slug/_slug2\n\n*or whatever you want to name it\n```\n\n```text\nproduct/_slug\n```\n\n```text\ndesign/_slug\n```\n\n========================================\n\nComments:\n- you cannot use same name for more than 1 param, you are free to use any other name for it, maybe `slug2`?\n- despite the warning, there seems to be no technical restrictions, as it is working in my case.","metadata":{"transformedAt":"2026-08-18T18:33:07.909Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":55,"estimatedTokens":265}}993{"id":"stack-62923990","source":"stackoverflow","questionId":62923990,"title":"nuxt: pass data from server plugin to client","tags":["nuxt.js"],"text":"Title: nuxt: pass data from server plugin to client\nTags: nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a nuxt behind an auth proxy. A request will get to nuxt (only if) it is authorized, in which case the `X-auth-username` (and other) headers will be set.\n\nI have found that, using a server plugin, I can read this info on the request. However, the data is not send from the server to the client. How do I get the server to send information headers (in particular the user name) to the client?\n\nMy plugin so far:\n\n```\nimport { Plugin } from '@nuxt/types'\nimport { IncomingHttpHeaders } from 'http'\n\ndeclare module '@nuxt/types' {\n interface NuxtAppOptions {\n $headers: IncomingHttpHeaders\n }\n}\n\nconst getAuth: Plugin = (context, inject) => {\n const headers = context.req.headers\n inject('headers', headers)\n}\n\nexport default getAuth\n```\n\n*NOTE* I am using the `nuxt-composition-api`, and not vuex.\n\n========================================\n\nTop Answer:\nInjected `header` should be available as `$headers` in templates or lifecycle methods of components as `this.$headers`.\n\n========================================\n\nCode:\n```js\nimport { Plugin } from '@nuxt/types'\nimport { IncomingHttpHeaders } from 'http'\n\ndeclare module '@nuxt/types' {\n interface NuxtAppOptions {\n $headers: IncomingHttpHeaders\n }\n}\n\nconst getAuth: Plugin = (context, inject) => {\n const headers = context.req.headers\n inject('headers', headers)\n}\n\nexport default getAuth\n```\n\n```text\nX-auth-username\n```\n\n```text\nnuxt-composition-api\n```\n\n```text\n// in nuxt plugin\nif (process.server) {\n // set property on server\n context.beforeNuxtRender(({ nuxtState }) => {\n nuxtState.headerValue = 'test';\n });\n} else {\n // retrieve it on client\n let valueOnClient = context.nuxtState?.headerValue;\n}\n```\n\n```text\nheader\n```\n\n```text\n$headers\n```\n\n```text\nthis.$headers\n```\n\n========================================\n\nComments:\n- you can use a server middleware to achieve this. nuxtjs.org/api/configuration-servermiddleware\n- @BillSomen That gives me access to the request, but how/where to I put the info to pass to the client? (Already in the server plugin I have access to the request -- so that isn't the problem per se.)\n- When I inject on the server, I see it in the server. The task is to get it to the client after reading it from the request on the server. Right now I'm putting it in a cookie, which seems to work, but I would prefer to get it into the webpack bundle.","metadata":{"transformedAt":"2026-08-18T18:33:07.909Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":96,"estimatedTokens":618}}994{"id":"stack-65095236","source":"stackoverflow","questionId":65095236,"title":"Nuxt - composition api and watchers","tags":["vue.js","vuejs2","nuxt.js","vuejs3","vue-composition-api"],"text":"Title: Nuxt - composition api and watchers\nTags: vue.js, vuejs2, nuxt.js, vuejs3, vue-composition-api\nSource: Stack Overflow\n\nQuestion:\nI am trying to watch for some warnings in my component\n\n```\nimport VueCompositionApi, { watch } from '@vue/composition-api';\nimport useWarning from '@composables/warnings';\n\nVue.use(VueCompositionApi);\n\nsetup () {\n\n const { activeWarnings } = useWarning();\n\n watch(activeWarnings, () => {\n \n console.log('called inside on update')\n });\n\n }\n```\n\nIn my composition function I just push into the reactive array to simulate warning.\n\n```\nimport { reactive } from '@vue/composition-api';\n\nexport default function useWarnings () {\n\n const activeWarnings = reactive([]);\n\n setInterval(() => {\n fakeWarning();\n }, 3000);\n\n function fakeWarning () {\n activeWarnings.push({\n type: 'severe',\n errorCode: 0,\n errorLevel: 'red',\n \n }\n);\n }\n return { activeWarnings };\n```\n\nDoes this not work in Vue 2 at all? Is there a workaround? activeWarnings does update in my component - I see the array filling up but this watcher is never called.\n\nI am using https://composition-api.nuxtjs.org/\n\n========================================\n\nCode:\n```text\nimport VueCompositionApi, { watch } from '@vue/composition-api';\nimport useWarning from '@composables/warnings';\n\nVue.use(VueCompositionApi);\n\nsetup () {\n\n const { activeWarnings } = useWarning();\n\n watch(activeWarnings, () => {\n \n console.log('called inside on update')\n });\n\n }\n```\n\n```text\nimport { reactive } from '@vue/composition-api';\n\nexport default function useWarnings () {\n\n const activeWarnings = reactive([]);\n\n setInterval(() => {\n fakeWarning();\n }, 3000);\n\n\n function fakeWarning () {\n activeWarnings.push({\n type: 'severe',\n errorCode: 0,\n errorLevel: 'red',\n \n }\n);\n }\n return { activeWarnings };\n```\n\n```text\nconst { activeWarnings } = useWarning();\n\n watch(activeWarnings, () => {\n \n console.log('called inside on update')\n },{\n immediate:true\n });\n```\n\n```text\nconst { activeWarnings } = useWarning();\n\n watch(()=>activeWarnings, () => {\n \n console.log('called inside on update')\n },{\n immediate:true\n });\n```\n\n```text\nimport { reactive,toRef } from '@vue/composition-api';\n\nexport default function useWarnings () {\n\n const state= reactive({activeWarnings :[]});\n\n setInterval(() => {\n fakeWarning();\n }, 3000);\n\n\n function fakeWarning () {\n state.activeWarnings.push({\n type: 'severe',\n errorCode: 0,\n errorLevel: 'red',\n \n }\n);\n }\n return { activeWarnings : toRef(state,'activeWarnings')};\n```\n\n```text\nconst { activeWarnings } = useWarning();\n\n watch(activeWarnings, () => {\n\n console.log('called inside on update')\n },{\n immediate:true\n });\n```\n\n```text\nactiveWarnings\n```\n\n```text\nimmediate:true\n```\n\n========================================\n\nComments:\n- Thanks a lot this works - interestingly Tony posted this codesandbox.io/s/… which is exactly what I had.","metadata":{"transformedAt":"2026-08-18T18:33:07.909Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":168,"estimatedTokens":755}}995{"id":"stack-62521923","source":"stackoverflow","questionId":62521923,"title":"Gsap not working properly with typescript","tags":["javascript","typescript","vue.js","nuxt.js","gsap"],"text":"Title: Gsap not working properly with typescript\nTags: javascript, typescript, vue.js, nuxt.js, gsap\nSource: Stack Overflow\n\nQuestion:\nI am writing app in nuxt.js with ssr rendering. I have a problem with gsap. I am using typescript and when I am trying to use timeline.staggerTo() method I am getting error that property staggerTo() does not exists on TimelineMax type.\n\nHow I am using gsap:\nI've installed it with yarn add gsap\nthen i've imported TimelineMax from \"gsap\"\n\nthat's all\n\nto() works for example but staggerTo / from no. Probably there is no definition for that. Does anybody knows what I can make in order to fix / workaround it ?\n\nThanks a lot for help some code\n\n```\nimport Vue from \"vue\";\n\nimport { TweenMax, gsap, TimelineMax } from \"gsap\";\n\nexport default Vue.extend({\n mounted() {\n const timeline = new TimelineMax();\n timeline\n .fromTo(\n \".header__subtitle\",\n 1,\n { opacity: 0, translateY: -30 },\n { opacity: 1, translateY: 0 }\n )\n .staggerFrom(); //Property 'staggerFrom' does not exist on type 'TimelineMax'.Vetur(2339)\n }\n});\n```\n\n========================================\n\nTop Answer:\nOkay so in order to create stagger just add\n{stagger: 0.1} in fromVars/ toVars\n\nhave a nice day :)\n\n========================================\n\nCode:\n```text\nimport Vue from \"vue\";\n\nimport { TweenMax, gsap, TimelineMax } from \"gsap\";\n\nexport default Vue.extend({\n mounted() {\n const timeline = new TimelineMax();\n timeline\n .fromTo(\n \".header__subtitle\",\n 1,\n { opacity: 0, translateY: -30 },\n { opacity: 1, translateY: 0 }\n )\n .staggerFrom(); //Property 'staggerFrom' does not exist on type 'TimelineMax'.Vetur(2339)\n }\n});\n```\n\n```js\nimport Vue from \"vue\";\n\nimport { gsap } from \"gsap\";\n\nexport default Vue.extend({\n mounted() {\n const timeline = gsap.timeline()\n .fromTo(\".header__subtitle\", {\n opacity: 0,\n translateY: -30\n }, {\n duration: 1, \n opacity: 1, \n translateY: 0,\n stagger: 0.2\n })\n }\n});\n```\n\n========================================\n\nComments:\n- What doesn't work here?\n- My app won't compile because I am getting error when using staggerTo that it doesn't exists\n- Which version of GSAP are you using? I don't think those methods exist in v3?\n- I'am using 3.3.4\n- I can't seem to find those methods on the GSAP Docs greensock.com/docs/search/stagger\n- I have read similar problem on gsap forum but there wasn't universal solution. This issue was from February so i thought that maybe something have changed until now. Pretty sad if no ;D\n- oh... ok. Maybe there is something else in v3. I am confused now. I am using gsap for 2 hours now andmaybe i dont know about something ;D Thanks a lot. I will read docs\n- Note that the stagger property should be included in the last parameter of a tween (the only one for .from() and .to() but the second one for a .fromTo()).","metadata":{"transformedAt":"2026-08-18T18:33:07.909Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":100,"estimatedTokens":726}}996{"id":"stack-66987028","source":"stackoverflow","questionId":66987028,"title":"Error starting Nuxt.js app: No build files found","tags":["docker","nuxt.js"],"text":"Title: Error starting Nuxt.js app: No build files found\nTags: docker, nuxt.js\nSource: Stack Overflow\n\nQuestion:\n```\n$ npm run start\n\n> app@1.2.3 start /home/app/ui/web\n> nuxt start\n\nFATAL No build files found in /home/app/ui/web/.nuxt/dist/server.\nUse either `nuxt build` or `builder.build()` or start nuxt in development mode.\n```\n\nError happens when starting a Nuxt.js app in a Docker image that was built multi-stage:\n\n- `npm ci && npm run build` inside the build-stage image\n\n- copy the built app `.nuxt`, and also `package.json` and `node_modules` into the run-stage image\n\n**Some details regarding the environment.**\n\nNuxt.js application mode is 'spa'. The missing files are really present inside the final image, no volumes/mounts have been used. OS user names are different between build-stage and run-stage images, however (hopefully) that should not be the case.\n\nNuxt.js 2.12.2, Node.js 14.16.0.\n\n========================================\n\nCode:\n```text\n$ npm run start\n\n> app@1.2.3 start /home/app/ui/web\n> nuxt start\n\nFATAL No build files found in /home/app/ui/web/.nuxt/dist/server.\nUse either `nuxt build` or `builder.build()` or start nuxt in development mode.\n```\n\n```text\nnpm ci && npm run build\n```\n\n```text\n.nuxt\n```\n\n```text\npackage.json\n```\n\n```text\nnode_modules\n```\n\n```text\n> app@1.2.3 start /home/app/ui/web\n> nuxt start\n\nℹ Listening on: http://172.17.0.2:3000/\n```\n\n```text\n/.nuxt\n/node_modules\nnuxt.config.js\npackage.json\n```\n\n```text\n/.nuxt\nnuxt.config.js\npackage.json\nyarn.lock\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nlocalhost\n```\n\n```text\n0.0.0.0\n```\n\n```text\nserver.host\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnpm\n```\n\n```text\nyarn\n```\n\n```text\nyarn install --frozen-lockfile && yarn build\n```\n\n```text\nnode_modules\n```\n\n```text\nyarn install --frozen-lockfile --production=true\n```\n\n```text\nnode_modules\n```\n\n========================================\n\nComments:\n- Can you provide a minimal reproducible example, including your `Dockerfile` and how you're starting the container? In particular, are you overwriting the image's code with volumes or bind mounts?\n- @DavidMaze thank you for your swift answer, I've found the root cause and updated the question with the environment details. Many thanks!","metadata":{"transformedAt":"2026-08-18T18:33:07.909Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":126,"estimatedTokens":559}}997{"id":"stack-66978237","source":"stackoverflow","questionId":66978237,"title":"Error: Cannot find module nuxt.js, why my app don't start?","tags":["javascript","vue.js","nuxt.js"],"text":"Title: Error: Cannot find module nuxt.js, why my app don't start?\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI´ve got this error when try to run npm run dev after installed the dependencies and i cant find why. Help me please.\nI tried some things that found around the internet but none of that worked\n\n```\nplusholidays-app@1.0.0 dev\n> nuxt\n\n\"F\\plusholidays-app\\node_modules\\.bin\\\" no se reconoce como un comando interno o externo,\nprograma o archivo por lotes ejecutable.\ninternal/modules/cjs/loader.js:883\n throw err;\n ^\n\nError: Cannot find module 'C:\\Users\\anyel\\Documents\\src\\nuxt\\bin\\nuxt.js'\n at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)\n at Function.Module._load (internal/modules/cjs/loader.js:725:27)\n at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)\n at internal/main/run_main_module.js:17:47 {\n code: 'MODULE_NOT_FOUND',\n requireStack: []\n}\n```\n\nHere is the package.json\n\n```\n{\n \"name\": \"plusholidays-app\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"@nuxtjs/axios\": \"^5.13.1\",\n \"@nuxtjs/moment\": \"^1.6.1\",\n \"@nuxtjs/proxy\": \"^2.1.0\",\n \"apexcharts\": \"^3.26.0\",\n \"core-js\": \"^3.9.0\",\n \"js-cookie\": \"^2.2.1\",\n \"leaflet\": \"^1.7.1\",\n \"lodash.clonedeep\": \"^4.5.0\",\n \"nuxt\": \"^2.15.2\",\n \"nuxt-i18n\": \"^6.21.1\",\n \"vue-advanced-cropper\": \"^1.3.2\",\n \"vue-apexcharts\": \"^1.6.0\",\n \"vue-the-mask\": \"^0.11.1\",\n \"vue2-leaflet\": \"^2.6.0\"\n },\n \"devDependencies\": {\n \"@nuxtjs/vuetify\": \"^1.11.3\",\n \"babel-eslint\": \"^10.1.0\",\n \"eslint\": \"^7.20.0\",\n \"eslint-config-prettier\": \"^8.1.0\",\n \"eslint-loader\": \"^4.0.2\",\n \"eslint-plugin-prettier\": \"^3.3.1\",\n \"eslint-plugin-vue\": \"^7.6.0\",\n \"prettier\": \"^2.2.1\"\n }\n}\n```\n\nI really want to understand what is going on here, but I'm at a bit of a loss as to where to look next. Any suggestions?\n\n========================================\n\nTop Answer:\nTry and install nuxt-start package.\n\nThis is what I used to solve a very similar challenge (On Production)\n\n========================================\n\nCode:\n```text\nplusholidays-app@1.0.0 dev\n> nuxt\n\n\"F\\plusholidays-app\\node_modules\\.bin\\\" no se reconoce como un comando interno o externo,\nprograma o archivo por lotes ejecutable.\ninternal/modules/cjs/loader.js:883\n throw err;\n ^\n\nError: Cannot find module 'C:\\Users\\anyel\\Documents\\src\\nuxt\\bin\\nuxt.js'\n at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)\n at Function.Module._load (internal/modules/cjs/loader.js:725:27)\n at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)\n at internal/main/run_main_module.js:17:47 {\n code: 'MODULE_NOT_FOUND',\n requireStack: []\n}\n```\n\n```text\n{\n \"name\": \"plusholidays-app\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"@nuxtjs/axios\": \"^5.13.1\",\n \"@nuxtjs/moment\": \"^1.6.1\",\n \"@nuxtjs/proxy\": \"^2.1.0\",\n \"apexcharts\": \"^3.26.0\",\n \"core-js\": \"^3.9.0\",\n \"js-cookie\": \"^2.2.1\",\n \"leaflet\": \"^1.7.1\",\n \"lodash.clonedeep\": \"^4.5.0\",\n \"nuxt\": \"^2.15.2\",\n \"nuxt-i18n\": \"^6.21.1\",\n \"vue-advanced-cropper\": \"^1.3.2\",\n \"vue-apexcharts\": \"^1.6.0\",\n \"vue-the-mask\": \"^0.11.1\",\n \"vue2-leaflet\": \"^2.6.0\"\n },\n \"devDependencies\": {\n \"@nuxtjs/vuetify\": \"^1.11.3\",\n \"babel-eslint\": \"^10.1.0\",\n \"eslint\": \"^7.20.0\",\n \"eslint-config-prettier\": \"^8.1.0\",\n \"eslint-loader\": \"^4.0.2\",\n \"eslint-plugin-prettier\": \"^3.3.1\",\n \"eslint-plugin-vue\": \"^7.6.0\",\n \"prettier\": \"^2.2.1\"\n }\n}\n```\n\n```text\nC:\\Users\\anyel\\Documents\\src\\nuxt\\bin\\nuxt.js\n```\n\n```text\nscript: './node_modules/nuxt/bin/nuxt.js',\n```\n\n========================================\n\nComments:\n- can you your directory structure? Nuxt should be in a node_modules folder which should be generated during npm install.\n- Already solved it, thank you.\n- Edit your question or answer your own question with an answer.\n- It didn't work but thank you, i already fixed it, it was a problem with the path. Just moved the project to another folder and it magically worked.\n- could you please describe in detail how you fixed it. I am facing same problem.","metadata":{"transformedAt":"2026-08-18T18:33:07.909Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":158,"estimatedTokens":1089}}998{"id":"stack-65967612","source":"stackoverflow","questionId":65967612,"title":"TailwindCSS Dark mode not working in Nuxt.js","tags":["javascript","css","typescript","nuxt.js","tailwind-css"],"text":"Title: TailwindCSS Dark mode not working in Nuxt.js\nTags: javascript, css, typescript, nuxt.js, tailwind-css\nSource: Stack Overflow\n\nQuestion:\nI've been at this for a couple of days now and still can't seem to get this working. I'm trying to get the whole dark mode going with Tailwind CSS in Nuxt.js.\n\nI think it may be an issue with the CSS setup and not the TypeScript side as I have a toggle that switches the `` class to light and dark.\n\nAs a reference, I've been trying to copy Fayazara's work which you can find here.\n\nEnv:\n\n- Windows 10 Pro\n\n- Node 14.15.4\n\n- NPM 6.14.10\n\n- Nuxt.js 2.14.12\n\n- TailwindCSS 2.0.2\n\nHere are some of the config files:\n\n**nuxt.config.js:**\n\n```\nexport default {\n head: {\n // meta stuff\n },\n purgeCSS: { \n whitelist: ['dark-mode'], \n },\n components: true,\n buildModules: [\n '@nuxt/typescript-build',\n '@nuxtjs/tailwindcss',\n '@nuxtjs/color-mode', \n ],\n colorMode: {\n classSuffix: \"\"\n },\n ...\n ...\n}\n```\n\n**tailwind.config.js:**\n\n```\nmodule.exports = {\n theme: {\n darkSelector: '.dark-mode',\n },\n variants: {\n backgroundColor: ['dark', 'dark-hover', 'dark-group-hover', 'dark-even', 'dark-odd', 'hover', 'responsive'],\n borderColor: ['dark', 'dark-focus', 'dark-focus-within', 'hover', 'responsive'],\n textColor: ['dark', 'dark-hover', 'dark-active', 'hover', 'responsive']\n },\n plugins: [\n require('tailwindcss-dark-mode')()\n ]\n}\n```\n\n**~/assets/css/tailwind.css:**\n\n```\n@import 'tailwindcss/base';\n@import 'tailwindcss/components';\n@import 'tailwindcss/utilities';\n```\n\nI have this in my settings page `Settings\n\n` which stays blue even with the toggle\n\nI uploaded my project to GitHub for all the other files\n\nThanks to anyone that helps :)\n\n========================================\n\nCode:\n```js\nexport default {\n head: {\n // meta stuff\n },\n purgeCSS: { \n whitelist: ['dark-mode'], \n },\n components: true,\n buildModules: [\n '@nuxt/typescript-build',\n '@nuxtjs/tailwindcss',\n '@nuxtjs/color-mode', \n ],\n colorMode: {\n classSuffix: \"\"\n },\n ...\n ...\n}\n```\n\n```js\nmodule.exports = {\n theme: {\n darkSelector: '.dark-mode',\n },\n variants: {\n backgroundColor: ['dark', 'dark-hover', 'dark-group-hover', 'dark-even', 'dark-odd', 'hover', 'responsive'],\n borderColor: ['dark', 'dark-focus', 'dark-focus-within', 'hover', 'responsive'],\n textColor: ['dark', 'dark-hover', 'dark-active', 'hover', 'responsive']\n },\n plugins: [\n require('tailwindcss-dark-mode')()\n ]\n}\n```\n\n```css\n@import 'tailwindcss/base';\n@import 'tailwindcss/components';\n@import 'tailwindcss/utilities';\n```\n\n```text\n<hmtl></html>\n```\n\n```text\n<p class=\"bg-blue-500 dark:bg-red-500\">Settings</p>\n```\n\n```text\n// tailwind.config.js\nmodule.exports = {\n darkMode: 'class',\n}\n```\n\n```text\n<template>\n <div class=\"dark\">\n <Navigation />\n <Nuxt />\n </div>\n</template>\n\n<script lang=\"ts\">\nimport Vue from 'vue'\nimport Navigation from '~/components/Navigation.vue'\nexport default Vue.extend({\n name: 'Default',\n components: {\n Navigation\n }\n})\n</script>\n```\n\n```text\ntailwind.config.js\n```\n\n```text\ndark\n```\n\n```text\nlayouts/default\n```\n\n```text\n<div class=\"dark\">\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.909Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":180,"estimatedTokens":808}}999{"id":"stack-59223470","source":"stackoverflow","questionId":59223470,"title":"Is it possible to apply 'label-position: top' to only one form-item in Element UI","tags":["vue.js","nuxt.js","element-ui"],"text":"Title: Is it possible to apply 'label-position: top' to only one form-item in Element UI\nTags: vue.js, nuxt.js, element-ui\nSource: Stack Overflow\n\nQuestion:\nI'm building web app with Nuxt and Element UI.\nI have a question about form component provided Element UI.\n\nThis is the screenshot of my web app.\n\nhttps://gyazo.com/4cf04aa85d0a9bb9a4f2d09a693bbdd6\n\nAnd there are two el-form-item components(Form Item A and Form Item B).\n\nI would like to apply 'label-position: left' to 'Form Item B', but not 'Form Item A'.\nHowever, there is a problem I already know.\n\n[Problem]\n\n- el-form-item component doesn't have 'label-position' attribute, so if I would like to apply it, I have to apply it to el-form component, but if I do it, all el-form-item components in el-from are applied.\n\nHow can I fix it?\n\nThis is my code.\n\n```\n\n \n \n \n \n \n \n \n \n \n \n \n\n export default {\n data() {\n return {\n form: {\n name: '',\n region: '',\n }\n }\n },\n }\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <el-form ref=\"form\" :model=\"form\" label-width=\"120px\" label-position=\"left\">\n <el-form-item label=\"Form Item A\">\n <el-input v-model=\"form.name\"></el-input>\n </el-form-item>\n <el-form-item label=\"Form Item B\">\n <el-select v-model=\"form.region\" placeholder=\"please select your zone\">\n <el-option label=\"Zone one\" value=\"shanghai\"></el-option>\n <el-option label=\"Zone two\" value=\"beijing\"></el-option>\n </el-select>\n </el-form-item>\n </el-form>\n</template>\n\n<script>\n export default {\n data() {\n return {\n form: {\n name: '',\n region: '',\n }\n }\n },\n }\n</script>\n```\n\n```js\nvar Main = {\n data() {\n return {\n form: {\n name: '',\n region: ''\n }\n };\n }\n}\nvar Ctor = Vue.extend(Main)\nnew Ctor().$mount('#app')\n```\n\n```css\n@import url(\"//unpkg.com/element-ui@2.13.0/lib/theme-chalk/index.css\");\n.el-form-item--label-top .el-form-item__label {\n width: auto!important;\n float: none;\n display: inline-block;\n text-align: left;\n padding: 0 0 10px;\n}\n\n.el-form-item--label-top .el-form-item__content {\n margin-left: 0!important;\n}\n```\n\n```html\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js\"></script>\n<script src=\"//unpkg.com/element-ui@2.13.0/lib/index.js\"></script>\n\n<div id=\"app\">\n <el-form ref=\"form\" :model=\"form\" label-width=\"120px\" label-position=\"left\">\n <el-form-item label=\"Form Item A\" class=\"el-form-item--label-top\">\n <el-input v-model=\"form.name\"></el-input>\n </el-form-item>\n <el-form-item label=\"Form Item B\">\n <el-select v-model=\"form.region\" placeholder=\"please select your zone\">\n <el-option label=\"Zone one\" value=\"shanghai\"></el-option>\n <el-option label=\"Zone two\" value=\"beijing\"></el-option>\n </el-select>\n </el-form-item>\n </el-form>\n</div>\n```\n\n```text\nel-form-item\n```\n\n```text\n'label-position' attribute\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.909Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":140,"estimatedTokens":731}}1000{"id":"stack-59677141","source":"stackoverflow","questionId":59677141,"title":"composition api doesn't work with Nuxt-TS","tags":["javascript","vue.js","nuxt.js"],"text":"Title: composition api doesn't work with Nuxt-TS\nTags: javascript, vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nCreated nuxt app using `npx create-nuxt-app`. Followed documentation at https://typescript.nuxtjs.org, however i have an issue using `@vue/composition-api`:\n\nexample component.vue:\n\n```\n\n \n {{ msg }}\n \n\nimport { createComponent, ref } from '@vue/composition-api'\n\nexport default createComponent({\n setup() {\n const msg = ref('hello')\n\n return {\n msg\n }\n }\n})\n\n```\n\nDoesn't work, throws an error \"Property or method \"msg\" is not defined on the instance but referenced during render.\" because it doesn't see my `ref`. I've added composition API as plugin in \"plugins/composition-api.ts\":\n\n```\nimport Vue from 'vue'\nimport VueCompositionApi from '@vue/composition-api'\n\nVue.use(VueCompositionApi)\n```\n\nThen in nuxt.config.ts:\n\n`plugins: ['@/plugins/composition-api']`\n\n========================================\n\nCode:\n```text\n<template>\n <div>\n {{ msg }}\n </div>\n</template>\n\n<script lang=\"ts\">\nimport { createComponent, ref } from '@vue/composition-api'\n\nexport default createComponent({\n setup() {\n const msg = ref('hello')\n\n return {\n msg\n }\n }\n})\n</script>\n```\n\n```text\nimport Vue from 'vue'\nimport VueCompositionApi from '@vue/composition-api'\n\nVue.use(VueCompositionApi)\n```\n\n```text\nnpx create-nuxt-app\n```\n\n```text\n@vue/composition-api\n```\n\n```text\nref\n```\n\n```text\nplugins: ['@/plugins/composition-api']\n```\n\n```text\nnpm i -S @nuxt/typescript-runtime\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.909Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":93,"estimatedTokens":375}}1001{"id":"stack-59107674","source":"stackoverflow","questionId":59107674,"title":"Component mounted but template tags not rendered in production environment (but rendered in development): Nuxtjs Vuejs Vuetifyjs Rollupjs","tags":["vuejs2","vue-component","vuetify.js","nuxt.js","rollupjs"],"text":"Title: Component mounted but template tags not rendered in production environment (but rendered in development): Nuxtjs Vuejs Vuetifyjs Rollupjs\nTags: vuejs2, vue-component, vuetify.js, nuxt.js, rollupjs\nSource: Stack Overflow\n\nQuestion:\n### Synonypsis\n\nPlease allow me to explain what is going on. I did the following:\n\n- made custom Vue components using Vuetify components\n\n- made a custom Vue component using these Vuetify components and the custom components from (1)\n\n- used rollupjs to bundle these components together\n\n- published these components on npm\n\n- deployed to GitLab pages an example of the \"main\" component from (2), using the local version of the component (rather than the one from npm)\n\n- made a new nuxt project\n\n- dockerized it\n\n- I install my package from (4) and use it\n\n- deployed this test repository on GitLab pages\n\nWhat happened that inspired this post:\n1. On the component's repository GitLab page (step 5 from above), the component is both rendered and mounted\n2. On the test repository GitLab page (step 9 from above), the component is **mounted** but the template is not rendered (e.g. it is like its template tag ``)\n3. In the test repository, using docker in development everything is ok\n4. In the test repository the component is mounted but not rendered\n\n### Details\n\nThe offending component is called `VRecordsTable` from the package `valpha`. It is a wrapper of the Vuetify component `VDataTable` and adds custom slots, logic and a few other components. (links below). \n\nThe component is mounted in production (the data is there, reactive via vuex store also works), but the html is as follows:\n\n```\n\n```\n\nHere is an image from the linked test repo below showing what I mean:\n\nhttps://i.sstatic.net/I6LNe.png\n\nNotice, the component is mounted with data all there, but unlike all the other components, it doesn't have a drop down to see the internal components. \n\nI'm not sure where I went wrong, at the bottom of this post is quick links to the repo of both the component and the test repo, in addition to useful files like `rollup.config.js`\n\n### Useful commands\n\nFor docker in the test repo please use:\n\n```\n# dev\ndocker-compose -f docker-compose.development.yml build\ndocker-compose -f docker-compose.development.yml up\ndocker-compose -f docker-compose.development.yml down\n\n# prod\ndocker-compose -f docker-compose.production.yml build\ndocker-compose -f docker-compose.production.yml up\ndocker-compose -f docker-compose.production.yml down\n```\n\n### Links\n\ncomponent repo:\n\n- npm package of component\n\n- gitlab page of the component\n\n- git repository of component\n\n- rollup.config.js of component\n\n- package.json file of component\n\n- nuxt.config.js of component's repo\n\n- entry.js used by rollup.config.js\n\n- offending component `VRecordsTable`\n\ntest repo\n\n- gitlab page of the test repo\n\n- test repo\n\n### Hunchs\n\n- something with `npm run start` vs `npm run dev` / how nuxt is built is the issue?\n\n- something with how I configured rollup.config.js is the issue?\n\n- something with vuetify is the issue?\n\n========================================\n\nCode:\n```html\n<v-col><v-data-table page=\"0\" items-per-page=\"5\" items=\"record1,record2,record3,record4,record5,record6,record7,record8,record9\" calculate-widths=\"true\" fixed-header=\"\" headers-length=\"7\"></v-data-table></v-col>\n```\n\n```sh\n# dev\ndocker-compose -f docker-compose.development.yml build\ndocker-compose -f docker-compose.development.yml up\ndocker-compose -f docker-compose.development.yml down\n\n# prod\ndocker-compose -f docker-compose.production.yml build\ndocker-compose -f docker-compose.production.yml up\ndocker-compose -f docker-compose.production.yml down\n```\n\n```text\n<my-component></my-component>\n```\n\n```text\nVRecordsTable\n```\n\n```text\nvalpha\n```\n\n```text\nVDataTable\n```\n\n```text\nrollup.config.js\n```\n\n```text\nVRecordsTable\n```\n\n```text\nnpm run start\n```\n\n```text\nnpm run dev\n```\n\n```html\n<template>\n <v-card>\n <v-card-title>...</v-card-title>\n <v-card-text>...</v-card-text>\n </v-card>\n</template>\n\n<script>\n import { VCard, VCardText, VCardTitle } from 'vuetify/lib'\n\n export default {\n components: {\n VCard,\n VCardText,\n VCardTitle,\n }\n }\n</script>\n```\n\n```text\nvalpha\n```\n\n```text\ntreeShake: false\n```\n\n========================================\n\nComments:\n- 1st thank you. Whenever I begin to think I am starting to know what I’m doing, it turns out I don’t :p because I am still learning could you please provide the changes to the configuration for valpha and how to set treeshaking? I’ve tried using vuetify a la carte in nuxt and always mess it up and struggle. If you do I’ll add a bounty and reward you\n- So I added the relevant components and tried `npm run r:build` in valpha, the result was that esm and umd build ok (complained about circular dependencies from vuetify, though) and for `unpkg` (creates `.min.js`) i get `[!] TypeError: Cannot read property 'length' of undefined` where `TypeError: Cannot read property 'length' of undefined: at ~/Projects/valpha/node_modules/rollup/dist/rollup.js:14802:5‌​5`\n- Well it seems the `.min` isn't needed... so your solution works (although if you could figure out the `.min` I believe it would be a more encompassing answer. Also, it may be worth adding a specific documentation page for those building components on top of vuetify ^^.\n- one more up question, in a nuxt project using vuetify, `vskeletonloader` doesn't show in production, but all the other components do. Is this related to treeshaking somehow? despite everything else rendering?\n- That's probably from `rollup-plugin-uglify-es` which hasn't been updated since 2017, you should use terser instead. > vskeletonloader doesn't show in production I don't know, could be related to SSR. If you disable silent mode you'll get more information.\n- If you don't mind could you help with an adjacent issue stackoverflow.com/questions/59158339/…","metadata":{"transformedAt":"2026-08-18T18:33:07.963Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":190,"estimatedTokens":1485}}1002{"id":"stack-62520976","source":"stackoverflow","questionId":62520976,"title":"Invariant Violation: Expecting a parsed GraphQL document","tags":["graphql","nuxt.js","apollo","vue-apollo"],"text":"Title: Invariant Violation: Expecting a parsed GraphQL document\nTags: graphql, nuxt.js, apollo, vue-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm getting the following error despite the mutation being wrapped in the `gql` tag:\n\n```\nInvariant Violation: Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\n```\n\nThis issue is only caused by the mutation code below, I have a query that works.\n\nCode:\n\n```\n\nimport gql from 'graphql-tag'\n\nexport default {\n apollo: {\n createTask: {\n mutation: gql`\n mutation Task(\n $taskName: String!\n $taskDesc: String!\n ) {\n setSession(\n taskName: $taskName\n taskDesc: $taskDesc\n ) {\n id\n taskName\n }\n }\n `,\n variables() {\n return {\n taskName: this.res.data.task_name,\n taskDesc: this.res.data.task_description,\n }\n },\n },\n },\n data() {\n return {\n createTask: '',\n }\n },\n}\n\n```\n\n========================================\n\nTop Answer:\nI had this problem recently and it was because of an issue with an async import\nI am using vue-apollo\n\n```\nasync account () {\n return {\n query: (await import('src/modules/accounts/graphql/accounts.list.query.gql')),\n......\n```\n\nI just had to replace that import with a require and it was happy again.\n\n```\nasync account () {\n return {\n query: require('src/modules/accounts/graphql/accounts.list.query.gql'),\n......\n```\n\n========================================\n\nCode:\n```text\nInvariant Violation: Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql\n```\n\n```js\n<script>\nimport gql from 'graphql-tag'\n\nexport default {\n apollo: {\n createTask: {\n mutation: gql`\n mutation Task(\n $taskName: String!\n $taskDesc: String!\n ) {\n setSession(\n taskName: $taskName\n taskDesc: $taskDesc\n ) {\n id\n taskName\n }\n }\n `,\n variables() {\n return {\n taskName: this.res.data.task_name,\n taskDesc: this.res.data.task_description,\n }\n },\n },\n },\n data() {\n return {\n createTask: '',\n }\n },\n}\n<script>\n```\n\n```text\ngql\n```\n\n```text\nexport default {\n apollo: {\n someQuery: gql`...`,\n }\n}\n```\n\n```text\nexport default {\n methods: {\n createTask() {\n this.$apollo.mutate({\n mutation: gql`...`,\n variables: {...},\n // other options\n }).then(result => {\n // do something with the result\n })\n }\n }\n}\n```\n\n```text\napollo\n```\n\n```text\nthis.$apollo.mutate\n```\n\n```js\nasync account () {\n return {\n query: (await import('src/modules/accounts/graphql/accounts.list.query.gql')),\n......\n```\n\n```js\nasync account () {\n return {\n query: require('src/modules/accounts/graphql/accounts.list.query.gql'),\n......\n```\n\n========================================\n\nComments:\n- This code results in the error: `Invariant Violation: Must contain a query definition.`\n- The mutation in my question is just an example, I do wanna run it when the user is redirected to a certain page, in my case the user would be sent to `website.com/token?code=CODE` and then I'd use the `code` to get a JWT token that I would store using apollo. I tried using this way but I can't seem to be able to call the method within `export default` using `createTask()`. Is there a way to call methods within `export default`?\n- It sounds like you want to use a lifecycle hook like mounted and call `this.$apollo.mutate` from there. That said, since you're using SSR, you might consider doing this on the server-side before your page is even rendered.\n- I'm still new to web development and using nuxt, I'm gonna try to understand how to do that, thanks.","metadata":{"transformedAt":"2026-08-18T18:33:07.963Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":177,"estimatedTokens":951}}1003{"id":"stack-59646672","source":"stackoverflow","questionId":59646672,"title":"Deploying Laravel and Nuxt.js application. Combine them, or deploy separately?","tags":["php","laravel","server-side-rendering","nuxt.js"],"text":"Title: Deploying Laravel and Nuxt.js application. Combine them, or deploy separately?\nTags: php, laravel, server-side-rendering, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have been developing a website that uses Laravel (v6) on the backend, and Nuxt.js (v2) on the frontend. The idea was for laravel to act as an api & oauth2 server, that also server side rendered the Nuxt.js app. From my research, it seemed like this was not only a common route, but not too much hassle to implement. \n\nWhile developing, I have kept the backend and frontend as completely separate projects with their own git repos and all that jazz. This is my first time deploying/developing a project like this, where there are two completely applications for the backend and frontend, so all this is very new and a little challenging at times. Now when it came time to deploy them, I always imagined that I would somehow merge the projects and that I would be able to setup Laravel to server side render the Nuxt.js app. However, I am now at that stage and trying to merge them with great difficulty. \n\nCurrently I am using the \"laravel-nuxt\" composer package and \"laravel-nuxt\" npm package in an attempt to connect the projects in one repo. However, I am having difficulty doing this. I've searched far and wide for a good resource on this process and have yet to find one that explains the process thoroughly. I even purchased a course on Udemy on the topic only to find out they didn't merge the projects! They deployed Nuxt to firebase and didn't even cover how the deployment of laravel.\n\nAnyway, this is my question(s): should or could I keep the projects separate and have 2 completely separate deployments? Or rather, if I keep them separate, how do I deploy nuxt in a way that still gets server side rendered? To me it doesn't matter if they are separate or together, but the most important part is that the nuxt app utlitlizes SSR (server side rendering) for SEO purposes. So am I on the right track? Should I keep these projects separate or should I continue trying to merge them? \n\nSorry if this is unclear, I am rather frustrated and kind of losing my mind. I would really appreciate any feedback or point in the right direction. Thank you for your time in reading this, and I otherwise hope you have a good day :)\n\n========================================\n\nCode:\n```text\nnpm start\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.963Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":21,"estimatedTokens":594}}1004{"id":"stack-62134935","source":"stackoverflow","questionId":62134935,"title":"How can I pass a variable value from a \"page\" to \"layout\" in Nuxt JS?","tags":["vue.js","nuxt.js"],"text":"Title: How can I pass a variable value from a \"page\" to \"layout\" in Nuxt JS?\nTags: vue.js, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm a beginner in VUE and donnow this one is the correct syntax. I need the variable {{name}} to be set from a page. Which means I need to change the value of the variable page to page. How can I achieve that? Help me guys. \n\nMy \"Layout\" Code is like below -\n\n```\n\n \n {{ name }}\n \n \n \n \n \n \n\nexport default {\n props: ['name']\n}\n\n```\n\nAnd my \"Page\" code is following -\n\n```\n\n Welcome\n\nexport default {\n layout: 'login',\n data: function() {\n return {\n name: 'Victor'\n }\n }\n}\n\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div class=\"login-page\">\n <div class=\"col1\">{{ name }}</div>\n <div class=\"col2\">\n <div class=\"content-box\">\n <nuxt />\n </div>\n </div>\n </div>\n</template>\n<script>\nexport default {\n props: ['name']\n}\n</script>\n```\n\n```text\n<template>\n <div>Welcome</div>\n</template>\n\n<script>\nexport default {\n layout: 'login',\n data: function() {\n return {\n name: 'Victor'\n }\n }\n}\n</script>\n```\n\n```text\n// page.js file in the store folder\nconst state = {\n name: ''\n}\n\nconst mutations = {\n setName(state, name) {\n state.name = name\n }\n}\n\nconst getters = {\n getName: (state) => state.name\n}\n\nexport default {\n state,\n mutations,\n getters\n}\n```\n\n```text\n// Page.vue page\n<template>\n <div>Welcome</div>\n</template>\n<script>\n export default {\n layout: 'login',\n created() {\n this.$store.commit('page/setName', 'Hello')\n },\n }\n</script>\n```\n\n```text\n<template>\n <div class=\"login-page\">\n <div class=\"col1\">{{ name }}</div>\n <div class=\"col2\">\n <div class=\"content-box\">\n <nuxt />\n </div>\n </div>\n </div>\n</template>\n<script>\nexport default {\n computed: {\n name() {\n return this.$store.getters['page/getName']\n }\n }\n}\n</script>\n```\n\n```text\nconst state = { name: '', title: '', subtitle: ''}\n```\n\n```text\nconst mutations = {\n setName(state, name) {\n state.name = name\n },\n setPageTitle(state, title) {\n state.title = title\n },\n setPageSubtitle(state, subtitle) {\n state.subtitle = subtitle\n },\n}\n```\n\n```text\nthis.$store.commit('page/setPageTitle', 'A page title')\n```\n\n```text\ncomputed: {\n title() {\n // you can get the variable state without a getter\n // ['page'] is the module name, nuxt create the module name\n // using the file name page.js\n return this.$store.state['page'].title\n }\n}\n```\n\n```text\nsetPageName\n```\n\n========================================\n\nComments:\n- Hi....Thanks. It's worked. As a beginner I have a doubt. For another variable, am I need to create a separate file in store folder?\n- Or else please tell me how I can pass multiple variables from a “page” to “layout” here?\n- Hi! I added additional information about your question in the answer :D.","metadata":{"transformedAt":"2026-08-18T18:33:07.964Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":184,"estimatedTokens":718}}1005{"id":"stack-63710114","source":"stackoverflow","questionId":63710114,"title":"Rails API Omniauth","tags":["ruby-on-rails","vue.js","nuxt.js","omniauth"],"text":"Title: Rails API Omniauth\nTags: ruby-on-rails, vue.js, nuxt.js, omniauth\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement Omniauth with Devise in Rails API with NuxtJS framework.\n\nI did auth module connexion and user account creation with Omniauth method but i would like understand how redirect the user afer signin/signup, i am Rails developer and beginner with NuxtJS.\n\n**BACKEND**\n\nUser model oauth registration method:\n\n```\ndef self.from_facebook(auth)\n where(uid: auth.uid, provider: auth.provider).first_or_create do |user|\n user.email = auth.info.email\n user.first_name = auth.info.first_name\n user.last_name = auth.info.last_name\n user.password = Devise.friendly_token[0, 20]\n user.provider = auth.provider\n user.uid = auth.uid\n Client.create(user: user)\n end\nend\n```\n\nRegistration controller:\n\n```\n# frozen_string_literal: true\n\nmodule Overrides\nclass RegistrationsController Omniauth callbacks controller:\n\n```\ndef facebook\n@user = User.from_facebook(request.env[\"omniauth.auth\"])\n\n# NOTE: redirection here\nend\n```\n\n**FRONTEND**\n\nStategie:\n\n```\nfacebook: {\n client_id: 'CLIENT_ID',\n userinfo_endpoint: 'https://graph.facebook.com/v2.12/me?fields=about,name,picture{url},email,birthday',\n redirect_uri:'http://localhost:3000/omniauth/facebook',\n scope: ['public_profile', 'email', 'user_birthday']\n }\n```\n\nLogin method:\n\n```\nfacebookLogin () {\n this.$auth.loginWith('facebook')\n .then((response) => {\n this.$toast.success({\n title: 'Connexion réussie',\n message: 'Vous vous êtes bien connecté.',\n position: 'bottom center',\n timeOut: 3000\n })\n })\n .catch(() => {\n this.$toast.error({\n title: 'Erreur',\n message: 'L\\'email ou le mot de passe ne sont pas valides. Vérifiez votre saisie.',\n position: 'bottom center',\n timeOut: 8000\n })\n })\n .finally(() => this.$wait.end('signing in'))\n }\n```\n\n========================================\n\nCode:\n```text\ndef self.from_facebook(auth)\n where(uid: auth.uid, provider: auth.provider).first_or_create do |user|\n user.email = auth.info.email\n user.first_name = auth.info.first_name\n user.last_name = auth.info.last_name\n user.password = Devise.friendly_token[0, 20]\n user.provider = auth.provider\n user.uid = auth.uid\n Client.create(user: user)\n end\nend\n```\n\n```text\n# frozen_string_literal: true\n\nmodule Overrides\nclass RegistrationsController < DeviseTokenAuth::ApplicationController\nbefore_action :set_user_by_token, only: [:destroy, :update]\nbefore_action :validate_sign_up_params, only: :create\nbefore_action :validate_account_update_params, only: :update\nskip_after_action :update_auth_header, only: [:create, :destroy]\n\ndef create\n build_resource\n\n unless @resource.present?\n raise DeviseTokenAuth::Errors::NoResourceDefinedError,\n \"#{self.class.name} #build_resource does not define @resource,\"\\\n ' execution stopped.'\n end\n\n # give redirect value from params priority\n @redirect_url = params.fetch(\n :confirm_success_url,\n DeviseTokenAuth.default_confirm_success_url\n )\n\n # success redirect url is required\n if confirmable_enabled? && !@redirect_url\n return render_create_error_missing_confirm_success_url\n end\n\n # if whitelist is set, validate redirect_url against whitelist\n return render_create_error_redirect_url_not_allowed if blacklisted_redirect_url?\n\n # override email confirmation, must be sent manually from ctrl\n resource_class.set_callback('create', :after, :send_on_create_confirmation_instructions)\n resource_class.skip_callback('create', :after, :send_on_create_confirmation_instructions)\n\n if @resource.respond_to? :skip_confirmation_notification!\n # Fix duplicate e-mails by disabling Devise confirmation e-mail\n @resource.skip_confirmation_notification!\n end\n\n if @resource.save\n if params[:farmer]\n Farmer.create(\n user: @resource\n )\n else\n Client.create(\n user: @resource\n )\n end\n\n yield @resource if block_given?\n\n unless @resource.confirmed?\n # user will require email authentication\n @resource.send_confirmation_instructions({\n client_config: params[:config_name],\n redirect_url: @redirect_url\n })\n end\n\n if active_for_authentication?\n # email auth has been bypassed, authenticate user\n @client_id, @token = @resource.create_token\n @resource.save!\n update_auth_header\n end\n\n render_create_success\n else\n clean_up_passwords @resource\n render_create_error\n end\nend\n\ndef update\n if @resource\n if @resource.send(resource_update_method, account_update_params)\n yield @resource if block_given?\n render_update_success\n else\n render_update_error\n end\n else\n render_update_error_user_not_found\n end\nend\n\ndef destroy\n if @resource\n @resource.destroy\n yield @resource if block_given?\n render_destroy_success\n else\n render_destroy_error\n end\nend\n\ndef sign_up_params\n params.permit(\n :first_name,\n :last_name,\n :email,\n :cellphone,\n :phone,\n :password,\n :password_confirmation,\n :birthdate\n )\nend\n\ndef account_update_params\n params.permit(*params_for_resource(:account_update))\nend\n\nprotected\n\ndef build_resource\n @resource = resource_class.new(sign_up_params)\n @resource.provider = provider\n\n # honor devise configuration for case_insensitive_keys\n if resource_class.case_insensitive_keys.include?(:email)\n @resource.email = sign_up_params[:email].try(:downcase)\n else\n @resource.email = sign_up_params[:email]\n end\nend\n\ndef render_create_error_missing_confirm_success_url\n response = {\n status: 'error',\n data: resource_data\n }\n message = I18n.t('devise_token_auth.registrations.missing_confirm_success_url')\n render_error(422, message, response)\nend\n\ndef render_create_error_redirect_url_not_allowed\n response = {\n status: 'error',\n data: resource_data\n }\n message = I18n.t('devise_token_auth.registrations.redirect_url_not_allowed', redirect_url: @redirect_url)\n render_error(422, message, response)\nend\n\ndef render_create_success\n render json: {\n status: 'success',\n data: resource_data\n }\nend\n\ndef render_create_error\n render json: {\n status: 'error',\n data: resource_data,\n errors: resource_errors\n }, status: 422\nend\n\ndef render_update_success\n render json: {\n status: 'success',\n data: resource_data\n }\nend\n\ndef render_update_error\n render json: {\n status: 'error',\n errors: resource_errors\n }, status: 422\nend\n\ndef render_update_error_user_not_found\n render_error(404, I18n.t('devise_token_auth.registrations.user_not_found'), status: 'error')\nend\n\ndef render_destroy_success\n render json: {\n status: 'success',\n message: I18n.t('devise_token_auth.registrations.account_with_uid_destroyed', uid: @resource.uid)\n }\nend\n\ndef render_destroy_error\n render_error(404, I18n.t('devise_token_auth.registrations.account_to_destroy_not_found'), status: 'error')\nend\n\nprivate\n\ndef resource_update_method\n if DeviseTokenAuth.check_current_password_before_update == :attributes\n 'update_with_password'\n elsif DeviseTokenAuth.check_current_password_before_update == :password && account_update_params.key?(:password)\n 'update_with_password'\n elsif account_update_params.key?(:current_password)\n 'update_with_password'\n else\n 'update_attributes'\n end\nend\n\ndef validate_sign_up_params\n validate_post_data sign_up_params, I18n.t('errors.messages.validate_sign_up_params')\nend\n\ndef validate_account_update_params\n validate_post_data account_update_params, I18n.t('errors.messages.validate_account_update_params')\nend\n\ndef validate_post_data which, message\n render_error(:unprocessable_entity, message, status: 'error') if which.empty?\nend\n\ndef active_for_authentication?\n !@resource.respond_to?(:active_for_authentication?) || @resource.active_for_authentication?\nend\nend\nend\n```\n\n```text\ndef facebook\n@user = User.from_facebook(request.env[\"omniauth.auth\"])\n\n# NOTE: redirection here\nend\n```\n\n```text\nfacebook: {\n client_id: 'CLIENT_ID',\n userinfo_endpoint: 'https://graph.facebook.com/v2.12/me?fields=about,name,picture{url},email,birthday',\n redirect_uri:'http://localhost:3000/omniauth/facebook',\n scope: ['public_profile', 'email', 'user_birthday']\n }\n```\n\n```text\nfacebookLogin () {\n this.$auth.loginWith('facebook')\n .then((response) => {\n this.$toast.success({\n title: 'Connexion réussie',\n message: 'Vous vous êtes bien connecté.',\n position: 'bottom center',\n timeOut: 3000\n })\n })\n .catch(() => {\n this.$toast.error({\n title: 'Erreur',\n message: 'L\\'email ou le mot de passe ne sont pas valides. Vérifiez votre saisie.',\n position: 'bottom center',\n timeOut: 8000\n })\n })\n .finally(() => this.$wait.end('signing in'))\n }\n```\n\n```text\nsign_in_and_redirect @user\n```\n\n```text\n@user = ...\n```\n\n```text\ndevise for :users\n```\n\n```text\nrake routes\n```\n\n========================================\n\nComments:\n- Yes is that why my note here, i have my routes too and my omniauth work well in Rails but i need to redirect on my NuxtJS page with the user authentificate","metadata":{"transformedAt":"2026-08-18T18:33:07.964Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":384,"estimatedTokens":2279}}1006{"id":"stack-56927438","source":"stackoverflow","questionId":56927438,"title":"nuxt generate throws error for dynamic page nuxt.js","tags":["vue.js","vuejs2","nuxt.js"],"text":"Title: nuxt generate throws error for dynamic page nuxt.js\nTags: vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI can not seem to figure out what the issue is here...\n\nI have created a blog with pagination using nuxt.js now in my `nuxt.config.js` I have a method that gets the posts from contentful like so\n\n```\nconst getBlogPosts = async () => {\n let blogPosts = await client.getEntries({ order: '-sys.createdAt', limit: 1000, content_type: config.CTF_BLOG_POST });\n return blogPosts;\n};\n```\n\nthen when I generate the routes I do the following...\n\n```\ngenerate: {\n routes: async () => {\n const posts = await getBlogPosts();\n const routes = [];\n let postsNum = Math.ceil(posts.items.length / 10); // get the page numbers\n for (let i = 1; i then in my `_page/index.vue`\n\nhttps://i.sstatic.net/EiSDn.png\n\n```\n\nexport default {\n components: {\n //...\n },\n aysnc asyncData(context) {\n if(context.payload) {\n return {\n blogPosts: context.payload.data.items.slice(0, 8)\n }\n } else {\n //...\n }\n }\n}\n\n```\n\nnow when Im running this locally the page works fine no errors etc.. but on `nuxt generate` I get \n\n`ERROR: Error generating /page/1`\n\nnow I've tried to `console.log()` the blogPosts on `mounted()` but It never fires.\n\nI can not figure out what is wrong here, Ive tried to strip back everything and made my `_page/index.vue` to look like this\n\n```\n\n \n \n\n### hello\n\n \n\nexport default {\n\n}\n\n```\n\nbut I still get the generate error I've `console.log()` routes and I get this\n\n```\n[ 11:39:44 \n {\n route: '/page/1',\n payload: {\n data: [Array]\n }\n }\n]\n```\n\nwhich looks correct, so why is the page erroring??\n\n**edit 1**\n\nWhen I check my dist folder the page 1 index.html is there but in the html it says `this page could not be found`\n\nany help would be appreciated thanks or is there a way to get a better error message\n\n**edit 2**\n\nAll of my individual blog pages build correctly, but the actual /page/1 is the only one that is failing I have put a try catch around the whole async generate method and there are no errors.. also If I console.log all the routes it appears as if it is all correct\n\n```\n[ 08:58:38\n {\n route: '/blog/6gQUEUwex7mjNtAXY4ZlTO',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/blog/2xDAv0zSt4kUfxOV1XC98C',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/blog/6f6shGDflvuBUMZn25sIbE',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/blog/24Sov29BazGj52WEQdJGiy',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/blog/r2ky97Vg8u6rouiVXdSzd',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/blog/2QnIl7GOScQ31A7EcRVgT1',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/blog/1bEUOT5Xnm7CU9Njd5xkeu',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/blog/7FUON1DcQcGQnvdp7Kxfbe',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/page/1',\n payload: {\n data: [Array]\n }\n }\n]\n```\n\nall of the other pages are generated correctly\n\n========================================\n\nCode:\n```text\nconst getBlogPosts = async () => {\n let blogPosts = await client.getEntries({ order: '-sys.createdAt', limit: 1000, content_type: config.CTF_BLOG_POST });\n return blogPosts;\n};\n```\n\n```text\ngenerate: {\n routes: async () => {\n const posts = await getBlogPosts();\n const routes = [];\n let postsNum = Math.ceil(posts.items.length / 10); // get the page numbers\n for (let i = 1; i <= postsNum; i++) {\n routes.push({\n route: '/page/' + i,\n payload: {\n data: posts.items.splice(i === 1 ? 0 : i * 10, 10)\n }\n });\n }\n return routes;\n }\n },\n```\n\n```text\n<script>\nexport default {\n components: {\n //...\n },\n aysnc asyncData(context) {\n if(context.payload) {\n return {\n blogPosts: context.payload.data.items.slice(0, 8)\n }\n } else {\n //...\n }\n }\n}\n</script>\n```\n\n```text\n<template>\n <div>\n <h1>hello</h1>\n </div>\n</template>\n\n<script>\nexport default {\n\n}\n</script>\n\n<style>\n\n</style>\n```\n\n```text\n[ 11:39:44 \n {\n route: '/page/1',\n payload: {\n data: [Array]\n }\n }\n]\n```\n\n```text\n[ 08:58:38\n {\n route: '/blog/6gQUEUwex7mjNtAXY4ZlTO',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/blog/2xDAv0zSt4kUfxOV1XC98C',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/blog/6f6shGDflvuBUMZn25sIbE',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/blog/24Sov29BazGj52WEQdJGiy',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/blog/r2ky97Vg8u6rouiVXdSzd',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/blog/2QnIl7GOScQ31A7EcRVgT1',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/blog/1bEUOT5Xnm7CU9Njd5xkeu',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/blog/7FUON1DcQcGQnvdp7Kxfbe',\n payload: {\n data: [Object]\n }\n },\n {\n route: '/page/1',\n payload: {\n data: [Array]\n }\n }\n]\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n_page/index.vue\n```\n\n```text\nnuxt generate\n```\n\n```text\nERROR: Error generating /page/1\n```\n\n```text\nconsole.log()\n```\n\n```text\nmounted()\n```\n\n```text\n_page/index.vue\n```\n\n```text\nconsole.log()\n```\n\n```text\nthis page could not be found\n```\n\n```text\nfor (let i = 1; i <= postsNum; i++) {\n routes.push({\n route: '/blog/page/' + i,\n payload: {\n data: posts.items.splice(i === 1 ? 0 : i * 10, 10)\n }\n });\n}\n```\n\n```text\n/blog/page/1\n```\n\n```text\n/page/1\n```\n\n========================================\n\nComments:\n- `console.log()` won't work unless in development mode, use `console.error()...` if you must\n- @Ohgodwhy `console.error()` didnt do anything either, If i put a console.log() on any other route, while its generating it will display it\n- @SmokeyDawson can you add some try/catch blocks to each of your `await` statements and see if you are getting any errors as a result of the async calls?\n- @ChrisLeyva I will try this and update my question, thanks\n- @SmokeyDawson I also added some more info to your question in the Nuxt reddit thread you posted.\n- @ChrisLeyva sorry for late response been working on other projects, I have put try catch blocks around the code and still no errors show up","metadata":{"transformedAt":"2026-08-18T18:33:07.964Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":356,"estimatedTokens":1591}}1007{"id":"stack-58263454","source":"stackoverflow","questionId":58263454,"title":"How to integrate Spring MVC and Nuxt JS?","tags":["rest","spring-mvc","nuxt.js"],"text":"Title: How to integrate Spring MVC and Nuxt JS?\nTags: rest, spring-mvc, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have learnt Nuxt JS and Spring MVC. I want to know, how to make a single page web application integrating or configuring Spring MVC and Nuxt JS. I didn't find any well documented material over internet. Basically, I want to handle all CRUD operations asynchronously. Database is MySQL. If possible, can someone help me how to do this? Thank you in advance!\n\n========================================\n\nCode:\n```text\n@RestController\n@RequestMapping(\"api\")\n@CrossOrigin(origins = \"http://localhost:3000\")\npublic class MainRestController {\n\n private final IRestService restService;\n\n @Autowired\n public MainRestController(IRestService restService) {\n this.restService = restService;\n }\n\n @GetMapping(value = \"users\", produces = MediaType.APPLICATION_JSON_VALUE)\n public ResponseEntity<Iterable<String>> getUsers() {\n try {\n return new ResponseEntity<>(restService.getAllUsers(), HttpStatus.OK);\n } catch (Exception e) {\n return new ResponseEntity<>(HttpStatus.BAD_REQUEST);\n }\n }\n}\n```\n\n```text\n<template>\n <div class=\"container\">\n <ul>\n <li v-for=\"user of users\">\n {{user}}\n </li>\n </ul>\n </div>\n</template>\n\n<script>\n export default {\n async asyncData({ $axios }) {\n\n const users = await $axios.$get('http://localhost:8080/api/users');\n return { users }\n }\n }\n</script>\n```\n\n```text\nmodules: [\n '@nuxtjs/axios',\n '@nuxtjs/proxy'\n ],\n\naxios: {\n proxy: true,\n },\n\n env: {\n baseUrl: process.env.BASE_URL || 'http://localhost:3000'\n },\n\n proxy: {\n '/api/': {\n target: 'http://localhost:8080/',\n pathRewrite: { \"^/api\": \"\" },\n changeOrigin: true,\n }\n },\n```\n\n```text\nCrossOrigin\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.964Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":82,"estimatedTokens":460}}1008{"id":"stack-55434494","source":"stackoverflow","questionId":55434494,"title":"How to outsource asyncData to Vuex Store?","tags":["vue.js","vuex","nuxt.js"],"text":"Title: How to outsource asyncData to Vuex Store?\nTags: vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm currently loading some data from firebase I wan't to be server side rendered so it can be indexed for SEO in `asyncData` on a page.\n\n```\nasyncData() {\n return firebase.firestore().collection('Programms').get().then((querySnapshot) => {\n const programms = [];\n querySnapshot.forEach((doc) => {\n const programm = doc.data();\n programm.id = doc.id;\n programms.push(programm)\n })\n return { programms: programms};\n })\n```\n\nHowever I would like to convert this to my vuex store.\n\nI know I could do this:\n\n```\nconst actions = {\n async nuxtServerInit({ commit }) {\n firebase.firestore().collection('Programms').onSnapshot((querySnapshot) => {\n const programms = [];\n querySnapshot.forEach((doc) => {\n const programm = doc.data();\n programm.id = doc.id;\n programms.push(programm)\n })\n console.log('loaded Programms', programms)\n\n commit('setProgramms', programms);\n })\n },\n}\n```\n\nBut this way the data will be loaded for every route in my app. I wan't to load this data only in some pages where I also display it, so I don't load it unnecessary.\n\nHow could I do this in Vuex?\n\n========================================\n\nCode:\n```text\nasyncData() {\n return firebase.firestore().collection('Programms').get().then((querySnapshot) => {\n const programms = [];\n querySnapshot.forEach((doc) => {\n const programm = doc.data();\n programm.id = doc.id;\n programms.push(programm)\n })\n return { programms: programms};\n })\n```\n\n```text\nconst actions = {\n async nuxtServerInit({ commit }) {\n firebase.firestore().collection('Programms').onSnapshot((querySnapshot) => {\n const programms = [];\n querySnapshot.forEach((doc) => {\n const programm = doc.data();\n programm.id = doc.id;\n programms.push(programm)\n })\n console.log('loaded Programms', programms)\n\n commit('setProgramms', programms);\n })\n },\n}\n```\n\n```text\nasyncData\n```\n\n```text\nfetch ({ store, params }) {\n return firebase.firestore().collection('Programms').get().then((querySnapshot) => {\n const programms = [];\n querySnapshot.forEach((doc) => {\n const programm = doc.data();\n programm.id = doc.id;\n programms.push(programm)\n })\n .then(() => {\n store.commit('setPrograms', programms)\n })\n }\n```\n\n========================================\n\nComments:\n- Need some more information as of how you're calling this data since you said you don't want to load it on every router?\n- Not sure what I should provide you. On some (currently only 1) page, I have this `asyncData`. However I want to handle my data not in the components, so I want to outsource this in a vuex store. However `nuxtServerInit` would load it for every page/route, so also for pages I don't need it.\n- I guess. First, you need to create routes and check if the data is loaded or not then you can add the example with all the relevant code.\n- I don't think you understand what I need exactly. I'm using Nuxt.js and Server Side Rendering. AsyncData runs before the client takes over from the server.\n- use fetch method instead of asyncdata 7 is it what u are looking for 7\n- The fetch method deosn't work for some reason. I posted my vuex store in my post. Any Ideas?","metadata":{"transformedAt":"2026-08-18T18:33:07.964Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":108,"estimatedTokens":845}}1009{"id":"stack-57416050","source":"stackoverflow","questionId":57416050,"title":"change facebook sdk lang code dynamically in vue (nuxt)","tags":["facebook","vue.js","nuxt.js","vue-i18n"],"text":"Title: change facebook sdk lang code dynamically in vue (nuxt)\nTags: facebook, vue.js, nuxt.js, vue-i18n\nSource: Stack Overflow\n\nQuestion:\ni am currently working on a simple like implementation in nuxt. when i change the language with 1i8n, i want to change the facebook sdk language accordingly, so the button renders in the given language code when i change the overall app language. my code looks like this:\n\n```\nimport config from '@/config'\n\nexport default {\n data() {\n return {\n FB_APP_ID: config.appname.FB_APP_ID\n }\n },\n mounted() {\n var langua;\n\n if (this.$i18n.locale == 'en') {\n langua = \"en_US\";\n }\n\n if (this.$i18n.locale == 'de') {\n langua = \"de_DE\";\n }\n\n window.fbAsyncInit = () => {\n FB.init({\n appId: this.FB_APP_ID,\n cookie: true,\n xfbml: true,\n version: 'v2.8'\n })\n }\n\n (function(d, s, id){\n var js, fjs = d.getElementsByTagName(s)[0];\n if (d.getElementById(id)) {return;}\n js = d.createElement(s); js.id = id;\n js.src = \"//connect.facebook.net/\" + langua + \"/sdk.js\";\n fjs.parentNode.insertBefore(js, fjs);\n }(document, 'script', 'facebook-jssdk'));\n }\n}\n```\n\nit works but the dynamic change is not happening, do i miss something like async on the button sdk here ??? no idea, i am new to vue, help is appreciated thanks a lot.\n\n========================================\n\nTop Answer:\nI solved it by using `this.$router.go(0);` on the button click of the language switch, i had hoped to use another way, but still could'nt find one, anyway, now the language changes when the page reloads and the sdk's lang code as well, if else uses the appropriate language. Maybe i ll find a more elegant solution someday 😊👍\n\n========================================\n\nCode:\n```text\nimport config from '@/config'\n\nexport default {\n data() {\n return {\n FB_APP_ID: config.appname.FB_APP_ID\n }\n },\n mounted() {\n var langua;\n\n if (this.$i18n.locale == 'en') {\n langua = \"en_US\";\n }\n\n if (this.$i18n.locale == 'de') {\n langua = \"de_DE\";\n }\n\n window.fbAsyncInit = () => {\n FB.init({\n appId: this.FB_APP_ID,\n cookie: true,\n xfbml: true,\n version: 'v2.8'\n })\n }\n\n (function(d, s, id){\n var js, fjs = d.getElementsByTagName(s)[0];\n if (d.getElementById(id)) {return;}\n js = d.createElement(s); js.id = id;\n js.src = \"//connect.facebook.net/\" + langua + \"/sdk.js\";\n fjs.parentNode.insertBefore(js, fjs);\n }(document, 'script', 'facebook-jssdk'));\n }\n}\n```\n\n```text\n<template>\n <div\n :key=\"`fb-chat-${$i18n.locale}`\"\n class=\"fb-customerchat\"\n :page_id=\"pageId\"\n theme_color=\"#4586ff\"\n greeting_dialog_display=\"hide\"\n :logged_in_greeting=\"$t('greeting')\"\n :logged_out_greeting=\"$t('greeting')\"\n ></div>\n</template>\n\n<script>\nexport default {\n name: 'FacebookChat',\n\n data() {\n return {\n pageId: process.env.FACEBOOK_PAGE_ID,\n }\n },\n\n watch: {\n '$i18n.locale': 'resetFacebookSdk',\n },\n\n mounted() {\n this.initFacebookSdk()\n },\n\n methods: {\n initFacebookSdk() {\n if (!process.browser) return\n\n const locale = this.$i18n.locale === 'de' ? 'de_DE' : 'en_US'\n delete window.FB // needs to be undefined when inserting a second script with different locale\n\n window.fbAsyncInit = function () {\n window.FB.init({\n appId: process.env.FACEBOOK_APP_ID,\n autoLogAppEvents: true,\n xfbml: true,\n version: 'v10.0',\n })\n }\n ;(function (d, s, id) {\n let js = d.getElementById(id),\n fjs = d.getElementsByTagName(s)[0]\n if (js) js.parentNode.removeChild(js) // remove script tag if exists\n js = d.createElement(s)\n js.id = id\n js.src = `https://connect.facebook.net/${locale}/sdk/xfbml.customerchat.js`\n fjs.parentNode.insertBefore(js, fjs)\n })(document, 'script', `facebook-jssdk-${this.$i18n.locale}`)\n },\n\n resetFacebookSdk() {\n const fbRoot = this.$el.closest('#fb-root')\n if (!fbRoot) return\n\n // Move fb-customerchat element outside of fb-root (created by Facebook SDK)\n fbRoot.parentNode.insertBefore(this.$el, fbRoot)\n // Delete fb-root to let Facebook SDK create it again\n fbRoot.parentNode.removeChild(fbRoot)\n\n this.initFacebookSdk()\n },\n },\n}\n</script>\n```\n\n```text\nFB\n```\n\n```text\nkey\n```\n\n```text\nresetFacebookSdk\n```\n\n```text\n.fb-customerchat\n```\n\n```text\nkey\n```\n\n```text\n#fb-root\n```\n\n```text\nresetFacebookSdk\n```\n\n```text\n.fb-customerchat\n```\n\n```text\nthis.$router.go(0);\n```\n\n========================================\n\nComments:\n- What dynamic change are you talking about? You mean you initialize the SDK in language X, and then switch to Y in your app? That won’t work, the SDK can only be embedded and initialized once.\n- yeah yes exactly.. how can i change the language code (en_US) by changing the overall language dynamically, do i need to use an async function to access the asnyc sdk ? no idea...","metadata":{"transformedAt":"2026-08-18T18:33:07.964Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":211,"estimatedTokens":1272}}1010{"id":"stack-55573609","source":"stackoverflow","questionId":55573609,"title":"CORS error when accessing Django api with Nuxtjs","tags":["django","cors","nuxt.js","django-cors-headers"],"text":"Title: CORS error when accessing Django api with Nuxtjs\nTags: django, cors, nuxt.js, django-cors-headers\nSource: Stack Overflow\n\nQuestion:\nI have a Nuxtjs frontend and a Django backend. I want to consume my backend api and have the follwing index.vue :\n\n```\n\n \n \n\n### {{ data }}\n\n \n \n\n \n import axios from 'axios'\n\n export default {\n async asyncData({ params }) {\n // We can use async/await ES6 feature\n const { data } = await axios.get(`localhost:8000/api`)\n return { data }\n }\n }\n\n```\n\nMy nuxt.config.js has this code:\n\n```\naxios: {\n baseURL: 'localhost:8000',\n proxyHeaders: false,\n credentials: false,\n mode: 'no-cors'\n },\n```\n\nMy Django settings.py should be fine as it has corsheaders installed :\n\n```\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'corsheaders',\n 'django_celery_results',\n 'django_celery_beat',\n 'rest_framework',\n 'core',\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nCORS_ORIGIN_ALLOW_ALL = True\nCORS_ALLOW_CREDENTIALS = False\n```\n\nNo idea what is going on or why axios is still raising the CORS error :\n\n```\nVM1921:1 Access to XMLHttpRequest at 'localhost:8000/api' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.\n(anonymous) @ VM1921:1\ndispatchXhrRequest @ commons.app.js:199\nxhrAdapter @ commons.app.js:33\ndispatchRequest @ commons.app.js:638\nPromise.then (async)\nrequest @ commons.app.js:445\nAxios.(anonymous function) @ commons.app.js:455\nwrap @ commons.app.js:898\n_callee$ @ pages_index.js:51\ntryCatch @ commons.app.js:5762\ninvoke @ commons.app.js:5988\nprototype.(anonymous function) @ commons.app.js:5814\nasyncGeneratorStep @ vendors.app.js:31\n_next @ vendors.app.js:53\n(anonymous) @ vendors.app.js:60\n(anonymous) @ vendors.app.js:49\nasyncData @ pages_index.js:69\npromisify @ app.js:2841\n(anonymous) @ app.js:1089\n_callee4$ @ app.js:1059\ntryCatch @ commons.app.js:5762\ninvoke @ commons.app.js:5988\nprototype.(anonymous function) @ commons.app.js:5814\nasyncGeneratorStep @ vendors.app.js:31\n_next @ vendors.app.js:53\nPromise.then (async)\nasyncGeneratorStep @ vendors.app.js:41\n_next @ vendors.app.js:53\nPromise.then (async)\nasyncGeneratorStep @ vendors.app.js:41\n_next @ vendors.app.js:53\nPromise.then (async)\nasyncGeneratorStep @ vendors.app.js:41\n_next @ vendors.app.js:53\nPromise.then (async)\nasyncGeneratorStep @ vendors.app.js:41\n_next @ vendors.app.js:53\n(anonymous) @ vendors.app.js:60\n(anonymous) @ vendors.app.js:49\n_render @ app.js:1170\nrender @ app.js:787\n_callee5$ @ app.js:1478\ntryCatch @ commons.app.js:5762\ninvoke @ commons.app.js:5988\nprototype.(anonymous function) @ commons.app.js:5814\nasyncGeneratorStep @ vendors.app.js:31\n_next @ vendors.app.js:53\nPromise.then (async)\nasyncGeneratorStep @ vendors.app.js:41\n_next @ vendors.app.js:53\n(anonymous) @ vendors.app.js:60\n(anonymous) @ vendors.app.js:49\n_mountApp @ app.js:1504\nmountApp @ app.js:1402\nPromise.then (async)\n(anonymous) @ app.js:550\n./.nuxt/client.js @ app.js:1506\n__webpack_require__ @ runtime.js:787\nfn @ runtime.js:150\n0 @ app.js:3779\n__webpack_require__ @ runtime.js:787\ncheckDeferredModules @ runtime.js:46\nwebpackJsonpCallback @ runtime.js:33\n(anonymous) @ app.js:1\napp.js:540 Error: Network Error\n at createError (commons.app.js:565)\n at XMLHttpRequest.handleError (commons.app.js:108)\n at XMLHttpRequest.send (:1:781)\n at dispatchXhrRequest (commons.app.js:199)\n at new Promise ()\n at xhrAdapter (commons.app.js:33)\n at dispatchRequest (commons.app.js:638)\n```\n\n========================================\n\nTop Answer:\nI think you need whitelist the ports\n\nin settings.py\n\n```\nCORS_ORIGIN_WHITELIST = (\n 'http://190.0.0.21:8080', # server ip\n 'localhost:8000', # local host\n '*' # allow all\n)\n```\n\n========================================\n\nCode:\n```text\n<template>\n <div class=\"container\">\n <h1>{{ data }}</h1>\n </div>\n </template>\n\n <script>\n import axios from 'axios'\n\n export default {\n async asyncData({ params }) {\n // We can use async/await ES6 feature\n const { data } = await axios.get(`localhost:8000/api`)\n return { data }\n }\n }\n\n</script>\n```\n\n```text\naxios: {\n baseURL: 'localhost:8000',\n proxyHeaders: false,\n credentials: false,\n mode: 'no-cors'\n },\n```\n\n```text\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'corsheaders',\n 'django_celery_results',\n 'django_celery_beat',\n 'rest_framework',\n 'core',\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nCORS_ORIGIN_ALLOW_ALL = True\nCORS_ALLOW_CREDENTIALS = False\n```\n\n```text\nVM1921:1 Access to XMLHttpRequest at 'localhost:8000/api' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.\n(anonymous) @ VM1921:1\ndispatchXhrRequest @ commons.app.js:199\nxhrAdapter @ commons.app.js:33\ndispatchRequest @ commons.app.js:638\nPromise.then (async)\nrequest @ commons.app.js:445\nAxios.(anonymous function) @ commons.app.js:455\nwrap @ commons.app.js:898\n_callee$ @ pages_index.js:51\ntryCatch @ commons.app.js:5762\ninvoke @ commons.app.js:5988\nprototype.(anonymous function) @ commons.app.js:5814\nasyncGeneratorStep @ vendors.app.js:31\n_next @ vendors.app.js:53\n(anonymous) @ vendors.app.js:60\n(anonymous) @ vendors.app.js:49\nasyncData @ pages_index.js:69\npromisify @ app.js:2841\n(anonymous) @ app.js:1089\n_callee4$ @ app.js:1059\ntryCatch @ commons.app.js:5762\ninvoke @ commons.app.js:5988\nprototype.(anonymous function) @ commons.app.js:5814\nasyncGeneratorStep @ vendors.app.js:31\n_next @ vendors.app.js:53\nPromise.then (async)\nasyncGeneratorStep @ vendors.app.js:41\n_next @ vendors.app.js:53\nPromise.then (async)\nasyncGeneratorStep @ vendors.app.js:41\n_next @ vendors.app.js:53\nPromise.then (async)\nasyncGeneratorStep @ vendors.app.js:41\n_next @ vendors.app.js:53\nPromise.then (async)\nasyncGeneratorStep @ vendors.app.js:41\n_next @ vendors.app.js:53\n(anonymous) @ vendors.app.js:60\n(anonymous) @ vendors.app.js:49\n_render @ app.js:1170\nrender @ app.js:787\n_callee5$ @ app.js:1478\ntryCatch @ commons.app.js:5762\ninvoke @ commons.app.js:5988\nprototype.(anonymous function) @ commons.app.js:5814\nasyncGeneratorStep @ vendors.app.js:31\n_next @ vendors.app.js:53\nPromise.then (async)\nasyncGeneratorStep @ vendors.app.js:41\n_next @ vendors.app.js:53\n(anonymous) @ vendors.app.js:60\n(anonymous) @ vendors.app.js:49\n_mountApp @ app.js:1504\nmountApp @ app.js:1402\nPromise.then (async)\n(anonymous) @ app.js:550\n./.nuxt/client.js @ app.js:1506\n__webpack_require__ @ runtime.js:787\nfn @ runtime.js:150\n0 @ app.js:3779\n__webpack_require__ @ runtime.js:787\ncheckDeferredModules @ runtime.js:46\nwebpackJsonpCallback @ runtime.js:33\n(anonymous) @ app.js:1\napp.js:540 Error: Network Error\n at createError (commons.app.js:565)\n at XMLHttpRequest.handleError (commons.app.js:108)\n at XMLHttpRequest.send (<anonymous>:1:781)\n at dispatchXhrRequest (commons.app.js:199)\n at new Promise (<anonymous>)\n at xhrAdapter (commons.app.js:33)\n at dispatchRequest (commons.app.js:638)\n```\n\n```text\nconst { data } = await axios.get(`http://localhost:8000/api`)\n```\n\n```text\nCORS_ORIGIN_WHITELIST = (\n 'http://190.0.0.21:8080', # server ip\n 'localhost:8000', # local host\n '*' # allow all\n)\n```\n\n========================================\n\nComments:\n- It would most likely be a good idea to whitelist my ports, but I already have CORS_ORIGIN_ALLOW_ALL = True","metadata":{"transformedAt":"2026-08-18T18:33:07.964Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":321,"estimatedTokens":2152}}1011{"id":"stack-56924342","source":"stackoverflow","questionId":56924342,"title":"Prevent file from generating new build - Webpack","tags":["javascript","node.js","webpack","nuxt.js"],"text":"Title: Prevent file from generating new build - Webpack\nTags: javascript, node.js, webpack, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have an application with nuxt.js / Vue.\n\nI created a Webpack Plugin so that with each file changed, generate an `index.js` in a certain directory.\n\nThe problem is that when `index.js` is generated, Webpack recognizes this as a new change and build again, so it stays in that infinite loop ...\n\nTo detect changes, I'm using webpack hooks\n\n```\ncompiler.hooks.beforeCompile.tapAsync('MyPlugin', (params, callback) => {\n // script to generate an index.js in a given directory\n});\n```\n\nhow can I prevent `index.js` from triggering a new build?\n\n Updating the question for better understanding\n\nI'm working on an application made with vue.js | nuxt.js and this component structure\n\n```\n├── components\n│ ├── quarks\n│ │ └── ...\n│ ├── bosons\n│ │ └── GridLayout.vue\n│ │ └── ...\n│ ├── atoms\n│ │ └── ButtonStyle.vue\n│ │ └── InputStyle.vue\n│ │ └── ...\n│ ├── molecules\n│ │ └── ...\n│ ├── organisms\n│ │ └── ...\n│ ├── templates\n│ │ └── ...\n└─────\n```\n\nI need to do named and grouped imports, like this:\n\n```\nimport { ButtonStyle, InputStyle } from '@/components/atoms/'\n```\n\nbut for this to work out I would need to have an index.js inside each folder exporting component by component, example\n\n```\n├── components\n│ ├── atoms\n│ │ └── ButtonStyle.vue\n│ │ └── InputStyle.vue\n│ │ └── index.js\n└─────\n```\n\nand in `index.js`\n\n```\nexport { default as ButtonStyled } from './ButtonStyled.vue'\nexport { default as InputStyle } from './InputStyle.vue'\n```\n\nBut doing this work manually can be a very tiresome task. Every time you create, delete, rename a component, you would have to update the `index.js` of your respective folder.\n\nso I started to develop a solution\n\nin `nuxt.config.js`\n\n```\nimport NamedExports from './plugins/NamedExports.js'\n\nexport default {\n // ... other config here ...\n build: {\n plugins: [\n new NamedExports()\n ],\n }\n}\n```\n\nin `plugins/NamedExports.js`\n\n```\nconst pluginName = 'NamedExports'\nconst { exec } = require('child_process')\n\nclass NamedExports {\n apply(compiler) {\n compiler.hooks.beforeCompile.tap(pluginName, (params, callback) => {\n exec('sh plugins/shell.sh', (err, stdout, stderr) => {\n console.log(stdout)\n console.log(stderr)\n })\n })\n }\n}\n\nexport default NamedExports\n```\n\n`plugins/shell.sh`\n\n```\nparameters=$(ls components)\nfor item in ${parameters[*]}\ndo\n ls components/$item/ | grep -v index.js | sed 's#^\\([^.]*\\).*$#export { default as \\1 } from \"./&\"#' > components/$item/index.js\ndone\n```\n\nbut whenever the plugin creates an `index.js`, a new build is triggered\n\n========================================\n\nTop Answer:\nHave you added the new file/directory to WebPacks exclude list? If not, the watchOptions.ignore property might be just what your looking for:\nhttps://webpack.js.org/configuration/watch/\n\nHope this helps\n\n========================================\n\nCode:\n```text\ncompiler.hooks.beforeCompile.tapAsync('MyPlugin', (params, callback) => {\n // script to generate an index.js in a given directory\n});\n```\n\n```text\n├── components\n│ ├── quarks\n│ │ └── ...\n│ ├── bosons\n│ │ └── GridLayout.vue\n│ │ └── ...\n│ ├── atoms\n│ │ └── ButtonStyle.vue\n│ │ └── InputStyle.vue\n│ │ └── ...\n│ ├── molecules\n│ │ └── ...\n│ ├── organisms\n│ │ └── ...\n│ ├── templates\n│ │ └── ...\n└─────\n```\n\n```text\nimport { ButtonStyle, InputStyle } from '@/components/atoms/'\n```\n\n```text\n├── components\n│ ├── atoms\n│ │ └── ButtonStyle.vue\n│ │ └── InputStyle.vue\n│ │ └── index.js\n└─────\n```\n\n```text\nexport { default as ButtonStyled } from './ButtonStyled.vue'\nexport { default as InputStyle } from './InputStyle.vue'\n```\n\n```text\nimport NamedExports from './plugins/NamedExports.js'\n\nexport default {\n // ... other config here ...\n build: {\n plugins: [\n new NamedExports()\n ],\n }\n}\n```\n\n```text\nconst pluginName = 'NamedExports'\nconst { exec } = require('child_process')\n\nclass NamedExports {\n apply(compiler) {\n compiler.hooks.beforeCompile.tap(pluginName, (params, callback) => {\n exec('sh plugins/shell.sh', (err, stdout, stderr) => {\n console.log(stdout)\n console.log(stderr)\n })\n })\n }\n}\n\nexport default NamedExports\n```\n\n```text\nparameters=$(ls components)\nfor item in ${parameters[*]}\ndo\n ls components/$item/ | grep -v index.js | sed 's#^\\([^.]*\\).*$#export { default as \\1 } from \"./&\"#' > components/$item/index.js\ndone\n```\n\n```text\nindex.js\n```\n\n```text\nindex.js\n```\n\n```text\nindex.js\n```\n\n```text\nindex.js\n```\n\n```text\nindex.js\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nplugins/NamedExports.js\n```\n\n```text\nplugins/shell.sh\n```\n\n```text\nindex.js\n```\n\n```text\ncompiler.hooks.entryOption.tap('MyPlugin', (context, entry) => {\n // generates index.js\n // Watch a directory with chokidar \n});\n```\n\n```text\nchokidar\n```\n\n========================================\n\nComments:\n- I already tried this option, and I can make the webpack stop observing the `index.js`, but this causes another problem. When my script `updates` the contents of `index.js`, the webpack will not recognize these changes and will be as if it had not updated.\n- Hmm... Perhaps I misunderstood the question then. So that we can understand correctly and attempt to better answer let me ask. Are you saying you want WebPack to detect content changes to the file, but ignore the file if the file is replaced (i.e. a new file is created with the same name and size)?\n- That's exactly what I need. the `index.js` file makes named exports, and can be updated as new components / modules are created or deleted, so content is very important for the operation of the application. but index.js is dynamically generated so it will not be possible to fire new constructs.\n- Unfortunately I'm not familiar with a watch option that will give you the behavior you are looking for out of the box. Perhaps someone else has some ideas. However if you are willing to a little more information such as when your plug-in is triggered we may be able to approach this from another vector. Based on the little I have learned, it almost sounds like this would primarily be a problem at development time? In any case we may be able to solve this via timing and arrangement updates. Or perhaps leveraging your index file as a link to your generated files and excluding those.\n- I updated my question for better understanding my problem, if you can read it, be happy\n- Thanks for the updates Yung, this should be very helpful. I have to go meet my girlfriends family for dinner so won't be able to review until later, but another option I plan to look at is to see if we can intercept the WebPack hooks \"completed\" event to see if we could manually trigger an \"everything is good\" status thus circumventing the build during that polling cycle. I have a couple other thoughts too, but will need to review further once I get back and can give your updated question a closer look. P.S. I up voted the question in hopes more people will see it and have a chance to respond.\n- thank you very much for your attention, I'm very happy, I'll be waiting anxiously, I've been trying to solve this problem for days.\n- Try this in your watchOptions and let us know: \"watchOptions: { aggregateTimeout: 3500 }\" I'm not 100% sure this will suppress the issue for us due to the beforeCompile hook, but figured it's worth a shot since this will likely be the quickest work around by a fair margin.\n- the loop continues, only now with a delay\n- Interesting, what is the watch polling in the webpack.conf for project currently set for? Basically what we want to do is have the webpack watch polling detect the changes, then execute your plug-in before compilation (regenerate the index) and ideally have the aggregate timeout wait long enough to incorporate those changes into the pending build. Probably need some tweaking at minimum none the less or perhaps look at other pre compile intercept events. Trick might be we need to wait long enough for both your plugin to execute then the system I/O create and unlock the file in time.\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:07.964Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":275,"estimatedTokens":2039}}1012{"id":"stack-54425193","source":"stackoverflow","questionId":54425193,"title":"Why am I suddenly getting an Unknown word error in Nuxt?","tags":["javascript","vue.js","webpack","nuxt.js"],"text":"Title: Why am I suddenly getting an Unknown word error in Nuxt?\nTags: javascript, vue.js, webpack, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI have a Nuxt project that was working fine until today.\n\nWithin this project, I am using Vue Flickity, which includes a link to a Flickity CSS file in `node_modules`. This has been working fine until now and seems to be the root of the issue.\n\nWhen I run `npm run dev` I get the following error:\n\n ERROR in\n ./node_modules/flickity/dist/flickity.css?vue&type=style&index=0&lang=css&\n friendly-errors 16:00:12\n\n \n Syntax Error: ModuleBuildError: Module build failed (from\n ./node_modules/postcss-loader/src/index.js): friendly-errors\n 16:00:12 SyntaxError\n\n \n (141:7) Unknown word\n\n \n 139 | 140 | if(module.hot) {\n\n \n \n 141 | // 1548777611244\n | ^ 142 | var cssReload = require(\"../../extract-css-chunks-webpack-plugin/dist/hotModuleReplacement.js\")(module.id,\n {\"fileMap\":\"{fileName}\",\"reloadAll\":true}); 143 |\n\n module.hot.dispose(cssReload); > friendly-errors 16:00:12 @\n ./node_modules/flickity/dist/flickity.css?vue&type=style&index=0&lang=css&\n 1:0-576 1:592-595 1:597-1170 1:597-1170 @\n ./node_modules/vue-flickity/src/flickity.vue @\n ./plugins/vue-flickity.js @ ./.nuxt/index.js @ ./.nuxt/client.js @\n multi eventsource-polyfill\n webpack-hot-middleware/client?reload=true&timeout=30000&ansiColors=&overlayStyles=&name=client&path=/__webpack_hmr/client\n ./.nuxt/client.js\n\n \n\nScreenshot:\n\nhttps://i.sstatic.net/0hQaQ.png\n\nI used the cli to create the project and so haven't even touched any Webpack configuration.\n\nVue Flickity is called via a plugin (as is the recommended way within Nuxt) with SSR set to false. Again, however, it has always been this way and was working fine before.\n\nI can't understand why this is happening. Any help or pointers would be greatly appreciated.\n\n========================================\n\nTop Answer:\nI have often faced this issue in Nuxt3, and downgrading the node to `16.19.1` version works.\n\n========================================\n\nCode:\n```text\nnode_modules\n```\n\n```text\nnpm run dev\n```\n\n```text\n\"nuxt\": \"^2.3.4\"\n```\n\n```text\npackage.json\n```\n\n```text\n\"nuxt\": \"2.3.4\"\n```\n\n```text\n16.19.1\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.964Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":84,"estimatedTokens":546}}1013{"id":"stack-55376329","source":"stackoverflow","questionId":55376329,"title":"Why does a reload return an empty state half of the time?","tags":["javascript","vue.js","vuex","nuxt.js"],"text":"Title: Why does a reload return an empty state half of the time?\nTags: javascript, vue.js, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI'm creating a webshop for a hobby project in Nuxt 2.5. In the Vuex store I have a module with a state \"currentCart\". In here I store an object with an ID and an array of products. I get the cart from the backend with an ID, which is stored in a cookie (with js-cookie). \n\nI use nuxtServerInit to get the cart from the backend. Then I store it in the state. Then in the component, I try to get the state and display the number of articles in the cart, if the cart is null, I display \"0\". This gives weird results. Half of the time it says correctly how many products there are, but the Vuex dev tools tells me the cart is null. The other half of the time it displays \"0\".\n\nAt first I had a middleware which fired an action in the store which set the cart. This didn't work consistently at all. Then I tried to set the store with nuxtServerInit, which actually worked right. Apparently I changed something, because today it gives the descibed problem. I can't find out why it produces this problem.\n\nThe nuxtServerInit:\n\n```\nnuxtServerInit ({ commit }, { req }) {\n let cartCookie;\n\n // Check if there's a cookie available\n if(req.headers.cookie) {\n\n cartCookie = req.headers.cookie\n .split(\";\")\n .find(c => c.trim().startsWith(\"Cart=\"));\n\n // Check if there's a cookie for the cart\n if(cartCookie)\n cartCookie = cartCookie.split(\"=\");\n else\n cartCookie = null;\n }\n // Check if the cart cookie is set\n if(cartCookie) {\n\n // Check if the cart cookie isn't empty\n if(cartCookie[1] != 'undefined') {\n let cartId = cartCookie[1];\n\n // Get the cart from the backend\n this.$axios.get(`${api}/${cartId}`)\n .then((response) => {\n let cart = response.data;\n // Set the cart in the state\n commit(\"cart/setCart\", cart);\n });\n }\n }\n else {\n // Clear the cart in the state\n commit(\"cart/clearCart\");\n }\n},\n```\n\nThe mutation:\n\n```\nsetCart(state, cart) {\n state.currentCart = cart;\n}\n```\n\nThe getter:\n\n```\ncurrentCart(state) {\n return state.currentCart;\n}\n```\n\nIn cart.vue:\n\n```\nif(this.$store.getters['cart/currentCart'])\n return this.$store.getters['cart/currentCart'].products.length;\nelse\n return 0;\n```\n\nThe state object:\n\n```\nconst state = () => ({\n currentCart: null,\n});\n```\n\nI put console.logs everywhere, to check where it goes wrong. The nuxtServerInit works, the commit \"cart/setCart\" fires and has the right content. In the getter, most of the time I get a null. If I reload the page quickly after another reload, I get the right cart in the getter and the component got the right count. The Vue dev tool says the currentCart state is null, even if the component displays the data I expect.\n\nI changed the state object to \"currentCart: {}\" and now it works most of the time, but every 3/4 reloads it returns an empty object. So apparently the getter fires before the state is set, while the state is set by nuxtServerInit. Is that right? If so, why is that and how do I change it?\n\nWhat is it I fail to understand? I'm totally confused.\n\n========================================\n\nTop Answer:\n### **Make the server wait for results**\n\nAbove is the answer boiled down to a statement.\n\nI had this same problem as @Maurits but slightly different parameters. I'm not using `nuxtServerInit()`, but Nuxt's fetch hook. In any case, the idea is essentially: You need to make the server wait for the data grab to finish.\n\nHere's code for my context; I think it's helpful for those using the Nuxt fetch hook. For fun, I added `computed` and `mounted` to help illustrate the fetch hook does *not* go in `methods`.\n\n**FAILS:**\n\n(I got blank pages on browser refresh)\n\n```\ncomputed: {\n /* some stuff */\n},\n\nasync fetch() {\n this.myDataGrab()\n .then( () => {\n console.log(\"Got the data!\")\n })\n},\n\nmounted() {\n /* some stuff */\n}\n```\n\n**WORKS:**\nI forgot to add `await` in front of the func call! Now the server will wait for this before completing and sending the page.\n\n```\nasync fetch() {\n await this.myDataGrab()\n .then( () => {\n console.log(\"Got the messages!\")\n })\n},\n```\n\n========================================\n\nCode:\n```js\nnuxtServerInit ({ commit }, { req }) {\n let cartCookie;\n\n // Check if there's a cookie available\n if(req.headers.cookie) {\n\n cartCookie = req.headers.cookie\n .split(\";\")\n .find(c => c.trim().startsWith(\"Cart=\"));\n\n // Check if there's a cookie for the cart\n if(cartCookie)\n cartCookie = cartCookie.split(\"=\");\n else\n cartCookie = null;\n }\n // Check if the cart cookie is set\n if(cartCookie) {\n\n // Check if the cart cookie isn't empty\n if(cartCookie[1] != 'undefined') {\n let cartId = cartCookie[1];\n\n // Get the cart from the backend\n this.$axios.get(`${api}/${cartId}`)\n .then((response) => {\n let cart = response.data;\n // Set the cart in the state\n commit(\"cart/setCart\", cart);\n });\n }\n }\n else {\n // Clear the cart in the state\n commit(\"cart/clearCart\");\n }\n},\n```\n\n```js\nsetCart(state, cart) {\n state.currentCart = cart;\n}\n```\n\n```js\ncurrentCart(state) {\n return state.currentCart;\n}\n```\n\n```js\nif(this.$store.getters['cart/currentCart'])\n return this.$store.getters['cart/currentCart'].products.length;\nelse\n return 0;\n```\n\n```js\nconst state = () => ({\n currentCart: null,\n});\n```\n\n```js\nasync nuxtServerInit ({ commit }, { req }) {\n ...\n await this.$axios.get(`${api}/${cartId}`)\n .then((response) => {\n ...\n }\n await commit(\"cart/clearCart\");\n```\n\n```text\ncomputed: {\n /* some stuff */\n},\n\nasync fetch() {\n this.myDataGrab()\n .then( () => {\n console.log(\"Got the data!\")\n })\n},\n\nmounted() {\n /* some stuff */\n}\n```\n\n```text\nasync fetch() {\n await this.myDataGrab()\n .then( () => {\n console.log(\"Got the messages!\")\n })\n},\n```\n\n```text\nnuxtServerInit()\n```\n\n```text\ncomputed\n```\n\n```text\nmounted\n```\n\n```text\nmethods\n```\n\n```text\nawait\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.964Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":259,"estimatedTokens":1488}}1014{"id":"stack-56551985","source":"stackoverflow","questionId":56551985,"title":"Nuxtjs plugin registration","tags":["javascript","nuxt.js"],"text":"Title: Nuxtjs plugin registration\nTags: javascript, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am curious as to the methodology Nuxt.js uses to register a plugin. I have been reading the documentation for Nuxt.js and I am slightly confused as to the registration methodology.\n\nI **do not** want to register plugins such as `vue-flag-icon` globally. \n\nMy understanding is when we register the plugin we use the plugin folder as such:\n\n```\nimport Vue from 'vue'\nimport FlagIcon from 'vue-flag-icon'\n\nVue.use(FlagIcon)\n```\n\nI can now use the flag component anywhere in my app - I dont want this!!!\n\nI want to be able to load plugins into the components that need them ONLY. \n\nI have tried loading them as a component like:\n\n```\ncomponents:{\n 'flag': ()=> import('path to plugin') // @/plugins/vue-flag-icon\n}\n```\n\nThis does not work.\n\nI changed my plugins script to:\n\n```\nimport Vue from 'vue'\nimport FlagIcon from 'vue-flag-icon'\n\nexport default () => {\n Vue.use(FlagIcon)\n}\n```\n\nAnd then tried to register the plugin within the components like so:\n\n```\nimport flag from '@/plugins/vue-flag-icon';\n\n created(){\n flag()\n }\n```\n\nMy questions really are:\n\n- How can I register a plugin within the component without importing the `vue` instance? (I think is called a bus)\n\n- Is it bad practice to import the plugins directly into components?\n\n- Is registering all the plugins within `nuxt.config.js` creating a larger download file for users to download (example: registering vue-twix is not necessary on pages that do not have textareas) or will nuxt/webpack handle the removal of unnecessary plugins on a page by page or component by component basis (so I don't have to even worry about this)?. If this is the case than I dig nuxt.\n\nThanks\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\nimport FlagIcon from 'vue-flag-icon'\n\n\nVue.use(FlagIcon)\n```\n\n```text\ncomponents:{\n 'flag': ()=> import('path to plugin') // @/plugins/vue-flag-icon\n}\n```\n\n```text\nimport Vue from 'vue'\nimport FlagIcon from 'vue-flag-icon'\n\nexport default () => {\n Vue.use(FlagIcon)\n}\n```\n\n```text\nimport flag from '@/plugins/vue-flag-icon';\n\n created(){\n flag()\n }\n```\n\n```text\nvue-flag-icon\n```\n\n```text\nvue\n```\n\n```text\nnuxt.config.js\n```\n\n```text\n<template>\n <flag iso=\"ca\" />\n</template>\n\n<script>\nimport FlagIcon from 'vue-flag-icon'\nexport default () => {\n components: {\n FlagIcon\n }\n</script>\n```\n\n```text\n<style lang=\"scss\" scoped>\n @import 'path/to/plugin/style.css';\n</style>\n```\n\n========================================\n\nComments:\n- Whats wrong with the `components` one? Any errors?\n- It is. There's simply no good reason why creating a plugin and calling that from the component as opposed to simply import the component inside the component that's going to use it. Specially not in the case mentioned (vue-flag-icon). Nuxt plugins are used to inject components into Vue, kind of like on a regular vue-cli application you'd do in the main.js file.","metadata":{"transformedAt":"2026-08-18T18:33:07.964Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":134,"estimatedTokens":745}}1015{"id":"stack-54458042","source":"stackoverflow","questionId":54458042,"title":"How can I set the custom marker icon for my leaflet map with NUXT.js","tags":["javascript","vue.js","leaflet","nuxt.js"],"text":"Title: How can I set the custom marker icon for my leaflet map with NUXT.js\nTags: javascript, vue.js, leaflet, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to change marker icon for separate marker on my OpenStreetMap.\n\n```\nmapIconsReinit(L) {\n delete L.Icon.Default.prototype._getIconUrl;\n\n L.Icon.Default.imagePath = ''\n L.Icon.Default.mergeOptions({\n iconRetinaUrl: require('@/assets/img/map_markers/default/marker-icon-2x.png'),\n iconUrl: require('@/assets/img/map_markers/default/marker-icon.png'),\n shadowUrl: require('@/assets/img/map_markers/default/marker-shadow.png'),\n });\n },\n\n getMarkerIcon(L, color) {\n return L.divIcon({\n iconRetinaUrl: require('@/assets/img/map_markers/marker-icon-2x-' + color + '.png'),\n iconUrl: require('@/assets/img/map_markers/marker-icon-' + color + '.png'),\n shadowUrl: require('@/assets/img/map_markers/marker-shadow.png'),\n iconSize: [25, 41],\n iconAnchor: [12, 41],\n popupAnchor: [1, -34],\n shadowSize: [41, 41]\n })\n }\n```\n\nFirst function works fine with paths like `'@/...'`, but the 2nd one - no.\n\nDefault marker works fine:\n\n```\nL.marker([marker.lat, marker.lng]).addTo(_context.map)\n```\n\nbut if I try to use custom marker:\n\n```\nL.marker([marker.lat, marker.lng], {icon: this.getMarkerIcon(L, \"red\")}).addTo(_context.map)\n```\n\nI see a white square\n\nhttps://i.sstatic.net/IAlQX.png\n\n========================================\n\nCode:\n```text\nmapIconsReinit(L) {\n delete L.Icon.Default.prototype._getIconUrl;\n\n L.Icon.Default.imagePath = ''\n L.Icon.Default.mergeOptions({\n iconRetinaUrl: require('@/assets/img/map_markers/default/marker-icon-2x.png'),\n iconUrl: require('@/assets/img/map_markers/default/marker-icon.png'),\n shadowUrl: require('@/assets/img/map_markers/default/marker-shadow.png'),\n });\n },\n\n getMarkerIcon(L, color) {\n return L.divIcon({\n iconRetinaUrl: require('@/assets/img/map_markers/marker-icon-2x-' + color + '.png'),\n iconUrl: require('@/assets/img/map_markers/marker-icon-' + color + '.png'),\n shadowUrl: require('@/assets/img/map_markers/marker-shadow.png'),\n iconSize: [25, 41],\n iconAnchor: [12, 41],\n popupAnchor: [1, -34],\n shadowSize: [41, 41]\n })\n }\n```\n\n```text\nL.marker([marker.lat, marker.lng]).addTo(_context.map)\n```\n\n```text\nL.marker([marker.lat, marker.lng], {icon: this.getMarkerIcon(L, \"red\")}).addTo(_context.map)\n```\n\n```text\n'@/...'\n```\n\n```text\nL.icon\n```\n\n```text\nL.divIcon\n```\n\n========================================\n\nComments:\n- What does your browser error console say when trying to load `/assets/img/map_markers/marker-icon-2x-red.png`? Also note that their is no `iconRetinaUrl` defined for your custom marker, I'm not sure if there is a fall-back to a default one.\n- @scai I added `iconRetinaUrl` option but result is the same. No errors in the browser console at all. Simply white rectangle without any error.\n- It works like a charm! Thank you very much. Could you describe more detailed, why `L.icon` works and `L.divIcon` is not?\n- Added more details","metadata":{"transformedAt":"2026-08-18T18:33:07.964Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":105,"estimatedTokens":762}}1016{"id":"stack-77658157","source":"stackoverflow","questionId":77658157,"title":"how to integrate toast prive into nuxt3?","tags":["vue.js","nuxt.js","nuxt3.js","primevue"],"text":"Title: how to integrate toast prive into nuxt3?\nTags: vue.js, nuxt.js, nuxt3.js, primevue\nSource: Stack Overflow\n\nQuestion:\nI'm using the primeVue library. I have not used nuxt before and this component worked for me.\nI registered it as a plugin in main.ts like this.\n\n```\nimport ToastService from \"primevue/toastservice\"\napp.use(ToastService)\n```\n\nHow can I get it to work in nuxt?\nIt immediately throws out the error No PrimeVue Toast provided! as soon as I try to call useToast\n\n========================================\n\nCode:\n```text\nimport ToastService from \"primevue/toastservice\"\napp.use(ToastService)\n```\n\n```js\nimport ToastService from 'primevue/toastservice'\n\nexport default defineNuxtPlugin((nuxtApp) => {\n nuxtApp.vueApp.use(ToastService);\n});\n```\n\n```text\n\"primevue/toastservice\"\n```\n\n```text\nplugins/primevue-toastservice.ts\n```\n\n========================================\n\nComments:\n- if primevue is already in use in nuxt application, this will only result in an ssr warning saying that the plugin is already applied\n- @Allure how about adding the plugin as a client-side-only plugin which ends with `.client.ts` suffix?\n- I don't know if it will cause an error if the primevue was already installed and the toastservice would be added as a client-side plugin. I think it will, but didn't try. Probably it would be cool to split the entire library into server and client side parts, but are you sure that in this we wouldn't have to install all the parts other than toastservice separately and specify they are server-side?","metadata":{"transformedAt":"2026-08-18T18:33:07.964Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":46,"estimatedTokens":385}}1017{"id":"stack-56299811","source":"stackoverflow","questionId":56299811,"title":"Nuxtjs Favicons not showing on iOS Safari when bookmarked","tags":["express","nginx","reverse-proxy","nuxt.js","favicon"],"text":"Title: Nuxtjs Favicons not showing on iOS Safari when bookmarked\nTags: express, nginx, reverse-proxy, nuxt.js, favicon\nSource: Stack Overflow\n\nQuestion:\nI have an issue with Nuxtjs+express using Nginx reverse proxy, that favicons are not showing on iOS Safari when bookmark/favorite only shows the first letter from website title. all my favicons served from static directory and working on safari macOS and all other browsers/platforms, also I have an other app with the same configuration facing the issue. \n\ngenerally I generate all my favicons using https://realfavicongenerator.net/ and I checked my website and all the results are green. I've tried the following but no luck:-\n\n- host favicons on CDN server.\n\n- install @nuxt/pwa to generate all the icons.\n\n- tried dummy icons from other websites\n\n- tested on multiple iOS devices iPad and iPhone cleared the cache, also tried emulators like saucelabs.com\n\n- checked nginx access.log and error.log and restart the server\n\n- restart PM2\n\n- check folder and files permissions\n\n- created dummy website on the same server but without Nuxt and everything worked as expected\n\nnuxt.config.js head option\n\n```\nhead: {\n ...\n link: [\n {\n rel: \"canonical\",\n hid: \"canonical\",\n href: process.env.APP_URL\n },\n {\n rel: \"apple-touch-icon\",\n sizes: \"180x180\",\n href: \"/apple-touch-icon.png?v=GvmpJqoA5j\"\n },\n {\n rel: \"icon\",\n type: \"image/png\",\n sizes: \"32x32\",\n href: \"/favicon-32x32.png?v=GvmpJqoA5j\"\n },\n {\n rel: \"icon\",\n type: \"image/png\",\n sizes: \"192x192\",\n href: \"/android-chrome-192x192.png?v=GvmpJqoA5j\"\n },\n {\n rel: \"icon\",\n type: \"image/png\",\n sizes: \"16x16\",\n href: \"/favicon-16x16.png?v=GvmpJqoA5j\"\n },\n {\n rel: \"manifest\",\n href: \"/site.webmanifest?v=GvmpJqoA5j\"\n },\n {\n rel: \"mask-icon\",\n href: \"/safari-pinned-tab.svg?v=GvmpJqoA5j\",\n color: \"#611e75\"\n },\n {\n rel: \"shortcut icon\",\n href: \"/favicon.ico?v=GvmpJqoA5j\",\n type: \"image/x-icon\"\n },\n {\n rel: \"icon\",\n href: \"/favicon.ico?v=GvmpJqoA5j\",\n type: \"image/x-icon\"\n }\n ],\n ...\n },\n```\n\nnginx \n\n```\nmap $sent_http_content_type $expires {\n \"text/html\" epoch;\n \"text/html; charset=utf-8\" epoch;\n default off; # set this to your needs\n}\n\nserver {\n listen 80;\n listen [::]:80;\n server_name www.example.com;\n return 301 https://www.example.fm$request_uri;\n\n}\n\nserver {\n listen 443 ssl http2;\n listen [::]:443 ssl http2;\n ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem; # managed by Certbot\n ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem; # managed by Certbot\n include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot\n ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot\n\n server_name www.example.com;\n rewrite ^/(.*)/$ /$1 permanent;\n\n gzip on;\n gzip_types text/plain application/xml text/css application/javascript;\n gzip_min_length 1000;\n\n location / {\n expires $expires;\n ########### tried to disable below block\nadd_header X-Frame-Options \"SAMEORIGIN\" always;\n add_header X-XSS-Protection \"1; mode=block\" always;\n add_header X-Content-Type-Options \"nosniff\" always;\n add_header Referrer-Policy \"no-referrer-when-downgrade\" always;\n add_header Content-Security-Policy \"default-src * data: 'unsafe- \n eval' 'unsafe-inline'\" always;\n\n # Simple requests\n if ($request_method ~* \"(GET|POST)\") {\n add_header \"Access-Control-Allow-Origin\" *;\n }\n\n # Preflighted requests\n if ($request_method = OPTIONS ) {\n add_header \"Access-Control-Allow-Origin\" *;\n add_header \"Access-Control-Allow-Methods\" \"GET, POST, OPTIONS, HEAD\";\n\n add_header \"Access-Control-Allow-Headers\" \"Authorization, Origin, X-Requested-With, Content-Type, Accept,x-key\";\n return 200;\n }\n proxy_hide_header X-Powered-By;\n proxy_cache_bypass $http_upgrade;\n\n proxy_redirect off;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_read_timeout 1m;\n proxy_connect_timeout 1m;\n proxy_pass http://127.0.0.1:8003; \n }\n}\n```\n\nAll favicons are accessible with no issue when go to https://www.example.com/favicon.ico.\n\nany help would be appreciated\n\n========================================\n\nCode:\n```text\nhead: {\n ...\n link: [\n {\n rel: \"canonical\",\n hid: \"canonical\",\n href: process.env.APP_URL\n },\n {\n rel: \"apple-touch-icon\",\n sizes: \"180x180\",\n href: \"/apple-touch-icon.png?v=GvmpJqoA5j\"\n },\n {\n rel: \"icon\",\n type: \"image/png\",\n sizes: \"32x32\",\n href: \"/favicon-32x32.png?v=GvmpJqoA5j\"\n },\n {\n rel: \"icon\",\n type: \"image/png\",\n sizes: \"192x192\",\n href: \"/android-chrome-192x192.png?v=GvmpJqoA5j\"\n },\n {\n rel: \"icon\",\n type: \"image/png\",\n sizes: \"16x16\",\n href: \"/favicon-16x16.png?v=GvmpJqoA5j\"\n },\n {\n rel: \"manifest\",\n href: \"/site.webmanifest?v=GvmpJqoA5j\"\n },\n {\n rel: \"mask-icon\",\n href: \"/safari-pinned-tab.svg?v=GvmpJqoA5j\",\n color: \"#611e75\"\n },\n {\n rel: \"shortcut icon\",\n href: \"/favicon.ico?v=GvmpJqoA5j\",\n type: \"image/x-icon\"\n },\n {\n rel: \"icon\",\n href: \"/favicon.ico?v=GvmpJqoA5j\",\n type: \"image/x-icon\"\n }\n ],\n ...\n },\n```\n\n```text\nmap $sent_http_content_type $expires {\n \"text/html\" epoch;\n \"text/html; charset=utf-8\" epoch;\n default off; # set this to your needs\n}\n\nserver {\n listen 80;\n listen [::]:80;\n server_name www.example.com;\n return 301 https://www.example.fm$request_uri;\n\n}\n\n\nserver {\n listen 443 ssl http2;\n listen [::]:443 ssl http2;\n ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem; # managed by Certbot\n ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem; # managed by Certbot\n include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot\n ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot\n\n server_name www.example.com;\n rewrite ^/(.*)/$ /$1 permanent;\n\n gzip on;\n gzip_types text/plain application/xml text/css application/javascript;\n gzip_min_length 1000;\n\n location / {\n expires $expires;\n ########### tried to disable below block\nadd_header X-Frame-Options \"SAMEORIGIN\" always;\n add_header X-XSS-Protection \"1; mode=block\" always;\n add_header X-Content-Type-Options \"nosniff\" always;\n add_header Referrer-Policy \"no-referrer-when-downgrade\" always;\n add_header Content-Security-Policy \"default-src * data: 'unsafe- \n eval' 'unsafe-inline'\" always;\n\n # Simple requests\n if ($request_method ~* \"(GET|POST)\") {\n add_header \"Access-Control-Allow-Origin\" *;\n }\n\n # Preflighted requests\n if ($request_method = OPTIONS ) {\n add_header \"Access-Control-Allow-Origin\" *;\n add_header \"Access-Control-Allow-Methods\" \"GET, POST, OPTIONS, HEAD\";\n\n add_header \"Access-Control-Allow-Headers\" \"Authorization, Origin, X-Requested-With, Content-Type, Accept,x-key\";\n return 200;\n }\n proxy_hide_header X-Powered-By;\n proxy_cache_bypass $http_upgrade;\n\n proxy_redirect off;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_read_timeout 1m;\n proxy_connect_timeout 1m;\n proxy_pass http://127.0.0.1:8003; \n }\n}\n```\n\n```text\nlocation ~ \\.(ico|png|jpg|jpeg|woff) {\n root /var/www/example.com/static;\n add_header Cache-Control 'public, must-revalidate, proxy-revalidate, max-age=31557600';\n access_log off;\n proxy_redirect off;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.965Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":297,"estimatedTokens":2031}}1018{"id":"stack-76836058","source":"stackoverflow","questionId":76836058,"title":"Error: Cannot find module 'node:util' while running the nuxt project using npm run command","tags":["javascript","node.js","nuxt.js","node-modules","package.json"],"text":"Title: Error: Cannot find module 'node:util' while running the nuxt project using npm run command\nTags: javascript, node.js, nuxt.js, node-modules, package.json\nSource: Stack Overflow\n\nQuestion:\nI created a new nuxt 2 project using the following commands\n\n`npm init nuxt-app `\n\nafter the `npm install` command when i try to run it using `npm run dev` it throws the follwing error (attached image)\n\ninternal/modules/cjs/loader.js:883\nthrow err;\n\n^\n\nError: Cannot find module 'node:util'\nRequire stack:\n\nPackage.json\n\n```\n{\n \"name\": \"test\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"bootstrap\": \"^4.6.2\",\n \"bootstrap-vue\": \"^2.22.0\",\n \"core-js\": \"^3.25.3\",\n \"nuxt\": \"^2.15.8\",\n \"vue\": \"^2.7.10\",\n \"vue-server-renderer\": \"^2.7.10\",\n \"vue-template-compiler\": \"^2.7.10\"\n },\n \"devDependencies\": {}\n}\n```\n\nnode version : v14.16.1\nnpm version : 6.14.12\nnuxt version: 2.15.8\n\ni've tried the following:\n\ndeleting node_modules and package-lock\nnpm cache clean --force\nnpm i\nnpm ci\nnpm run dev\n\ninstalling nuxt utils\n\nnone of these work\n\nscreenshot\n\n========================================\n\nTop Answer:\nI had the same problem in my nuxt project. For me removing the `^ (caret symbol)` did not work. So I tried to test different node versions in my system to see which one solve the problem. I say my steps for others, although I'm not sure that this is working for all projects:\n\n- remove `node_modules` folder and `package-lock.json` file from the root directory of nuxt project.\n\n- I also removed `.nuxt` folder from the root directory of nuxt project.\n\n- run the `npm cache clean --force` in command line.\n\n- run `npm install` command to install modules.\n\n- run `npm run dev` command to start project.\n\nI used these steps with different node versions in my system. Each time I change the node version, I again started from step 1. To do that easily you can use **node version manager** or **nvm** in your system.\n\nfinally for a project with this `package.json` file, I found that node version 14.19.0 is solving the problem.\n\n```\n\"dependencies\": {\n \"@mdi/font\": \"^5.9.55\",\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/markdownit\": \"^2.0.0\",\n \"@nuxtjs/pwa\": \"^3.3.5\",\n \"@nuxtjs/strapi\": \"^0.3.1\",\n \"animate.css\": \"^4.1.1\",\n \"core-js\": \"^3.15.1\",\n \"highlight.js\": \"^11.6.0\",\n \"js-cookie\": \"^3.0.1\",\n \"markdown-it-footnote\": \"^3.0.3\",\n \"nuxt\": \"^2.15.7\",\n \"nuxt-speedkit\": \"^2.1.2\",\n \"swiper\": \"^6.8.3\",\n \"v-owl-carousel\": \"^1.0.8\",\n \"vue-async-computed\": \"^3.9.0\",\n \"vue-awesome-swiper\": \"^4.1.1\",\n \"vue-infinite-loading\": \"^2.4.5\",\n \"vue-slick-carousel\": \"^1.0.6\",\n \"vuetify\": \"^2.5.5\"\n },\n \"devDependencies\": {\n \"@nuxt/image\": \"^0.7.1\",\n \"@nuxtjs/vuetify\": \"^1.12.1\"\n }\n```\n\nIn my solution you do not need to remove the `^ (caret symbol)`. So my project is using nuxt `v2.18.1` with node `v14.19.0`\n\n========================================\n\nCode:\n```text\n{\n \"name\": \"test\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"nuxt\",\n \"build\": \"nuxt build\",\n \"start\": \"nuxt start\",\n \"generate\": \"nuxt generate\"\n },\n \"dependencies\": {\n \"bootstrap\": \"^4.6.2\",\n \"bootstrap-vue\": \"^2.22.0\",\n \"core-js\": \"^3.25.3\",\n \"nuxt\": \"^2.15.8\",\n \"vue\": \"^2.7.10\",\n \"vue-server-renderer\": \"^2.7.10\",\n \"vue-template-compiler\": \"^2.7.10\"\n },\n \"devDependencies\": {}\n}\n```\n\n```text\nnpm init nuxt-app <project-name>\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run dev\n```\n\n```text\nthe nuxt version in package.json to \"2.15.8\" and removed the ^ (caret symbol) , which was upgrading the dependencies\n```\n\n```text\n\"dependencies\": {\n \"@mdi/font\": \"^5.9.55\",\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/markdownit\": \"^2.0.0\",\n \"@nuxtjs/pwa\": \"^3.3.5\",\n \"@nuxtjs/strapi\": \"^0.3.1\",\n \"animate.css\": \"^4.1.1\",\n \"core-js\": \"^3.15.1\",\n \"highlight.js\": \"^11.6.0\",\n \"js-cookie\": \"^3.0.1\",\n \"markdown-it-footnote\": \"^3.0.3\",\n \"nuxt\": \"^2.15.7\",\n \"nuxt-speedkit\": \"^2.1.2\",\n \"swiper\": \"^6.8.3\",\n \"v-owl-carousel\": \"^1.0.8\",\n \"vue-async-computed\": \"^3.9.0\",\n \"vue-awesome-swiper\": \"^4.1.1\",\n \"vue-infinite-loading\": \"^2.4.5\",\n \"vue-slick-carousel\": \"^1.0.6\",\n \"vuetify\": \"^2.5.5\"\n },\n \"devDependencies\": {\n \"@nuxt/image\": \"^0.7.1\",\n \"@nuxtjs/vuetify\": \"^1.12.1\"\n }\n```\n\n```text\n^ (caret symbol)\n```\n\n```text\nnode_modules\n```\n\n```text\npackage-lock.json\n```\n\n```text\n.nuxt\n```\n\n```text\nnpm cache clean --force\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run dev\n```\n\n```text\npackage.json\n```\n\n```text\n^ (caret symbol)\n```\n\n```text\nv2.18.1\n```\n\n```text\nv14.19.0\n```\n\n========================================\n\nComments:\n- Did you update your node version?\n- @miltonbhowmick i updated it to 16.10.0, still throws the same error.\n- FIxed the error by changing the nuxt version in package.json to **\"2.15.8\"** (removed the **^** , which was upgrading the dependencies)","metadata":{"transformedAt":"2026-08-18T18:33:07.965Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":233,"estimatedTokens":1237}}1019{"id":"stack-55938705","source":"stackoverflow","questionId":55938705,"title":"Service Worker registration fails with firebase hosting and functions","tags":["firebase","nuxt.js","workbox"],"text":"Title: Service Worker registration fails with firebase hosting and functions\nTags: firebase, nuxt.js, workbox\nSource: Stack Overflow\n\nQuestion:\nService Worker is not registered with an application builded by Nuxt.js (Universal) which is running on Firebase Functions.\n\nI'm currently trying to build a prototype web application with Nuxt.js Universal mode and Firebase Functions.\nThe app uses service worker with nuxt official pwa-module to manage the session of logged in user, so that the client could send the request with authorization header to the server and server would verify the user session via Firebase Authentication.\n\nI've already tried to run it on local server with `yarn run build` and `yarn run start`, and ensured the service worker have been correctly registered and worked perfectly.\nHowever when I try to check the same operation with `firebase serve`, I receive following errors on the browser.\n\n```\nA bad HTTP response code (404) was received when fetching the script.\nFailed to load resource: net::ERR_INVALID_RESPONSE\ndcbac67bb39a765db27a.js:1 Service worker registration failed: TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.\n```\n\nI also found that the service worker does not send the session data to the server. Exactly same thing was reproduced when I deployed source into production with `firebase deploy`.\n\nIt even occurs when I completely clean project with `yarn create nuxt-app`, `yarn run build` and `firebase serve`. \"sw.js\" file indicates failed status on Chrome developer tool.\n\nI'm not sure if it is concerned but my Firebase is on Spark plan.\n\nMy project tree.\n\n```\n.\n├── firebase.json\n├── firestore.indexes.json\n├── firestore.rules\n├── functions\n│ ├── index.js\n│ ├── nuxt\n│ │ ├── App.js\n│ │ ├── axios.js\n│ │ ├── client.js\n│ │ ├── components\n│ │ ├── dist\n│ │ ├── empty.js\n│ │ ├── index.js\n│ │ ├── loading.html\n│ │ ├── middleware.js\n│ │ ├── router.js\n│ │ ├── server.js\n│ │ ├── store.js\n│ │ ├── sw.plugin.js\n│ │ ├── sw.template.js\n│ │ ├── utils.js\n│ │ └── views\n│ ├── package-lock.json\n│ ├── package.json\n│ └── yarn.lock\n├── public\n└── src\n ├── assets\n ├── components\n ├── jest.config.js\n ├── layouts\n ├── middleware\n ├── nuxt.config.js\n ├── package.json\n ├── pages\n ├── plugins\n ├── server\n ├── static\n │ └── sw.js\n ├── store\n └── test\n └── yarn.lock\n```\n\nsrc/static/sw.js\n\n```\nimportScripts('/_nuxt/workbox.4c4f5ca6.js')\n\nworkbox.precaching.precacheAndRoute([\n {\n \"url\": \"/_nuxt/021e1640b53136b75c48.js\",\n \"revision\": \"2753e747206d803c793b59a324c1931b\"\n },\n {\n \"url\": \"/_nuxt/03c9e340d8692d1403a9.js\",\n \"revision\": \"2b882d73d20a0b2cfd318e9e05d3496e\"\n },\n {\n \"url\": \"/_nuxt/78bddfa6b6a4919b78d6.js\",\n \"revision\": \"70312f6623089e3b4aa6454120c1e177\"\n },\n {\n \"url\": \"/_nuxt/85c817abccdd40162004.js\",\n \"revision\": \"45448f8709d01af59bb125a1d06be23a\"\n },\n {\n \"url\": \"/_nuxt/8654a518d0f3e326c9a6.js\",\n \"revision\": \"a42426f5e7b458acc6fdf0e9e48c7d35\"\n },\n {\n \"url\": \"/_nuxt/95b421159066eff9e318.js\",\n \"revision\": \"efd1643042f804defa7212979867558a\"\n },\n {\n \"url\": \"/_nuxt/9b487bf2df1190b68565.js\",\n \"revision\": \"78837d0e624deccc85761b44f9ede9be\"\n },\n {\n \"url\": \"/_nuxt/ce59381752309c170d41.js\",\n \"revision\": \"d3e50bf27891c4efa6dff5076a0772a6\"\n },\n {\n \"url\": \"/_nuxt/d8fa6ae5ca14331879f6.js\",\n \"revision\": \"5da6698c9359df803243ecc44519b610\"\n },\n {\n \"url\": \"/_nuxt/dcbac67bb39a765db27a.js\",\n \"revision\": \"9505aa84ddb2a70b826d324433daff36\"\n },\n {\n \"url\": \"/_nuxt/dee89eef613849499c7f.js\",\n \"revision\": \"43117ed819efe3d00c963dd655894d5f\"\n }\n], {\n \"cacheId\": \"justtest\",\n \"directoryIndex\": \"/\",\n \"cleanUrls\": false\n})\n\nworkbox.clientsClaim()\nworkbox.skipWaiting()\n\nworkbox.routing.registerRoute(new RegExp('/_nuxt/.*'), workbox.strategies.cacheFirst({}), 'GET')\n\nworkbox.routing.registerRoute(new RegExp('/.*'), workbox.strategies.networkFirst({}), 'GET')\n```\n\nfunctions/index.js\n\n```\nconst functions = require(\"firebase-functions\")\nconst { Nuxt } = require(\"nuxt\")\nconst express = require(\"express\")\nconst app = express()\n\nconst nuxt = new Nuxt({ buildDir: \"nuxt\", dev: false })\n\nfunction handleRequest(req, res) {\n res.setHeader('Cache-Control', 'private')\n return new Promise((resolve, reject) => {\n nuxt.render(req, res, promise => {\n promise.then(resolve).catch(reject)\n })\n })\n}\n\napp.use(handleRequest)\n\nexports.ssr = functions.https.onRequest(app)\n```\n\nExpected behavior is that sw.js working fine when I run the app with `firebase serve` and `firebase deploy`.\n\n========================================\n\nTop Answer:\n### Fellow Nuxt.js developers in 2020, Jun\n\nIf you are deploying Nuxt.js 2.12.2 project with SSR, you probably have `.nuxt` folder in your project directory. Delete that, configure Workbox from `nuxt.config.js` if you need and run `nuxt build`, `npm run build` or `yarn build`. \n\nIf it works on local machine, you can try clearing caches on server to make sure all old `.nuxt` folders are gone and redeploy the project.\n\nHope this helps ✨\n\n========================================\n\nCode:\n```text\nA bad HTTP response code (404) was received when fetching the script.\nFailed to load resource: net::ERR_INVALID_RESPONSE\ndcbac67bb39a765db27a.js:1 Service worker registration failed: TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.\n```\n\n```text\n.\n├── firebase.json\n├── firestore.indexes.json\n├── firestore.rules\n├── functions\n│ ├── index.js\n│ ├── nuxt\n│ │ ├── App.js\n│ │ ├── axios.js\n│ │ ├── client.js\n│ │ ├── components\n│ │ ├── dist\n│ │ ├── empty.js\n│ │ ├── index.js\n│ │ ├── loading.html\n│ │ ├── middleware.js\n│ │ ├── router.js\n│ │ ├── server.js\n│ │ ├── store.js\n│ │ ├── sw.plugin.js\n│ │ ├── sw.template.js\n│ │ ├── utils.js\n│ │ └── views\n│ ├── package-lock.json\n│ ├── package.json\n│ └── yarn.lock\n├── public\n└── src\n ├── assets\n ├── components\n ├── jest.config.js\n ├── layouts\n ├── middleware\n ├── nuxt.config.js\n ├── package.json\n ├── pages\n ├── plugins\n ├── server\n ├── static\n │ └── sw.js\n ├── store\n └── test\n └── yarn.lock\n```\n\n```text\nimportScripts('/_nuxt/workbox.4c4f5ca6.js')\n\nworkbox.precaching.precacheAndRoute([\n {\n \"url\": \"/_nuxt/021e1640b53136b75c48.js\",\n \"revision\": \"2753e747206d803c793b59a324c1931b\"\n },\n {\n \"url\": \"/_nuxt/03c9e340d8692d1403a9.js\",\n \"revision\": \"2b882d73d20a0b2cfd318e9e05d3496e\"\n },\n {\n \"url\": \"/_nuxt/78bddfa6b6a4919b78d6.js\",\n \"revision\": \"70312f6623089e3b4aa6454120c1e177\"\n },\n {\n \"url\": \"/_nuxt/85c817abccdd40162004.js\",\n \"revision\": \"45448f8709d01af59bb125a1d06be23a\"\n },\n {\n \"url\": \"/_nuxt/8654a518d0f3e326c9a6.js\",\n \"revision\": \"a42426f5e7b458acc6fdf0e9e48c7d35\"\n },\n {\n \"url\": \"/_nuxt/95b421159066eff9e318.js\",\n \"revision\": \"efd1643042f804defa7212979867558a\"\n },\n {\n \"url\": \"/_nuxt/9b487bf2df1190b68565.js\",\n \"revision\": \"78837d0e624deccc85761b44f9ede9be\"\n },\n {\n \"url\": \"/_nuxt/ce59381752309c170d41.js\",\n \"revision\": \"d3e50bf27891c4efa6dff5076a0772a6\"\n },\n {\n \"url\": \"/_nuxt/d8fa6ae5ca14331879f6.js\",\n \"revision\": \"5da6698c9359df803243ecc44519b610\"\n },\n {\n \"url\": \"/_nuxt/dcbac67bb39a765db27a.js\",\n \"revision\": \"9505aa84ddb2a70b826d324433daff36\"\n },\n {\n \"url\": \"/_nuxt/dee89eef613849499c7f.js\",\n \"revision\": \"43117ed819efe3d00c963dd655894d5f\"\n }\n], {\n \"cacheId\": \"justtest\",\n \"directoryIndex\": \"/\",\n \"cleanUrls\": false\n})\n\nworkbox.clientsClaim()\nworkbox.skipWaiting()\n\nworkbox.routing.registerRoute(new RegExp('/_nuxt/.*'), workbox.strategies.cacheFirst({}), 'GET')\n\nworkbox.routing.registerRoute(new RegExp('/.*'), workbox.strategies.networkFirst({}), 'GET')\n```\n\n```text\nconst functions = require(\"firebase-functions\")\nconst { Nuxt } = require(\"nuxt\")\nconst express = require(\"express\")\nconst app = express()\n\nconst nuxt = new Nuxt({ buildDir: \"nuxt\", dev: false })\n\nfunction handleRequest(req, res) {\n res.setHeader('Cache-Control', 'private')\n return new Promise((resolve, reject) => {\n nuxt.render(req, res, promise => {\n promise.then(resolve).catch(reject)\n })\n })\n}\n\napp.use(handleRequest)\n\nexports.ssr = functions.https.onRequest(app)\n```\n\n```text\nyarn run build\n```\n\n```text\nyarn run start\n```\n\n```text\nfirebase serve\n```\n\n```text\nfirebase deploy\n```\n\n```text\nyarn create nuxt-app\n```\n\n```text\nyarn run build\n```\n\n```text\nfirebase serve\n```\n\n```text\nfirebase serve\n```\n\n```text\nfirebase deploy\n```\n\n```text\n.\n├── firebase.json\n├── functions\n│ ├── index.js\n│ ├── nuxt\n│ │ ├── App.js\n│ │ ├── axios.js\n│ │ ├── client.js\n│ │ ├── components\n│ │ ├── dist\n│ │ ├── empty.js\n│ │ ├── index.js\n│ │ ├── loading.html\n│ │ ├── middleware.js\n│ │ ├── router.js\n│ │ ├── server.js\n│ │ ├── store.js\n│ │ ├── sw.plugin.js\n│ │ ├── sw.template.js\n│ │ ├── utils.js\n│ │ └── views\n│ ├── package-lock.json\n│ ├── package.json\n│ └── yarn.lock\n├── public\n│ ├── favicon.ico\n│ ├── sw-firebase-auth.js\n│ └── sw.js\n└── src\n ├── assets\n ├── components\n ├── layouts\n ├── middleware\n ├── nuxt.config.js\n ├── package.json\n ├── pages\n ├── plugins\n ├── server\n ├── static\n │ ├── favicon.ico\n │ ├── sw-firebase-auth.js\n │ └── sw.js\n ├── store\n └── yarn.lock\n```\n\n```text\nvar firebase = require('firebase')\n\n// Initialize the Firebase app in the service worker script.\nfirebase.initializeApp({\n apiKey: '*************',\n authDomain: '*************',\n databaseURL: '*************',\n projectId: '*************',\n storageBucket: '*************',\n messagingSenderId: '*************'\n})\n\n/**\n * Returns a promise that resolves with an ID token if available.\n * @return {!Promise<?string>} The promise that resolves with an ID token if\n * available. Otherwise, the promise resolves with null.\n */\nconst getIdToken = () => {\n return new Promise((resolve) => {\n const unsubscribe = firebase.auth().onAuthStateChanged((user) => {\n unsubscribe();\n if (user) {\n user.getIdToken().then((idToken) => {\n resolve(idToken)\n }, () => {\n resolve(null)\n });\n } else {\n resolve(null)\n }\n })\n })\n}\n\nconst getOriginFromUrl = (url) => {\n const pathArray = url.split('/');\n const protocol = pathArray[0];\n const host = pathArray[2];\n return protocol + '//' + host;\n};\n\nself.addEventListener('fetch', (event) => {\n const requestProcessor = (idToken) => {\n let req = event.request;\n if (self.location.origin == getOriginFromUrl(event.request.url) &&\n (self.location.protocol == 'https:' ||\n self.location.hostname == 'localhost') &&\n idToken) {\n const headers = new Headers();\n for (let entry of req.headers.entries()) {\n headers.append(entry[0], entry[1]);\n }\n headers.append('Authorization', 'Bearer ' + idToken);\n try {\n req = new Request(req.url, {\n method: req.method,\n headers: headers,\n mode: 'same-origin',\n credentials: req.credentials,\n cache: req.cache,\n redirect: req.redirect,\n referrer: req.referrer,\n body: req.body,\n bodyUsed: req.bodyUsed,\n context: req.context\n });\n } catch (e) {\n console.log(e)\n }\n }\n return fetch(req);\n };\n event.respondWith(getIdToken().then(requestProcessor, requestProcessor));\n});\n\nself.addEventListener('activate', event => {\n event.waitUntil(clients.claim());\n})\n```\n\n```text\nworkbox: {\n importScripts: [\n 'sw-firebase-auth.js'\n ]\n }\n```\n\n```text\n/static/sw.js\n```\n\n```text\nyarn run build\n```\n\n```text\nyarn run start\n```\n\n```text\n/static\n```\n\n```text\n/public\n```\n\n```text\nyarn run start\n```\n\n```text\n/static\n```\n\n```text\ndist/client\n```\n\n```text\n/public\n```\n\n```text\nyarn run build\n```\n\n```text\n/src/static\n```\n\n```text\n/public\n```\n\n```text\nsw-firebase-auth.js\n```\n\n```text\nnuxt.conf.js\n```\n\n```text\nimportScripts\n```\n\n```text\n.nuxt\n```\n\n```text\nnuxt.config.js\n```\n\n```text\nnuxt build\n```\n\n```text\nnpm run build\n```\n\n```text\nyarn build\n```\n\n```text\n.nuxt\n```\n\n========================================\n\nComments:\n- What if I use SSR? I don't really have a public folder :/\n- @Pixsa what'd you end up doing?","metadata":{"transformedAt":"2026-08-18T18:33:07.965Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":37,"totalLines":574,"estimatedTokens":3067}}1020{"id":"stack-53913342","source":"stackoverflow","questionId":53913342,"title":"Injecting Function in Nuxt","tags":["javascript","vue.js","vuejs2","nuxt.js"],"text":"Title: Injecting Function in Nuxt\nTags: javascript, vue.js, vuejs2, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nI try to inject a function inside my plugin\n\nplugin.js\n\n```\nimport Vue from 'vue'\nimport mediumZoom from 'medium-zoom'\n\nVue.prototype.$mediumZoom = mediumZoom()\n```\n\nWhen I try to load my page it keeps loading infinite and the page in the end doesnt react, it looks like this:\nhttps://i.sstatic.net/IzzZT.png\n\n========================================\n\nCode:\n```text\nimport Vue from 'vue'\nimport mediumZoom from 'medium-zoom'\n\nVue.prototype.$mediumZoom = mediumZoom()\n```\n\n```text\nVue.prototype.$mediumZoom = mediumZoom\n// don't call function, no () here ---^\n```\n\n```text\nmediumZoom\n```","metadata":{"transformedAt":"2026-08-18T18:33:07.965Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":37,"estimatedTokens":174}}1021{"id":"stack-53989147","source":"stackoverflow","questionId":53989147,"title":"Access to Vuex store state from a component using Nuxt","tags":["javascript","vue.js","vuejs2","vuex","nuxt.js"],"text":"Title: Access to Vuex store state from a component using Nuxt\nTags: javascript, vue.js, vuejs2, vuex, nuxt.js\nSource: Stack Overflow\n\nQuestion:\nhttps://i.sstatic.net/htnuL.png\n\nI'm trying to pass a list of button names into a menu component from the Vuex store following https://nuxtjs.org/guide/vuex-store\n\nmy /store/store.js:\n\n```\nexport const state = () => ({\n 'toolbarActions' : [ 'My project', 'Home', 'About', 'Contact' ]\n})\n```\n\nMy menu component:\n\n```\n\n \n \n Title\n \n \n {{action}}\n {{action}} -->\n Link One\n Link Two\n Link Three -->\n \n \n\n// import toolbarActions from '~/store/store.js'\n\nexport default {\ncomputed: {\n toolbarActions() {\n return this.$store.state.toolbarActions\n\n // return [ 'My project', 'Home', 'About', 'Contact' ]\n }\n }\n}\n\n```\n\nIf I uncomment:\n\n```\n// return [ 'My project', 'Home', 'About', 'Contact' ]\n```\n\nand comment:\n\n```\nreturn this.$store.state.toolbarActions\n```\n\nThe button names are passed into the component. but with \n\n```\nreturn this.$store.state.toolbarActions\n```\n\nnot commented, nothing is passed in.\n\nHow do I access the Vuex store here to pass in the button names?\n\nEDIT: I've made the changes, I'm getting:\n\n```\nERROR [Vue warn]: Error in render: \"TypeError: Cannot read property \n 'toolbarActions' of undefined\" \n 11:52:20\n\n found in\n\n ---> at components/menu.vue\n at layouts/default.vue\n \n\n » store\\_toolbar.js\n```\n\n========================================\n\nTop Answer:\nBetter option may be \n\n```\nimport {mapGetters} from 'vuex';\n```\n\nand use like\n\n```\ncomputed:mapGetters({\n toolbarActions:'toolbar/toolbarActions'\n})\n```\n\n========================================\n\nCode:\n```text\nexport const state = () => ({\n 'toolbarActions' : [ 'My project', 'Home', 'About', 'Contact' ]\n})\n```\n\n```text\n<template>\n <v-toolbar color=\"indigo\" dark>\n <v-toolbar-side-icon></v-toolbar-side-icon>\n <v-toolbar-title class=\"white--text\">Title</v-toolbar-title>\n <v-spacer></v-spacer>\n <v-toolbar-items class=\"hidden-sm-and-down\">\n <v-btn flat v-for=\"action in toolbarActions\" :key=\"action\">{{action}}</v-btn>\n <!-- <v-btn flat v-for=\"action in toolbarActions\">{{action}}</v-btn> -->\n <!-- <v-btn flat>Link One</v-btn>\n <v-btn flat>Link Two</v-btn>\n <v-btn flat>Link Three</v-btn> -->\n </v-toolbar-items>\n </v-toolbar>\n</template>\n\n<script>\n\n// import toolbarActions from '~/store/store.js'\n\nexport default {\ncomputed: {\n toolbarActions() {\n return this.$store.state.toolbarActions\n\n // return [ 'My project', 'Home', 'About', 'Contact' ]\n }\n }\n}\n</script>\n```\n\n```text\n// return [ 'My project', 'Home', 'About', 'Contact' ]\n```\n\n```text\nreturn this.$store.state.toolbarActions\n```\n\n```text\nreturn this.$store.state.toolbarActions\n```\n\n```text\nERROR [Vue warn]: Error in render: \"TypeError: Cannot read property \n 'toolbarActions' of undefined\" \n 11:52:20\n\n found in\n\n ---> <Menu> at components/menu.vue\n <Default> at layouts/default.vue\n <Root>\n\n » store\\_toolbar.js\n```\n\n```text\nexport const state = () => ({\n 'toolbarActions' : [ 'My project', 'Home', 'About', 'Contact' ]\n })\n```\n\n```text\n.\n.\n> static\nv store\n |_toolbar.js\n```\n\n```text\ncomputed: {\n toolbarActions() {\n return this.$store.state.toolbar.toolbarActions //look i added the name of the toolbar module\n // ^___________\n\n }\n }\n}\n```\n\n```text\ntoolbar\n```\n\n```text\ncomputed\n```\n\n```text\nimport {mapGetters} from 'vuex';\n```\n\n```text\ncomputed:mapGetters({\n toolbarActions:'toolbar/toolbarActions'\n})\n```\n\n========================================\n\nComments:\n- what's the issue ?\n- @BoussadjraBrahim is that clearer?\n- yes it's clear but i recommend to the store code as text not as screenshot\n- @BoussadjraBrahim I've added ir above\n- the file name should be `toolbar.js` not `_toolbar.js` please remove the `_`\n- I've made the changes. Its working! Based on this I understand the state.toolbar.toolbaractions. But where does \"this.$store\" come from?\n- read this nuxtjs.org/guide/vuex-store#activate-the-store, nuxt will automatically inject `store` property inside vue instance `new Vue()`\n- Thanks very much!\n- from those docs - > We don't need to install vuex since it's shipped with Nuxt.js. We can now use this.$store inside our components: {{ $store.state.counter }}\n- you could but it's not a good practice, try to not put a lot of logic inside the template, something like `@click=\"'increment\"` is more clean than `@click=\"$store.commit('increment')\"`","metadata":{"transformedAt":"2026-08-18T18:33:07.965Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":226,"estimatedTokens":1147}}1022 