Nuxt 3 + Vite & HMR : infinite reload & failed - vue.js

On a fresh install of Nuxt3, using Docker, I have this error on the console and an infinite reload of the page :
client.ts:28 WebSocket connection to 'wss://shop.store.local/_nuxt/'
failed: (anonyme) # client:188 client.ts:224 [vite] server connection
lost. polling for restart...
Here is the configuration of my vite server (via nuxt.config.js):
vite: {
server: {
hmr: {
host: 'shop.store.local',
port: 443,
}
}
}
The docker-compose describes the Traefik labels:
vuejs:
labels:
- "traefik.http.routers.front_store.rule=Host(`shop.store.local`)"
- "traefik.http.routers.front_store.tls=true"
- "traefik.http.services.front_store.loadbalancer.server.port=3000"
What I've tried too, in my package.json file:
"scripts": {
"dev": "nuxi dev --host=0.0.0.0",
"build": "nuxi build",
"start": "node .output/server/index.mjs"
},
Any idea ? I looked over internet, people have the problem, but no solution...

Expose ports for nuxt container.
ports:
3000:3000
24678:24678
Also edit your nuxt.config:
vite: {
server: {
host: "0.0.0.0",
hmr: {
},
},
},

Related

Connection error: docker compose: Loopback4 + Mongo

