Vite + SvelteKit + MariaDB: importing script with databse connection throws weird errors - database

I am trying to build simple app using Vite + SvelteKit that will connect to a server with MariaDB database. I tried many options, but nothing worked. When I tried to do connection like this:
Here is script I use for connection to database:
import mysql from 'mysql2/promise';
const connection = await mysql.createConnection({
host: "127.0.0.1",
user: "admin",
password: "givdb",
database: "givdb",
});
console.log('Connected to MariaDB');
export default connection;
Here is main svelte page.
<script>
import connection from '../db';
async function fetchData() {
const [rows, fields] = await connection.execute('SELECT * FROM User');
console.log(rows[0].Email,"(This was fetched from database)");
}
fetchData();
</script>
<h1>Welcome to SvelteKit</h1>
<p>Visit kit.svelte.dev to read the documentation</p>
This Code results in successful Fetching of Data from database as shown here:
> vite dev "--" "--open"
VITE v4.1.1 ready in 412 ms
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h to show help
Connected to MariaDB
lonzikormos#gmail.com (This was fetched from database)
17:22:43 [vite-plugin-svelte] ssr compile done.
package files time avg
giv-sveltekit 3 50.7ms 16.9ms
But app shows just replaces whole app with Error:
manifest.js:14
TypeError: Cannot read properties of undefined (reading 'prototype')
at node_modules/.pnpm/safer-buffer#2.1.2/node_modules/safer-buffer/safer.js (safer.js:25:33)
at __require2 (chunk-7FP5O474.js?v=72350a59:10:50)
at node_modules/.pnpm/iconv-lite#0.6.3/node_modules/iconv-lite/lib/index.js (index.js:3:14)
at __require2 (chunk-7FP5O474.js?v=72350a59:10:50)
at node_modules/.pnpm/mysql2#3.1.0/node_modules/mysql2/lib/parsers/string.js (string.js:3:15)
at __require2 (chunk-7FP5O474.js?v=72350a59:10:50)
at node_modules/.pnpm/mysql2#3.1.0/node_modules/mysql2/lib/packets/packet.js (packet.js:11:22)
at __require2 (chunk-7FP5O474.js?v=72350a59:10:50)
at node_modules/.pnpm/mysql2#3.1.0/node_modules/mysql2/lib/packet_parser.js (packet_parser.js:3:16)
at __require2 (chunk-7FP5O474.js?v=72350a59:10:50)
When I comment the section that tries to fetch Data, the Error preserves, but when I comment the fetching part also with the import Line from +page.svelte of my first attempt (import connection from '../db';),error dissapears but then I cannot possibly fetch Data from database...
So the problem roots in importing database connection script. But I don't know how to resolve this. PLS help I'm desperate.

mysql2, and possibly some dependencies, are Node libraries that are not browser compatible. By placing the respective code in the Svelte file it will run in the browser and consequently not work.
When using SvelteKit you should move such code to a server load function, this is ensured my putting it in a +page.server.ts/js file. The data is then fetched by the server and can be passed as the data property to the page. See the documentation for examples.

Related

WebSocket connection failed ERROR on Production (React 18.2.0)

I've got this error after building my project to a live server. It appears after 20-30 seconds after the page loads (any page).
Everything works just fine on my localhost.
I tried to create .env file WDS_SOCKET_PORT=0 in the same folder with package.json but it didn't help.
Maybe you created the server but the problem here:
const io = require('socket.io')(server, {
// handling CORS
cors: {
origin: 'YOU SHOULD WRITE WEBSITE URL HERE',
methods: ["GET", "POST"]
}
});
the socket.io server will not accept any connection that his URL is not similar to the URL in the origin value
anything else will be in react connection, for example, you forgot to write the correct URL

Trouble getting production build React application to make requests to Flask back-end

I have developed a React (front-end) and a Flask (back-end) application.
I have been using the command "npm start" to start the development version of the front-end. This is working fine. The front-end has no trouble sending "fetch" commands to the Flask back-end.
I need to get a production build of the React application running. The React application and the Flask server both need to be deployed locally on the same Linux box (I cannot use "Heroku", etc).
I have created a development build of the react application using the command "npm run build". After the build folder is created successfully, I can run the development build using the command "serve -s build"
The problem occurs when the production build React application attempts to communicate with the currently running back-end server using the fetch command.
The back-end server is set up to run on host = "localhost", port = 3001. The front-end is running on host = "localhost", port = 3000. For development purposes I installed "http-proxy-middleware" and then I created the file "src/setupProxy.js" with the following content:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(createProxyMiddleware("/api_tpwa" , { target : "http://127.0.0.1:3001/"})); }
After doing a bit of research online I came to the conclusion that the current proxy can be used for development, but not in a production build
Here is an example of some test react code (that calls "fetch") that works in the react development application but fails in the production build (proxy is still being used in production build)):
fetch(`/api_tpwa/test`).then(response => {
console.log(response);
return response.json();
})
.then((data) =>
{
console.log(data);
})
.catch(error => {
console.log(error);
})
When I run this using the production build I get the following information printed for the "response" variable in the console:
Response { type: "basic", url: "http://localhost:3000/api_tpwa/test", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false }
I get the following information for the caught error in the console:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I compared the value for "response" for the development build (started with npm start) vs the production build and the values were identical. So, I'm not sure why there would be a json syntax error in one case and not in the other.
I suspect the problem is related to the use of the proxy within the production build but I'm not sure.
Here is the back-end route test function:
#app.route("/api_tpwa/test")
def routeTest():
print("executing api test()")
returnResult = {'result': 1}
return json.dumps(returnResult)
This back-end function never gets executed for the production build. the text "executing api test()" is not printed to the console.
What changes would I need to make to either the front-end or back-end to get a production build react app that can successfully communicate with the Flask back-end?
Any help would be greatly appreciated.

