SvelteKit app Vercel random function crashes - vercel

[GET] /proizvodi/9?fbclid=PAAaY2n3yQfX-Wzxs5pTMWeP9nMUkdIv2V4qg8kObIDQgUAdPnwLtWEr4ICYg_aem_AT5iXQ0y2WTFTVjFAkqIfOf-vx44GuIUXoJKxT5IunSH48Cf1QVjlfC8Q1rKapxuuR9daAL70GWwpLZ_rINriwy815oEYfwfXFvOuh3HvHBvhWRFkVdfeQom7PK6UZvTp0s
02:39:09:44
2023-01-26T01:39:09.507Z f0d6641c-416c-4c0a-ba67-c59890f6f936 ERROR [2023-01-26T01:39:09.507Z] #firebase/firestore: Firestore (9.15.0): Could not reach Cloud Firestore backend. Backend didn't respond within 10 seconds.
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.
2023-01-26T01:39:09.539Z efb98c51-3cde-4791-981f-5d22145fe3c0 ERROR Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"TypeError: fetch failed","reason":{"errorType":"TypeError","errorMessage":"fetch failed","cause":{"errorType":"Error","errorMessage":"Client network socket disconnected before secure TLS connection was established","code":"ECONNRESET","host":"translate.googleapis.com","port":443,"localAddress":null,"stack":["Error: Client network socket disconnected before secure TLS connection was established"," at connResetException (node:internal/errors:711:14)"," at TLSSocket.onConnectEnd (node:_tls_wrap:1593:19)"," at TLSSocket.emit (node:events:525:35)"," at endReadableNT (node:internal/streams/readable:1359:12)"," at process.processTicksAndRejections (node:internal/process/task_queues:82:21)"]},"stack":["TypeError: fetch failed"," at fetch (/var/task/node_modules/undici/index.js:105:13)"," at process.processTicksAndRejections (node:internal/process/task_queues:95:5)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: TypeError: fetch failed"," at process.<anonymous> (file:///var/runtime/index.mjs:1194:17)"," at process.emit (node:events:525:35)"," at emit (node:internal/process/promises:149:20)"," at processPromiseRejections (node:internal/process/promises:283:27)"," at process.processTicksAndRejections (node:internal/process/task_queues:96:32)"]}
Unknown application error occurred
Runtime.Unknown
App works perfectly on the localhost, but on when deployed to vercel, I am getting these functions crashes now and then, seems like it's random. It's happening on all urls.
This is really a bummer since it's an e-commerce website and it's ruining my conversion rate.enter image description here
I tried changing the adapter in svelte.config.js to #sveltejs/adapter-vercel hoping it would work but to no avail.

Vercel uses cloud functions which lose web socket connections when they are frozen (as they are after a few minutes of not running). To ensure it works you can create a new connection for each request (so inside load function or GET function).
// $lib/firebase.js
import { initializeApp } from "firebase/app";
const firebaseConfig = {
// FIREBASE_CONFIGURATION
};
export const getFirebaseApp = () => initializeApp(firebaseConfig);
// src/routes/example/+page.server.ts
import { getFirestore } from "firebase/firestore";
import { getFirebaseApp } from "$lib/firebase";
export const load = async ({ params, url }) => {
const app = getFirebaseApp();
const db = getFirestore(app);
// use database and give a response
})
Another idea is would be to use #google-cloud/firestore serverside instead of #firebase/firestore because it is specifically for the backend (see this tutorial).

Related

How to make a fetch request to localhost in React Native/Expo?