I run the project with:
clean volumes & containers, then docker compose up --build
Tried creating different users for mongo. Made different settings for the docker file. For docker compose.
I assume that the error is somewhere between loopback & mongodb container.
For watch changes i use tsc-watch. Dont know it cause any bugs here, not sure.
Configuration
package.json
{
"name": "lympha-backend",
"version": "0.0.1",
"description": "lympha backend",
"keywords": [
"loopback-application",
"loopback"
],
"main": "dist/index.js",
"types": "dist/index.d.ts",
"engines": {
"node": "14 || 16 || 18 || 19"
},
"scripts": {
"dev": "tsc-watch --target es2017 --outDir ./dist --onSuccess \"node .\"",
"build": "lb-tsc",
"build:watch": "lb-tsc --watch",
"watch": "lb-tsc --watch",
"lint": "yarn run eslint && yarn run prettier:check",
"lint:fix": "yarn run eslint:fix && yarn run prettier:fix",
"prettier:cli": "lb-prettier \"**/*.ts\" \"**/*.js\"",
"prettier:check": "yarn run prettier:cli -l",
"prettier:fix": "yarn run prettier:cli --write",
"eslint": "lb-eslint --report-unused-disable-directives .",
"eslint:fix": "yarn run eslint --fix",
"pretest": "yarn run rebuild",
"test": "lb-mocha --allow-console-logs \"dist/__tests__\"",
"posttest": "yarn run lint",
"test:dev": "lb-mocha --allow-console-logs dist/__tests__/**/*.js && yarn run posttest",
"docker:build": "docker build -t lympha-backend .",
"docker:run": "docker run -p 3000:3000 -d lympha-backend",
"premigrate": "yarn run build",
"migrate": "node ./dist/migrate",
"preopenapi-spec": "yarn run build",
"openapi-spec": "node ./dist/openapi-spec",
"prestart": "yarn run rebuild",
"start": "node -r source-map-support/register .",
"clean": "lb-clean dist *.tsbuildinfo .eslintcache",
"rebuild": "yarn run clean && yarn run build"
},
"repository": {
"type": "git",
"url": ""
},
"license": "",
"files": [
"README.md",
"dist",
"src",
"!*/__tests__"
],
"dependencies": {
"#loopback/boot": "^5.0.7",
"#loopback/core": "^4.0.7",
"#loopback/repository": "^5.1.2",
"#loopback/rest": "^12.0.7",
"#loopback/rest-crud": "^0.15.6",
"#loopback/rest-explorer": "^5.0.7",
"#loopback/service-proxy": "^5.0.7",
"loopback-connector-mongodb": "^5.2.3",
"tsc-watch": "^6.0.0",
"tslib": "^2.0.0"
},
"devDependencies": {
"#loopback/build": "^9.0.7",
"#loopback/eslint-config": "^13.0.7",
"#loopback/testlab": "^5.0.7",
"#types/node": "^14.18.36",
"eslint": "^8.30.0",
"source-map-support": "^0.5.21",
"typescript": "~4.9.4"
}
}
Docker compose
version: '3.9'
services:
mongodb:
image: mongo
container_name: mongodb
ports:
- "27017:27017"
environment:
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=password
- MONGO_INITDB_DATABASE=admin
restart: always
volumes:
- ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
- mongodb:/data/db
backend:
container_name: backend
build:
context: .
dockerfile: ./lympha-backend/Dockerfile
command: ["yarn", "dev"]
ports:
- 4000:3000
environment:
NAME: TEST_DEVELOPMENT
PORT: 3000
DB_NAME: lympha_db
DB_USER: root
DB_PASS: password
restart: always
volumes:
- ./lympha-backend:/home/node/app
depends_on:
- mongodb
links:
- mongodb
volumes:
backend:
mongodb:
Dockerfile
# Check out https://hub.docker.com/_/node to select a new base image
FROM node:16-slim
# Set to a non-root built-in user `node`
USER node
# Create app directory (with user `node`)
RUN mkdir -p /home/node/app
RUN mkdir -p /home/node/app/dist
WORKDIR /home/node/app
RUN pwd
COPY --chown=node package*.json ./
# RUN npm install
RUN yarn
# Bundle app source code
COPY --chown=node . .
# Bind to all network interfaces so that it can be mapped to the host OS
ENV HOST=0.0.0.0 PORT=3000
EXPOSE ${PORT}
mongo-init.js
db.createUser({
user: 'admin',
pwd: 'password',
roles: [
{ role: 'root', db: 'admin' },
]
});
db = db.getSiblingDB('lympha_db');
db.createCollection("lympha_db"); //MongoDB creates the database when you first store data in that database
db.createUser(
{
user: "lympha",
pwd: "lympha",
roles: [
{
role: "readWrite",
db: "lympha_db"
}
]
}
);
Mongo terminal
Look at the picture
Logs
Mongodb logs
Look at the picture
Backend logs
{
name: 'mongodb',
connector: 'mongodb',
host: 'localhost',
port: 27017,
user: 'admin',
password: 'password',
database: 'admin'
}
Server is running at http://127.0.0.1:3000
Try http://127.0.0.1:3000/ping
Connection fails: MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
It will be retried for the next request.
/home/node/app/node_modules/mongodb/lib/utils.js:698
throw error;
^
MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at Timeout.\_onTimeout (/home/node/app/node_modules/mongodb/lib/core/sdam/topology.js:438:30)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)
Emitted 'error' event on MongoDataSource instance at:
at MongoDataSource.postInit (/home/node/app/node_modules/loopback-datasource-juggler/lib/datasource.js:502:16)
at onError (/home/node/app/node_modules/loopback-connector-mongodb/lib/mongodb.js:325:21)
at /home/node/app/node_modules/loopback-connector-mongodb/lib/mongodb.js:333:9
at /home/node/app/node_modules/mongodb/lib/utils.js:695:9
at /home/node/app/node_modules/mongodb/lib/mongo_client.js:285:23
at connectCallback (/home/node/app/node_modules/mongodb/lib/operations/connect.js:367:5)
at /home/node/app/node_modules/mongodb/lib/operations/connect.js:554:14
at connectHandler (/home/node/app/node_modules/mongodb/lib/core/sdam/topology.js:286:11)
at Object.callback (/home/node/app/node_modules/mongodb/lib/core/sdam/topology.js:672:9)
at Timeout.\_onTimeout (/home/node/app/node_modules/mongodb/lib/core/sdam/topology.js:443:25)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
reason: TopologyDescription {
type: 'Single',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map(1) {
'localhost:27017' =\> ServerDescription {
address: 'localhost:27017',
error: Error: connect ECONNREFUSED 127.0.0.1:27017
at TCPConnectWrap.afterConnect \[as oncomplete\] (node:net:1278:16) {
name: 'MongoNetworkError'
},
roundTripTime: -1,
lastUpdateTime: 7989795,
lastWriteDate: null,
opTime: null,
type: 'Unknown',
topologyVersion: undefined,
minWireVersion: 0,
maxWireVersion: 0,
hosts: \[\],
passives: \[\],
arbiters: \[\],
tags: \[\]
}
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
I cant connect lb4 and mongo.
I can start for scratch to figure out what is going on. Ask everything you want, i will do everything is needed as well. Ping me please.
When you start in compose, it sets up single network. (https://docs.docker.com/compose/networking/)
In short, each container can see another by service name. In your case - mongodb, not localhost
try to change:
- host: 'localhost',
+ host: 'mongodb',

A way to run vite dev on remote server (like Laravel Mix)

I've switched from Laravel Mix to Vite, and am trying to accomplish same thing "npm run watch" does for Laravel Mix. Caveat: our staging servers are not local (i.e. staging.app-domain-name.com). If I run npm run dev with Vite it revs up the "dev" server that's supposed to be at http://ip:3000, but that obviously does not work. Aside from not having an active watcher, I can't get the dev to be used with Vue Devtools plugin (since vite only can spit out prod on server).
My vite.config.js:
const { resolve } = require('path');
import vue from '#vitejs/plugin-vue';
export default ({ command }) => ({
base: command === 'serve' ? '' : '/dist/',
publicDir: 'fake_dir_so_nothing_gets_copied',
build: {
manifest: true,
outDir: resolve(__dirname, 'public/dist'),
rollupOptions: {
input: 'resources/js/app.js',
},
},
server: {
host: true,
port: '8080',
hot: true
},
plugins: [vue()],
resolve: {
alias: {
'#': resolve('./resources/js'),
},
},
});
My app.js
import "./bootstrap";
import '../css/app.css';
import { createApp, h } from 'vue';
import { App as InertiaApp, plugin as InertiaPlugin } from '#inertiajs/inertia-vue3';
import { InertiaProgress } from '#inertiajs/progress';
let asyncViews = () => {
return import.meta.glob('./Pages/**/*.vue');
}
const el = document.getElementById('app');
createApp({
render: () =>
h(InertiaApp, {
initialPage: JSON.parse(el.dataset.page),
resolveComponent: async name => {
if (import.meta.env.DEV) {
return (await import(`./Pages/${name}.vue`)).default;
} else {
let pages = asyncViews();
const importPage = pages[`./Pages/${name}.vue`];
return importPage().then(module => module.default);
}
}
}),
})
.mixin({ methods: { route } })
.use(InertiaPlugin)
.mount(el);
And package.json scripts:
"scripts": {
"predev": "printf \"dev\" > public/hot",
"dev": "vite",
"preprod": "printf \"prod\" > public/hot",
"prod": "vite build"
}
Desired outcome to generate dev bundle on a remote server by running
npm run dev
Currently it tries to create localhost dev. I assume something in vite.config.js needs to be set to get that done. I've gone over the docs but could not find anything clear enough.
To tell Vite to listen also on network interface simply add --host parameter to dev script:
"scripts": {
"dev": "vite --host",
"prod": "vite build"
},
It gives me an result like this:
vite v2.5.10 dev server running at:
> Local: http://localhost:3000/
> Network: http://x.y.x.z:3000/ <-- server public IP
> Network: http://10.10.10.1:3000/ <-- server local IP via VPN
ready in 330ms.
But this was not solution. I had a problem with CORS. I resolved it in another way. It depends on web server. I use nGinx and I set reverse proxy to listen on port 3000.
server {
listen x.y.x.z:3000 ssl; ### Server public IP address
server_name dev.example.com;
location / {
proxy_pass https://127.0.0.1:3000/; ### https: is Important
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection upgrade;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
}
# SSL config
ssl_certificate /srv/certs/example.com/fullchain.cer;
ssl_certificate_key /srv/certs/example.com/example.com.key;
include ssl_config;
}
Ii is also important to listen only on public IP address due to not conflict with vite on same port. Vite default listen only on localhost. Reload nGinx
sudo nginx -t
sudo systemctl reload nginx
In package.json I put --https atribute
{
"private": true,
"scripts": {
"dev": "vite --https",
"prod": "vite build"
},
"devDependencies": {
"postcss": "^8.1.14",
"vite": "^2.5.10"
}
}
And that's it. Now I am able run
npm run dev
Finnally I put scripts to my layout blade end Vite start works.
<script type="module" src="https://dev.example.com:3000/#vite/client"></script>
<script type="module" src="https://dev.example.com:3000/resources/js/app.js"></script>
Setup nginx to proxy websocket
https://www.nginx.com/blog/websocket-nginx/
Sebastyan's guide to setup Vite with Laravel
https://sebastiandedeyne.com/vite-with-laravel
Adding this server part of this config to my config in vite.config.js file fixed things for me.
export default defineConfig({
server: {
hmr: {
host: 'localhost',
}
}
});
Except you may want to change the host part from localhost to your server's IP address.
Then do npm run dev -- --host as others have mentioned.
I copy pasted this answer from here without reading anything else about it or why it works.
Adding --host separated by -- worked in my case - no changes in config files needed this way:
npm run dev -- --host
Try this:
CMD [ "npm", "run", "dev", "--", "--host"]
It worked for me but the app keeps reloading
Adding the arguments "--" "--host" to my Docker file did the trick.
like so:
CMD [ "npm", "run", "dev", "--", "--host"]
this allows me to start the server in dev mode and to reach it from my host.
{
"name": "zustand",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"cmd": "cmd /k npm run dev -- --host",
"host": "vite --host",
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"#tanstack/react-query": "^4.20.9",
"axios": "^1.2.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"zustand": "^4.2.0"
},
"devDependencies": {
"#types/react": "^18.0.26",
"#types/react-dom": "^18.0.10",
"#vitejs/plugin-react": "^3.0.1",
"typescript": "^4.9.4",
"vite": "^4.0.4"
}
}
---
vite --host
VITE v4.0.4 ready in 623 ms
➜ Local: http://localhost:5173/
➜ Network: http://172.19.80.1:5173/
➜ Network: http://192.168.100.14:5173/
➜ press h to show help
para que funcione "vite --host", debe estar instalado globalmente.
Ej: npm install vite -g

How to set vite.config.js base public path?

I'm trying to set a base url for both my dev and prod environments, but vitejs configs are not resolved.
According to vitejs , you can set the base public path when served in development or production, in your config options.
When running vite from the command line, Vite will automatically try to resolve a config file named vite.config.js inside project root.
The issue is that my application requests don't go through 'http://localhost:8080/', but are still appended to the default serving port http://localhost:3000/.
My current configs are bellow:
// vite.config.js
export default {
base: 'http://localhost:8080/'
}
// packages.json
{
"name": "vue3ui",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
...,
"vue": "^3.0.11"
},
"devDependencies": {
"#vue/compiler-sfc": "^3.0.11",
"vite": "^1.0.0-rc.13"
}
}
Not totally clear to me but I will try to give you an answer to achieve what you want.
I'm trying to set a base url for both my dev and prod environments
Edit: I read again you question, and I think you are looking for the point C on this answer.
Changes should be made in vite.config.js
A) You are looking to change the running port from 3000 to 8080, adjust server.port
server: {
port: '8080'
}
B) But if you are looking to run on localhost:3000 and forward requests to localhost:8080 then you have to adjust server.proxy
server: {
proxy: {
'/': {
target: 'http://localhost:8080/'
},
'/admin': {
target: 'http://localhost:8081/'
}
}
}
example:
'/': will proxy all requests to localhost:8080
'/admin': will proxy only requests that have as endpoint /admin to http://localhost:8081
C) Changing base path depending on dev or prod environment
.env file :
// .env
// Running locally
APP_ENV=local
// you change port of local/dev here to :8000
// do not forget to adjust `server.port`
ASSET_URL=http://localhost:3000
// Running production build
APP_ENV=production
ASSET_URL=https://your-prod-asset-domain.com
vite.config.js:
const ASSET_URL = process.env.ASSET_URL || '';
export default {
base: `${ASSET_URL}/dist/`,
[...]
}
If it's not what you are looking for, please be more precise and I will edit my answer.
For more information, head to the official doc at https://vitejs.dev/config/#server-options
I think I understand what TC wants to solve.
He has 1 build for dev and prod envs.
But it depends on envs, he has a different base path.
Answer:
https://vitejs.dev/guide/build.html#advanced-base-options
At the moment it is an experimental feature
experimental: {
renderBuiltUrl(filename: string, { hostType }: { hostType: 'js' | 'css' | 'html' }) {
if (['js', 'css'].includes(hostType)) {
return { runtime: `window.__getFile(${JSON.stringify(filename)})` }
} else {
return { relative: true }
}
}
}
and create global function
window.__getFile = function(file){
if (window.location.host.includes('dev')) {
return `http://cdn.dev/${file}`
}
return `http://cdn.prod/${file}`
}
P.s. Sorry. I can't find any example with port

