Nuxt PM2 CPU up to 100% - vue.js

Hello guys can you help me please!
My app use up to 100% CPU when a lot of users go to my app.
I tried a lot of things, and my config turned into a mess
This is my nuxt.config.ts.
import type { NuxtConfig } from '#nuxt/types';
const isDev = process.env.NODE_ENV !== 'production';
const mainConfig: NuxtConfig = {
...
build: {
cache: true,
optimization: {
minimize: true,
runtimeChunk: true,
concatenateModules: true,
splitChunks: {
chunks: 'all',
minSize: 30000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 20,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
chunks: 'all'
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
},
filenames: {
app: ({ isDev }) => (isDev ? '[name].js' : 'js/[name]/[contenthash].js'),
chunk: ({ isDev }) => (isDev ? '[name].js' : 'js/[name]/[contenthash].js'),
css: ({ isDev }) => (isDev ? '[name].css' : 'css/[contenthash].css'),
img: ({ isDev }) => (isDev ? '[path][name].[ext]' : 'img/[contenthash:7].[ext]'),
font: ({ isDev }) => (isDev ? '[path][name].[ext]' : 'fonts/[contenthash:7].[ext]')
},
extend(config, { isClient }) {
config.externals = [
function (context, request, callback) {
if (/(pdfmake)/.test(request) || /(xlsx)/.test(request)) {
return callback(null, 'commonjs ' + request);
}
callback();
}
];
}
},
router: { ... },
modules: [ ... ],
server: { ... },
watchers: {
webpack: {
ignored: ['**/node_modules', 'node_modules']
}
}
};
export default mainConfig;
The application does not stand up to 2000 users and breaks,
I really dont know what to do! :(
Maybe you will can help me?

Related

Terser Plugin doesnt run with Vue CLI 5 on vue build

I am trying to create a production build with the following configureWebpack but Terser doesnt run during build.
Code is not minimized or uglified. Ialso tried hidden-source-map
Using "terser-webpack-plugin": "^5.3.3" with #vue/cli#5.0.7
isProd is correctly set to true.
const TerserPlugin = require('terser-webpack-plugin');
const isProd = process.env.NODE_ENV === 'production';
module.exports = {
publicPath: '/',
devServer: {
host: 'staging-beta.myDomain.com',
port: 9000,
allowedHosts: 'all',
},
transpileDependencies: ['vuetify'],
chainWebpack: (config) => {
// reducted code
},
configureWebpack: {
devtool: 'source-map',
optimization: {
minimize: isProd,
minimizer: isProd
? [
new TerserPlugin({
minify: TerserPlugin.uglifyJsMinify,
terserOptions: {
compress: {
drop_console: true,
},
output: {
comments: false,
},
},
}),
]
: [],
},
},
};
The correct setup is:
module.exports = defineConfig({
terser: {
minify: 'uglifyJs',
terserOptions: {
compress: {
drop_console: true,
},
},
},
})
You also need to npm install uglify-js
comments under output is deprecated.

Nuxt.js Oauth sometimes crashes whole webpage

I have created Nuxt.js application, I decided to build in Nuxt/auth module, everything works fine in web browsers, but somethimes when user navigates with mobile browser my application is crushed, simply it don't respond nothing, also there is no api calls, but after one refresh everything works fine, I can not guess what's happening, I could not find anything in the resources available on the Internet.
const axios = require('axios')
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'app',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
],
script: [
// { src: "//code-eu1.jivosite.com/widget/UoBOrMfSmm", async: true },
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [ '~/assets/css/transition.css', '~/assets/css/errors.css' ],
pageTransition: "fade",
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
{ src: "~/plugins/star-rating", ssr: false },
{ src: "~/plugins/mask", ssr: false },
{ src: "~/plugins/rangeSlider", ssr: false },
{ src: "~/plugins/vueSelect", ssr: false },
{ src: "~/plugins/vuelidate", ssr: false },
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
[ '#nuxtjs/google-analytics', {
id: 'xxx'
} ]
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/bootstrap
'bootstrap-vue/nuxt',
'#nuxtjs/axios',
'#nuxtjs/toast',
'#nuxtjs/auth-next',
[ 'nuxt-lazy-load', {
defaultImage: '/spin2.gif'
} ],
[ 'nuxt-facebook-pixel-module', {
/* module options */
track: 'PageView',
pixelId: '',
autoPageView: true,
disabled: false
} ],
'nuxt-moment',
'#nuxtjs/robots',
'#nuxtjs/sitemap'
],
moment: {
locales: ['ru', 'en']
},
toast: {
position: 'top-center',
},
robots: [
{
UserAgent: '*',
Disallow: ['/user', '/admin'],
},
],
axios: {
baseURL: 'https://api.test.com/', // Used as fallback if no runtime config is provided
},
sitemap:{
exclude:[
'/user',
'/admin',
'/admin/*',
'/user/*',
],
defaults: {
changefreq: 'daily',
priority: 1,
lastmod: new Date()
},
routes: async () => {
const { data } = await axios.get('https://api.test.com/api/cars/all')
return data.map((product) => `https://test.com/product/${product.id}/${product.name}`)
}
},
loading: {
color: '#F48245',
height: '4px'
},
target: 'server',
/* auth */
auth: {
plugins:[
{ src: "~/plugins/providers", ssr:false},
],
redirect: {
login: '/',
logout: '/',
home: '/',
callback: '/callback'
},
strategies: {
local: {
token: {
property: 'user.token',
},
user: {
property: false
},
endpoints: {
login: { url: 'api/login', method: 'post' },
logout: { url: 'api/logout', method: 'post' },
user: { url: 'api/user', method: 'get' }
},
},
facebook: {
endpoints: {
userInfo: 'https://graph.facebook.com/v6.0/me?fields=id,name,picture{url}',
},
redirectUri:'xxx',
clientId: '184551510189971',
scope: ['public_profile', 'email'],
},
google: {
responseType: 'token id_token',
codeChallengeMethod: '',
clientId: 'xxx',
redirectUri: 'https://test.com/callback',
scope: ['email'],
},
},
cookie: {
prefix: 'auth.',
},
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
};
This is my plugins directory file, where i am handling client oauth process.
export default async function ({ app }) {
console.log('auth executed')
if (!app.$auth.loggedIn) {
return
} else {
console.log('auth executed inside loop')
const auth = app.$auth;
const authStrategy = auth.strategy.name;
if (authStrategy === 'facebook') {
let data2 = {
fb_token: auth.user.id,
first_name: auth.user.name
}
try {
const response = await app.$axios.$post("/api/oauth", data2);
await auth.setStrategy('local');
await auth.strategy.token.set("Bearer " + response.user.token);
await auth.fetchUser();
} catch (e) {
console.log(e);
}
} else if (authStrategy === 'google') {
let dataGoogle = {
google_token: auth.user.sub,
first_name: auth.user.given_name,
last_name:auth.user.family_name
}
try {
const response = await app.$axios.$post("/api/oauth", dataGoogle);
await auth.setStrategy('local');
await auth.strategy.token.set("Bearer " + response.user.token);
await auth.fetchUser();
} catch (e) {
console.log(e);
}
}
}
}
For any issues related to DOM hydration, you can check my answer here: https://stackoverflow.com/a/67978474/8816585
It does have several possible cases (dynamic content with a difference between client side and server side rendered template, some random functions, purely wrong HTML structure etc...) and also a good blog article from Alex!

Vue + Vuetify + Axios + Django : CRUD data table

I am trying to build a Vuetify CRUD using AXIOS. I am able to do CRUD operations, but am not able to display the newly added data till the page is refreshed. When I select edit, I am not able to see the existing data while editing. The editable dialog box shows empty.
Please help me if to resolve this.
Here is my script
import Navbar from '../components/Navbar.vue'
import { getAPI } from '../axios-api'
// import DataService from "../services/DataService";
export default {
data: () => ({
dialog: false,
dialogDelete: false,
headers: [
{ text: 'ID', align: 'start', value: 'id',},
{ text: 'Length', value: 'size' },
{ text: 'Weight', value: 'weight' },
{ text: 'Actions', value: 'actions', sortable: false },
],
info: [],
editedIndex: -1,
editedItem: {
ID: '',
Weight: 0,
Length: 0,
},
defaultItem: {
name: '',
Weight: 0,
Length: 0,
},
}),
components:{
Navbar
},
computed: {
formTitle () {
return this.editedIndex === -1 ? 'New Item' : 'Edit Item'
},
},
methods: {
initialize () {
getAPI.get('calibration/sizeweight')
.then(response => {
this.info = response.data
})
},
editItem (item) {
this.editedIndex = this.info.indexOf(item)
this.editedItem = Object.assign({}, item)
this.dialog = true
},
deleteItem (item) {
this.editedIndex = this.info.indexOf(item)
this.editedItem = Object.assign({}, item)
this.dialogDelete = true
},
deleteItemConfirm () {
this.info.splice(this.editedIndex, 1)
this.closeDelete()
getAPI.delete('calibration/sizeweight/'+this.editedItem.id)
.then(response=>{
console.log(response)
})
},
close () {
this.dialog = false
this.$nextTick(() => {
this.editedItem = Object.assign({}, this.defaultItem)
this.editedIndex = -1
})
},
closeDelete () {
this.dialogDelete = false
this.$nextTick(() => {
this.editedItem = Object.assign({}, this.defaultItem)
this.editedIndex = -1
})
},
save () {
if (this.editedIndex > -1) {
Object.assign(this.info[this.editedIndex], this.editedItem)
getAPI.put('calibration/sizeweight/'+this.editedItem.ID,{id:this.editedItem.ID ,weight:this.editedItem.Weight,size:this.editedItem.Length})
.then(response=>{
console.log(response)
this.initialize()
})
} else {
this.info.push(this.editedItem)
getAPI.post('calibration/sizeweight',{id:this.editedItem.ID ,weight:this.editedItem.Weight,size:this.editedItem.Length})
.then(response=>{
console.log(response)
this.initialize()
})
.catch(error => { console.log(error.response.data)})
}
this.close()
},
},
watch: {
dialog (val) {
val || this.close()
},
dialogDelete (val) {
val || this.closeDelete()
},
},
created () {
this.initialize()
},
}
</script>

How to remove console logs from Production Build in Vue 3

Here is my vue.config.js file. I have followed the instructions given here: https://github.com/JayeshLab/demo-vue-console-log-removal
Still I can see logs in browser, what else am I missing?
const TerserPlugin = require("terser-webpack-plugin");
const isProd = true
module.exports = {
lintOnSave: false,
devServer: {
proxy: 'http://localhost:3000/'
},
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.tap(args => {
})
},
configureWebpack: {
optimization: {
minimize: true,
minimizer: isProd ? [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true
},
output: {
comments: false
}
}
})
] : []
}
}
}
Managed to solve it by changing babel.config.js configuration. Added transform-remove-console plugin
const removeConsolePlugin = []
if(process.env.NODE_ENV == 'staging' || process.env.NODE_ENV == 'production') {
removeConsolePlugin.push("transform-remove-console")
}
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset'
],
plugins: removeConsolePlugin
}