How to fix a 404 error pulling data from MongoDB

I am working on a backend for my React app that pulls the data from MongoDB, but receiving a 404 error whenever I try to launch the app.
Here is how I added axios in App.js file:
Here is the route in server.js file:
But I am getting this error whenever I try to open the main page of the app:
When I launch the database using node server.js command, the database is started successfully.
I don't have much experience for troubleshooting such errors - can anyone please offer some advice?

Cannot Connect to Firestore Database

When trying to get a document and its fields from Firestore I get the following errors:
From Local Host:
#firebase/firestore: Firestore (8.3.2): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=permission-denied]: Permission denied on resource project "xxxxxxxxx".
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.
From Firebase Hosting:
BrowserPollConnection.ts:728 GET https://[PROJECT_ID]-default-rtdb.firebaseio.com/.lp?start=t&ser=82934841&cb=1&v=5&p=1:303920306737:web:bc61250d7aa9a51a415310 net::ERR_NAME_NOT_RESOLVED
When looking up this issue the resolution seems to be caching, DNS, ISP, VPN, or something of the likes. I have tried every proposed solution and still no resolution. I'm thinking it might be how I configured the connection?
The only thing I find odd is that it states its trying to go to https://[PROJECT_ID]-default-rtdb.firebaseio.com which I thought is only for RTDB but I am using Firestore.
In my configuration file I have the following:
firebase/index.js
import firebase from 'firebase/app';
import 'firebase/firestore';
var config = {
apiKey: process.env.REACT_APP_API_KEY,
authDomain: `${process.env.REACT_APP_PROJECT_ID}.firebaseapp.com`,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE,
messagingSenderId:process.env.REACT_APP_MESSAGE_SENDER_ID,
appId:process.env.REACT_APP_APP_ID,
measurementId: process.env.REACT_APP_MEASUREMENT_ID
}
firebase.initializeApp(config);
export default firebase;
I'm trying to just get one document in a useEffect. Weird thing is that once it returns setData, doing data.id prints out the actual ID however within the useEffect or out of it checking if the doc exists docSnapshot.exists is always false. Probably because of my connection issues.
import firebase from './firebase';
const db = firebase.firestore();
.
.
.
useEffect(() => {
db.collection('myCollection').doc('myDocID')
.onSnapshot(docSnapshot => {
console.log(`Received doc snapshot: ${docSnapshot}`);
setData(docSnapshot);
}, err => {
console.log(`Encountered error: ${err}`);
});
},[]);
The issue was actually in my .env file where I had quotes " around the variables. This caused them to be undefined and thus couldn't connect. This question answer helped me
react evironment variables .env return undefined
The error is code=permission-denied. So I think you should try to generate a new API key to check if the errors is caused by permission or your missed configuration

NextJs: The Serverless Function exceeds the maximum size limit of 50mb

I'm new working with NextJs and when trying to deploy my project to Vercel I'm getting the following error:
Error! The Serverless Function "api/auth" is 50.55mb which exceeds the maximum size limit of 50mb.
I have spent a lot of my time trying to find a proper answer but I didn't find any. Here is the code of the api request I'm making:
const { auth: adminAuth } = require("firebase/admin");
export default async function auth(req, res) {
const tokenId = req.query.token;
return new Promise((resolve) => {
adminAuth
.verifyIdToken(tokenId)
.then((user) => {
res.json(user);
resolve();
})
.catch(() => {
res.status(302).send("Invalid authentication");
resolve();
});
});
}
I'll be really grateful if anybody can help me, thanks y'all!
I've been dealing with the same issue. It appears that when bundling the serverless function vercel is pulling in ALL assets within your project. So 50.55MB is likely the size of your current entire build. I'm researching how to only include certain files within the vercel.json but have so far not figured exactly how to do that. For now you could probably just remove a few files from your public assets to get under the limit.
This is likely caused by firebase/admin including everything in the firebase package, not just the "admin" parts.
You can verify this by creating a file with only the import and running #vercel/nft to trace the files.
npm init -y
npm add firebase
echo "const { auth: adminAuth } = require('firebase/admin')" > index.js
npm i -g #vercel/nft
nft print index.js
The entire firebase package is quite large, so its best to follow the recommendation from the firebase team and use the firebase-admin package inside Serverless Functions.
This SDK (firebase) is intended for end-user client access from environments such as the Web, mobile Web (e.g. React Native, Ionic), Node.js desktop (e.g. Electron), or IoT devices running Node.js. If you are instead interested in using a Node.js SDK which grants you admin access from a privileged environment (like a server), you should use the Firebase Admin Node.js SDK (firebase-admin).
source: firebase NPM
You could add .vercelignore file to avoid this
Ref: https://vercel.com/guides/prevent-uploading-sourcepaths-with-vercelignore
# Ignore everything (folders and files) on root only
/*
!api
!vercel.json
!*.html
!*.css

Resources