I'm creating a React Native/Expo app that uses Deno on the backend. I've created an API in the backend that I can run locally on localhost:4000. When I try to use fetch to call the API in the Expo app, however, I keep getting an error
[Unhandled promise rejection: TypeError: Network request failed] at node_modules/whatwg-fetch/dist/fetch.umd.js:535:17 in setTimeout$argument_0
Here is how I set up the backend
import { Application } from "https://deno.land/x/oak/mod.ts";
import { oakCors } from "https://deno.land/x/cors/mod.ts";
import { APP_HOST, APP_PORT } from "./config.ts";
import router from "./routes.ts";
import _404 from "./controllers/404.ts";
import errorHandler from "./controllers/errorHandler.ts";
const app = new Application();
app.use(oakCors());
app.use(errorHandler);
app.use(router.routes());
app.use(router.allowedMethods());
app.use(_404);
console.log(`Listening on port:${APP_PORT}...`);
And how I use fetch to call the API
const App = () => {
const getData = async () => {
const response = await fetch("http://localhost:4000/something");
const data = await response.json();
console.log(data);
};
useEffect(() => {
getData();
}, []);
return (
...
);
};
Note
Some answers on StackOverflow suggest fetching http://[IP_ADDRESS]:4000/something instead of localhost. I've tried that with no luck.
I've verified that the API is working. I can call it successfully in VSCode's Thunder Client and I can also see the data by going to http://localhost:4000 in the browser.
I found a solution to this issue. I'm running my Expo app on a physical device while my server is running on my computer, on localhost. It makes sense that I'm unable to make requests to localhost on my device, because localhost is not running there.
I fixed this issue by using ngrok, a tool that forwards localhost to a cloud URL, and fetching that URL in the app.
Use the local IP assign to your device, like: http://192.168.20.109:port/api/x
find the local IP using the command "ipconfig" in windows or ifconfig in linux

using redis in getServerSideProps results in error net.isIP is not a function

Correct me if I am wrong but getServerSideProps is used to pre-render data on each render? If I use the standard redis npm module in getServerSideProps I get the error net.isIP is not a function. From what I have researched this is due to the client trying to use the redis functions.
I am trying to create an application to where session data is saved in a redis key based on a cookie token. Based on the user Id a database is called and renders data to the component. I can get the cookie token in getServerSideProps but I I run client.get(token) I get the error net.isIP is not a function at runtime.
Am I not using getServerSideProps correctly or should I be using a different method / function? I am new to the whole Next.js world. I appreciate the help.
If I use the same functionality in an /api route everything works correctly.
import util from 'util';
import client from '../libs/redis' // using 'redis' module
// ... my component here
export async function getServerSideProps(context) {
const get = util.promisify(client.get).bind(client);
const name = await get('mytoken') // error `net.isIP is not a function`
return {
props: {
name
},
}
}
// redis.js
const redis = require("redis");
const client = redis.createClient();
client.on("error", function(error) {
console.error(error);
});
module.exports = client
I upgraded to next version 10.0.6 from 9.3 and I do not receive the error anymore.

React Native with axios - Network error calling localhost with self signed https endpoint

I created service in Visual Studio with Conveyor extension to make it accessible in local network. I installed certificate on my Android device so there is green padlock when calling it in browser and service works fine.
However when calling it from React Native app with axios then i get Network error.
That's my code:
const fetchData = async () => {
console.log('url', `${Settings.API_URL}/location/GetDataByMyIp`);
try {
const result = await axios(
`${Settings.API_URL}/location/GetDataByMyIp`,
);
console.log('result', result);
ipData = {
city: result.data.city,
longitude: result.data.longitude,
latitude: result.data.latitude,
};
} catch (e) {
console.log('error', e);
}
};
await fetchData();
In console i see:
url https://192.168.1.14:45455/api/location/GetDataByMyIp
error Error: Network Error
at createError (path_to_app\node_modules\axios\lib\core\createError.js:16)
at EventTarget.handleError (path_to_app\node_modules\axios\lib\adapters\xhr.js:83)
at EventTarget.dispatchEvent (path_to_app\node_modules\event-target-shim\dist\event-target-shim.js:818)
at EventTarget.setReadyState (path_to_app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:575)
at EventTarget.__didCompleteResponse (path_to_app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389)
at path_to_app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:502
at RCTDeviceEventEmitter.emit (path_to_app\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189)
at MessageQueue.__callFunction (path_to_app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425)
at path_to_app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112
at MessageQueue.__guard (path_to_app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373)
I tried to add this line to AndroidManifest.xml application tag but still have the error
android:usesCleartextTraffic="true"
Some solutions say about adding as 2nd parameter to axios, but it doesn't work with React Native.
new https.Agent({
rejectUnauthorized: false,
});
I tried to call some other service from the internet and then error was gone.
Is there some solution to this? I haven't found anything more. My last idea is to host service on Azure so I'll have properly signed SSL, but i guess it has to be a way to run it locally.
Edit: It works through http

WebSockets from Vue component to flask - can't connect to server