Docker-compose node express container doesn't show error logs and restart continuously

I am trying to make nginx, node express work on the container by using docker compose.
But problem is express container doesn't show any error log why it is died.
This is my docker-compose.yml
version: '3'
services:
proxy:
image: nginx:latest
container_name: proxy
ports:
- "80:80"
volumes:
- ./proxy/nginx.conf:/etc/nginx/nginx.conf
restart: "unless-stopped"
express:
build:
context: ./server
container_name: express
expose:
- "3000"
volumes:
- ./source:/source
- /source/node_modules
restart: "unless-stopped"
This is my directory structure.
source directory, i move all files and directories from express-generator outputs.
This is my Dockerfile.
FROM node:12
COPY package*.json /source/
WORKDIR /source
RUN npm install
CMD [ "node", "app.js" ]
This is my package.json
{
"name": "docker_web_app",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "sjk5766",
"license": "ISC",
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"morgan": "~1.9.1"
}
}
When i did docker ps after docker-compose up -d, result is like below.
When i did docker logs express, there is nothing i can see.
I really wanna know what is the problem.
Considering your express application is running fine without docker.
you can change your Dockerfile as below
FROM node:12
WORKDIR /source
COPY . .
RUN npm install
EXPOSE 3000
CMD [ "node", "app.js" ]
COPY command will copy your local directory code to /server directory in docker
try docker-compose file as below
version: '3'
services:
proxy:
image: nginx:latest
container_name: proxy
ports:
- "80:80"
volumes:
- ./proxy/nginx.conf:/etc/nginx/nginx.conf
networks:
- test_bridge
restart: "unless-stopped"
express:
build: ./server
container_name: express
ports:
- "3000:3000"
networks:
- test_bridge
networks:
test_bridge:
driver: bridge

