Restart MongoDB Connecton on crash - NodeJS - node.js

I have server implemented using nodejs. According to this post, I have one single connection (using native MongoDB) in my index.js file which connects to the MongoDB on server start.
I am using forever, so each time the server crashes this module restarts it.
My question is: What will happen if my mongo connection will crash? How can I handle this situation? How can I detect the crash programmatically? Should I restart it, if yes, how?

You can set auto-connect parameter as true.
app.use(session({
store: new MongoStore({
// Basic usage
host: 'localhost', // Default, optional
port: 27017, // Default, optional
db: 'test-app', // Required
// Basic authentication (optional)
username: 'user12345',
password: 'foobar',
// Advanced options (optional)
autoReconnect: true, // Default
})
}));

Related

nodejs express webapp - ERROR: read ECONNRESET

When I leave my application idle for a few minutes, it errors out. This is my first webapp I created and it is sending and receiving data from a mysql database - somewhat of a sign up form. Is there a way to stop this from happening? Thanks!
var connection = mysql.createPool({
host: host,
user: user,
password: password,
database: db,
ssl: ssl
});
My original code was var connection = mysql.createConnection...
I replaced that and removed connection.connect();
This seems to happen when establish a single use connection, it can be avoided by establishing a connection pool instead.

How to destroy the session (store)?

For authentification I'm trying to understand, how sessions work. With help of documentation of express session and Sessions in Node JS I got it work.
Now I'm figuring out, what to do, that users can log out. In the documentation of express session is to read "The default server-side session storage, MemoryStore, is purposely not designed for a production environment." They recommand a compatible session store.
I have choosen connect-redis. They call it an "in-memory data structure store". Now I'm wondering, what is the difference between redis and the database, that I would like to use (back4app).
If I implement connect-redis
const RedisStore = require('connect-redis')(session);
const redis = require("redis").createClient();
let sess = {
store: new RedisStore({ host: 'localhost', 6379, client: redis }),
secret: cryptoString,
resave: true,
saveUninitialized: true,
cookie: {
maxAge: 1 * 60 * 1000,
},
}
server.use(session(sess));
the user object from back4app stills undefined. (Without redis the user object exists.)
As mentioned I have tryed Parse.User.logOut(). It doesn't work. The console says Parse.User is null.
Please, explain
what is the difference between back4app and redis? Do I need both?
how do I enable log out?
For all with the same problem. This is my other question in this context. It will help you to see the whole picture.

Multiple redis instances for multiple NodeJS servers

After a bit of research, I came to the conclusion that I can run multiple instances of Redis on my CentOS server for each NodeJS server I run (I use Redis to store sessions).
I have followed these instructions and both instances are running properly on two different ports.
On my NodeJS servers, I configured Redis as follows:
import * as session from "express-session";
var RedisStore = require('connect-redis')(session);
var redis = require("redis").createClient();
app.use(session(
{
secret: secret,
store: new RedisStore({ host: 'localhost', port: 6379, client: redis }),
cookie: { maxAge: 12 * 3600000 },
resave: true, saveUninitialized: true
}
));
One with port 6379 and the other with 6380.
I use req.session.regenerate to register a session.
Both login systems work perfectly individually. However, when I load anything on one application, the sessions of the other application are deleted (and need to be re-logged in).
What am I missing here?
The problem looks like it is the "session store" in Express and not your usage of Redis.
From the express session documentation:
NOTE be careful to generate unique IDs so your sessions do not conflict.
app.use(session({
genid: function(req) {
return genuuid() // use UUIDs for session IDs
},
secret: 'keyboard cat'
}))
Name: The name of the session ID cookie to set in the response (and read from in the request).
The default value is 'connect.sid'.
Specifically this warning explains your problem:
Note if you have multiple apps running on the same hostname (this is
just the name, i.e. localhost or 127.0.0.1; different schemes and
ports do not name a different hostname), then you need to separate the
session cookies from each other. The simplest method is to simply set
different names per app.

Google App Engine connection.session() error

My App Engine logs show this.
Warning: connection.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
Now my nodejs App can't use session. How I fix this?
Assuming you're referring to user authentication, note the following portion of the code from the AppEngine Node documentation and example:
// In production use the App Engine Memcache instance to store session data,
// otherwise fallback to the default MemoryStore in development.
if (config.get('NODE_ENV') === 'production' && config.get('MEMCACHE_URL')) {
sessionConfig.store = new MemcachedStore({
hosts: [config.get('MEMCACHE_URL')]
});
}
The default MemoryStore fallback is basically just there for development purposes; you should specify a more permanent/scaleable session storage of your choice for actual usage.
I think you are using PM2 or your server is running multiple threads, with default session storage mechanism. This won't scale pass a single thread solution, which is what you generally use in the development mode.
Hence, in-order to persist the session, you need to store it somewhere. For example, Redis.
const EXPRESS = require('express');
const APP = EXPRESS();
const EXPRESS_SESSION = require('express-session');
const REDIS_STORE = require('connect-redis')(EXPRESS_SESSION);
APP.use(EXPRESS_SESSION({
secret: 'YOUR_SECRET',
saveUninitialized: false,
resave: false,
store: new REDIS_STORE({ //storing the session in redis
host: 'localhost',
port: 6379, //redis port, should be 6379 by default
ttl: 300 //time-to-live, session will be destroyed if no activity in 5 mins
})
}));
Source of the code: Personal project
Using a session store fixed the error.
use this link.
https://github.com/expressjs/session#compatible-session-stores
In the README.md under
compatible session stores there is list of compatible session stores for expressjs.

Sails connect-redis adapter

I want to use redis commands for ZSET elements. In sails, I enabled the connect-redis adapter as per the docs. Now how do I access the redis commands with this redis client which is already created(I guess) when sails is lifted?
Also do I need to create a global variable for it?
/* config/session.js */
adapter: 'connect-redis',
host: 'localhost',
port: 6379,
db: 0,
// pass: <redis auth password>,
prefix: 'sess:',
Thanks in advance.
I think it should be available as sails.config.session.store.client, and if you have globals enabled, it would work in any place in your code.

Resources