I am making my first steps with websockets in my application.
My frontend is using vue.js while my backend uses flask.
In my component I wrote this.
created() {
console.log('Starting connection to WebSocket Server');
// this.connection = new WebSocket('wss://echo.websocket.org');
this.connection = new WebSocket('wss://192.168.0.22:5000');
this.connection.onmessage = function (event) {
console.log(event);
};
this.connection.onopen = function (event) {
console.log(event);
console.log('Successfully connected to the echo websocket server...');
};
},
In my flask app.py besides other stuff I have this
app = Flask(__name__)
socketio = SocketIO(app)
CORS(app)
"""Socket.IO decorator to create a websocket event handler"""
#socketio.on('my event')
def handle_my_custom_event(json, methods=['GET', 'POST']):
print('received my event: ' + str(json))
socketio.emit('my response', json, callback=messageReceived)
def messageReceived(methods=['GET', 'POST']):
print('message was received!!!')
if __name__ == "__main__":
socketio.run(app, debug=True)
In my browser I get the error that firefox could not make a connection to wss://192.168.0.22:5050. I already tried the frontend with the websocket from a tutorial which is commented out now.
I am not sure, which url I should use for my own backend or what I have to add there.
Sorry if this is obvious but I am a complete beginnern.
Thanks in advance!
EDIT:
In chrome the error I receive is "WebSocket connection to 'wss://192.168.0.38:5000/' failed: WebSocket opening handshake timed out"
Also as I saw this error when trying out stuff, maybe this question could be relevant? vue socket.io connection attempt returning "No 'Access-Control-Allow-Origin' header is present" error even when origins have been set
so the part for the socket which i ended up using for the client/component:
import io from 'socket.io-client';
created() {
// test websocket connection
const socket = io.connect('http://192.168.0.38:5000');
// getting data from server
// eslint-disable-next-line
socket.on('connect', function () {
console.error('connected to webSocket');
//sending to server
socket.emit('my event', { data: 'I\'m connected!' });
});
// we have to use the arrow function to bind this in the function
// so that we can access Vue & its methods
socket.on('update_on_layouts', (data) => {
this.getAllLayouts();
console.log(data);
});
},
The Flask server code stayed as shown above. Additionally here is an example from my flask server to emit the update_on_layouts socketio.emit('update_on_layouts', 'success')

Prevent supertest from running until express server has started

I have an node / express js app that was generated using the yoman full stack generator. I have swapped out mongo / mongoose for cloudant db (which is just a paid for version of couchdb). I have a written a wrapper for the Cloudant node.js library which handles cookie auth with my instance via an init() method wrapped in a promise. I have refactored my application to not start the express server until the connection to the db has been established as per snippet below taken from my app.js
myDb.init(config).then(function (db) {
logger.write(1001, '','Connection to Cloudant Established');
// Start server
server.listen(config.port, config.ip, function () {
logger.write(1001, "",'Express server listening on '+config.port+', in '+app.get('env')+' mode');
});
});
On my express routes I have introduced a new middleware which attaches the db object to the request for use across the middleware chain as per below. This gets the db connection object before setting the two collections to use.
exports.beforeAll = function (req, res, next) {
req.my = {};
// Adding my-db
req.my.db = {};
req.my.db.connection = myDb.getDbConnection();
req.my.db.orders = req.my.db.connection.use(dbOrders);
req.my.db.dbRefData = req.my.db.connection.use(dbRefData);
next();
};
This mechanism works when i manually drive my apis through POSTman as the express server won't start until after the promise from the db connection has been resolved. However when running my automated tests the first few tests are now always failing because the application has not finished initialising with the db before jasmine starts to run my tests against the APIs. I can see in my logs the requests on the coming through and myDb.getDbConnection(); in the middleware returning undefined. I am using supertest and node-jasmine to run my tests. For example
'use strict';
var app = require('../../app');
var request = require('supertest');
describe('GET /api/content', function () {
it('should respond with JSON object', function (done) {
request(app)
.get('/api/content')
.expect(200)
.expect('Content-Type', /json/)
.end(function (err, res) {
if (err) return done(err);
expect(res.body).toEqual(jasmine.any(Object));
done();
});
});
});
So, my question is how can I prevent supertest from making the requests until the server.listen() step has been completed as a result of the myDb.init() call being resolved? OR perhaps there is some kind of jasmine beforeAll that I can use to stop it running the describes until the promise has been resolved?
You could make you app return an EventEmitter which emits a "ready" event when it has completed its initialisation.
Then your test code, in a before clause, can wait until the "ready" event arrives from the app before proceeding with the tests.