Can I change the default port from 8080 to something else in Vue?

I have been working on Vue.js and Node.js to build my app. When I have started with Vue it is by default running on 8080 and Node I am running on 3008.
What I am trying to do is due to some circumstances I want to change the port for Vue from 8080 to any other like 8086 or 3005. How can I do that?
Simply you can run the following command to run vue app as per your required port :
npm run serve --port 8086
Another way is to update the serve script command in your package.json file. Just append --port 8086 like so:
"scripts": {
"serve": "vue-cli-service serve --port 8086",
"build": "vue-cli-service build",
"inspect": "vue-cli-service inspect",
"lint": "vue-cli-service lint"
}
If you don't have one create vue.config.js in the root dir of your project and there add this option:
module.exports = {
devServer: {
port: 8086
}
}
In webpack docs you can see all the available options for configuring the dev server.
Check also vue-cli docs.
This is the way! ...that worked for me!
npm run serve -- --port 8086
With "npm":
npm run serve --port 8086
With "yarn":
yarn serve --port 8086
If you are using vite as your build tool, you can override the default port with the one you want by providing a server.port entry in the vite configuration file - vite.config.js
In the example below, I set the default port to 8086
export default defineConfig({
...
server: {
port: 8086,
},
});
in vue.config.js
module.exports = defineConfig({
...
devServer: {
port: 8086,
},
DIR: node_modules#vue\cli-service\lib\commands
CHANGE FILE: serve.js
const defaults = {
host: '0.0.0.0',
port: 8086,
https: false
}