React Native: Cannot get PeerJs server to communicate back to my React Native Client, sending back the peer ID

The example i found was here for the client:
https://github.com/metehankurucu/react-native-video-calling-app
So im trying to build the Server.js from this.
This is my Peer Client:
import React, {useState} from 'react';
import {Alert} from 'react-native';
import {
mediaDevices,
MediaStream,
MediaStreamConstraints,
} from 'react-native-webrtc';
import socketio from 'socket.io-client';
import {MainContext as MainContextType, User} from '../interfaces';
import {
SERVER_URL,
PEER_SERVER_HOST,
PEER_SERVER_PORT,
PEER_SERVER_PATH,
} from '../server';
// #ts-ignore
import Peer from 'react-native-peerjs';
import {navigate} from '../helpers/RootNavigation';
const initialValues: MainContextType = {
username: '',
peerId: '',
users: [],
localStream: null,
remoteStream: null,
remoteUser: null,
initialize: () => {},
setUsername: () => {},
call: () => {},
switchCamera: () => {},
toggleMute: () => {},
isMuted: false,
closeCall: () => {},
reset: () => {},
activeCall: null,
};
export const MainContext = React.createContext(initialValues);
interface Props {}
const MainContextProvider: React.FC<Props> = ({children}) => {
const [username, setUsername] = useState(initialValues.username);
const [peerId, setPeerId] = useState(initialValues.peerId);
const [users, setUsers] = useState<User[]>(initialValues.users);
const [localStream, setLocalStream] = useState<MediaStream | null>(
initialValues.localStream,
);
const [remoteStream, setRemoteStream] = useState<MediaStream | null>(
initialValues.remoteStream,
);
const [remoteUser, setRemoteUser] = useState<User | null>(null);
const [socket, setSocket] = useState<SocketIOClient.Socket | null>(null);
const [peerServer, setPeerServer] = useState<any>(null);
const [isMuted, setIsMuted] = useState(initialValues.isMuted);
const [activeCall, setActiveCall] = useState<any>(null);
const initialize = async () => {
const isFrontCamera = true;
const devices = await mediaDevices.enumerateDevices();
const facing = isFrontCamera ? 'front' : 'environment';
const videoSourceId = devices.find(
(device: any) => device.kind === 'videoinput' && device.facing === facing,
);
const facingMode = isFrontCamera ? 'user' : 'environment';
const constraints: MediaStreamConstraints = {
audio: true,
video: {
mandatory: {
minWidth: 1280,
minHeight: 720,
minFrameRate: 30,
},
facingMode,
optional: videoSourceId ? [{sourceId: videoSourceId}] : [],
},
};
const newStream = await mediaDevices.getUserMedia(constraints);
setLocalStream(newStream as MediaStream);
const io = socketio.connect('http://localhost', {
reconnection: true,
autoConnect: true,
});
io.on('connect', () => {
console.log('connect');
setSocket(io);
console.log('setSocket');
io.emit('register', username);
console.log('register');
});
io.on('users-change', (users: User[]) => {
console.log('users-change');
setUsers(users);
console.log('setUsers');
});
io.on('accepted-call', (user: User) => {
console.log('accepted-call');
setRemoteUser(user);
console.log('setRemoteUser');
});
io.on('rejected-call', (user: User) => {
console.log('rejected-call');
setRemoteUser(null);
console.log('setRemoteUser');
setActiveCall(null);
console.log('setActiveCall');
Alert.alert('Your call request rejected by ' + user?.username);
navigate('Users');
console.log('navigate');
});
io.on('not-available', (username: string) => {
console.log('not-available');
setRemoteUser(null);
console.log('setRemoteUser');
setActiveCall(null);
console.log('setActiveCall');
Alert.alert(username + ' is not available right now');
navigate('Users');
console.log('Users');
});
const peerServer = new Peer({
host: 'localhost',
path: '/peerjs',
secure: false,
port: 9000,
config: {
iceServers: [
{
urls: [
'stun:stun1.l.google.com:19302',
'stun:stun2.l.google.com:19302',
],
},
],
},
});
console.log(peerServer);
peerServer.on('error', (err: Error) =>
console.log('Peer server error', err),
);
peerServer.on('open', (peerId: string) => {
console.log('open');
setPeerServer(peerServer);
console.log('setPeerServer');
setPeerId(peerId);
console.log('setPeerId');
io.emit('set-peer-id', peerId);
console.log('set-peer-id');
});
io.on('call', (user: User) => {
console.log(user);
peerServer.on('call', (call: any) => {
console.log('call');
setRemoteUser(user);
console.log('setRemoteUser');
Alert.alert(
'New Call',
'You have a new call from ' + user?.username,
[
{
text: 'Reject',
onPress: () => {
io.emit('reject-call', user?.username);
setRemoteUser(null);
setActiveCall(null);
},
style: 'cancel',
},
{
text: 'Accept',
onPress: () => {
io.emit('accept-call', user?.username);
call.answer(newStream);
setActiveCall(call);
navigate('Call');
},
},
],
{cancelable: false},
);
call.on('stream', (stream: MediaStream) => {
console.log('stream');
setRemoteStream(stream);
console.log('setRemoteStream');
});
call.on('close', () => {
console.log('close');
closeCall();
console.log('closeCall');
});
call.on('error', () => {});
});
});
};
const call = (user: User) => {
if (!peerServer || !socket) {
Alert.alert('Peer server or socket connection not found');
return;
}
if (!user.peerId) {
Alert.alert('User not connected to peer server');
return;
}
socket.emit('call', user.username);
console.log('setRemoteUser');
setRemoteUser(user);
try {
console.log('1');
const call = peerServer.call(user.peerId, localStream);
console.log('peerServer.call(user.peerId, localStream)');
call.on(
'stream',
(stream: MediaStream) => {
setActiveCall(call);
setRemoteStream(stream);
},
(err: Error) => {
console.error('Failed to get call stream', err);
},
);
} catch (error) {
console.log('Calling error', error);
}
};
const switchCamera = () => {
if (localStream) {
// #ts-ignore
localStream.getVideoTracks().forEach((track) => track._switchCamera());
}
};
const toggleMute = () => {
if (localStream)
localStream.getAudioTracks().forEach((track) => {
track.enabled = !track.enabled;
setIsMuted(!track.enabled);
});
};
const closeCall = () => {
activeCall?.close();
setActiveCall(null);
setRemoteUser(null);
navigate('Users');
Alert.alert('Call is ended');
};
const reset = async () => {
peerServer?.destroy();
socket?.disconnect();
setActiveCall(null);
setRemoteUser(null);
setLocalStream(null);
setRemoteStream(null);
setUsername('');
setPeerId('');
};
return (
<MainContext.Provider
value={{
username,
setUsername,
peerId,
setPeerId,
users,
setUsers,
localStream,
setLocalStream,
remoteStream,
setRemoteStream,
initialize,
call,
switchCamera,
toggleMute,
isMuted,
closeCall,
reset,
remoteUser,
activeCall,
}}>
{children}
</MainContext.Provider>
);
};
export default MainContextProvider;
Forgive me as i have put alot of consol.logs in there, so i hope i havent confused you.
And this is my Peerjs Server:
const express = require("express");
const app = express();
const port = 9000;
const http = require("http");
const server = http.createServer(app);
const io = require("socket.io")(server);
app.use(express.static(__dirname + "/public"));
io.sockets.on("error", e => console.log(e));
server.listen(port, () => console.log(`Server is running on port ${port}`));
let broadcaster
io.sockets.on("connection", socket => {
socket.on("broadcaster", () => {
broadcaster = socket.id;
socket.broadcast.emit("broadcaster");
});
socket.on("watcher", () => {
socket.to(broadcaster).emit("watcher", socket.id);
});
socket.on("disconnect", () => {
socket.to(broadcaster).emit("disconnectPeer", socket.id);
});
});
this is the JSON i get from the client:
{
"acks": {},
"connected": false,
"disconnected": true,
"flags": {},
"ids": 0,
"io": {
"_autoConnect": true,
"_callbacks": {
"$close": [Array],
"$error": [Array],
"$open": [Array],
"$packet": [Array]
},
"_randomizationFactor": 0.5,
"_readyState": "opening",
"_reconnection": true,
"_reconnectionAttempts": Infinity,
"_reconnectionDelay": 1000,
"_reconnectionDelayMax": 5000,
"_timeout": 20000,
"backoff": {
"attempts": 0,
"factor": 2,
"jitter": 0.5,
"max": 5000,
"ms": 1000
},
"decoder": {},
"encoder": {},
"engine": {
"_callbacks": [Object],
"hostname": "localhost",
"id": null,
"opts": [Object],
"pingInterval": null,
"pingTimeout": null,
"pingTimeoutTimer": null,
"port": "80",
"prevBufferLen": 0,
"readyState": "opening",
"secure": false,
"transport": [XHR],
"transports": [Array],
"upgrades": null,
"writeBuffer": [Array]
},
"nsps": {
"/": [Circular]
},
"opts": {
"autoConnect": true,
"hostname": "localhost",
"path": "/socket.io",
"port": "80",
"reconnection": true,
"secure": false
},
"skipReconnect": false,
"subs": [
[Function subDestroy],
[Function subDestroy],
[Function subDestroy]
],
"uri": "http://localhost"
},
"nsp": "/",
"receiveBuffer": [],
"sendBuffer": [],
"subs": [
[Function subDestroy],
[Function subDestroy],
[Function subDestroy],
[Function subDestroy]
]
}
[Mon Mar 29 2021 19: 22: 16.595] LOG {
"_api": {
"_options": {
"config": [Object],
"debug": 0,
"host": "localhost",
"key": "peerjs",
"path": "/peerjs/",
"port": 9000,
"secure": false,
"token": "f0ty4c4n2si"
}
},
"_connections": Map {},
"_destroyed": false,
"_disconnected": false,
"_events": {},
"_eventsCount": 0,
"_id": null,
"_lastServerId": null,
"_lostMessages": Map {},
"_open": false,
"_options": {
"config": {
"iceServers": [Array]
},
"debug": 0,
"host": "localhost",
"key": "peerjs",
"path": "/peerjs/",
"port": 9000,
"secure": false,
"token": "f0ty4c4n2si"
},
"_socket": {
"_baseUrl": "ws://localhost:9000/peerjs/peerjs?key=peerjs",
"_disconnected": true,
"_events": {
"close": [r],
"disconnected": [r],
"error": [r],
"message": [r]
},
"_eventsCount": 4,
"_messagesQueue": [],
"pingInterval": 5000
}
}
[Mon Mar 29 2021 19: 22: 16.752] LOG Peer server error[Error: Could not get an ID from the server.]