I'm working on a new website, and although things were working well as we developed locally we've run into an issue when we tried to deploy on Vercel. The app uses the Sapper framework for both the pages and an API, and a database in MongoDB Atlas that we access through Mongoose. The behavior we have locally is that we npm run dev and a single DB connection is made which persists until we shut the app down.
When it gets deployed to Vercel though, the code which makes the DB connection and prints that "DB connection successful" message and is only supposed to run once is instead run on every API request
This seems to quickly get out of hand, reaching our database's limit of 500 connections:
As a result, after the website is used briefly even by a single user some of our API requests start failing with this error (We have the db accepting any connection rather than an IP whitelist, so the suggestion the error gives isn't helpful):
Our implementation is that we have a call to mongoose.connect in a .js file:
mongoose.connect(DB, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
}).then(() => console.log("DB connection successful!")).catch(console.error);
and then we import that file in Sapper's server.js. The recommendation we've been able to find is "just cache the connection", but that hasn't been successful and seems to be more of a node-mongodb-native thing. Regardless, this is what we tried which didn't work better or worse locally, but also didn't fix the problems on Vercel:
let cachedDb = {};
exports.connection = async () => {
if (cachedDb.isConnected)
return;
try {
const db = await mongoose.connect(DB, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
});
cachedDb.isConnected = db.connections[0].readyState;
console.log("DB connection successful!");
return cachedDb;
} catch(error) {console.log("Couldn't connect to DB", error);}
So... is there a way to make this work without replacing at least one of the pieces? The website isn't live yet so replacing something isn't the end of the world, but "just change a setting" is definitely preferred to starting from scratch.
Summary
Serverless functions on Vercel work like a self-contained process. While it is possible to cache the connection "per function," it is not a good idea to deploy a serverful-ready library to a serverless environment. Here are a few questions that you need to answer:
Is your framework or DB library caching the connection?
Is your code prepared for Serverless?
What type of workload is Vercel optimized for?
Further Context
Vercel is an excellent platform for your frontend that would use Serverless Functions as helpers. The CDN available in conjunction with the workflow makes the deployment process very quick and allows you to move faster. Deploying a full-blown API or serverful workload will never be a good idea. Let's suppose I need to use MySQL with Vercel. Instead of mysql, you should use mysql-serverless, which is optimized for the serverless primitives. Even with that in mind, it will be probably cheaper to just use a VM/Container for the API depending on the level of requests you are expecting. Therefore, we would end up with the following ideal solution:
Frontend (Vercel - Serverless) --> Backend (Serverful - External provider) --> DB
Disclaimer: At the moment, I work for Vercel.
If you are using the cloud database of MongoDB Atlas, then you can use the mongodb-data-api library, which is encapsulated based on the Data API of MongoDB Atlas. All data operations are performed through the HTTPS interface, and there is no connection problem.
import { MongoDBDataAPI, Region } from 'mongodb-data-api'
const api = new MongoDBDataAPI({
apiKey: '<your_mongodb_api_key>',
appId: '<your_mongodb_app_id>'
})
api
.findOne({
dataSource: '<target_cluster_name>',
database: '<target_database_name>',
collection: '<target_collection_name>',
filter: { name: 'Surmon' }
})
.then((result) => {
console.log(result.document)
})
The example codes provided by NextJS say to cache the database connection yet this is the issue that happens with myself as well.
Both here
https://github.com/vercel/next.js/blob/canary/examples/with-mongodb-mongoose/utils/dbConnect.js
And here
https://github.com/vercel/next.js/blob/canary/examples/with-mongodb/util/mongodb.js
are caching the connection and if I copy the example i get the same issue as the OP.
It also says here
https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation
that i can interact directly with my database. Massively conflicting information where I'm told on one hand to cache the connection, while a member of the team tells me its not suitable for this approach despite the docs & examples telling me otherwise. Is this a bug report type situtation?
I was struggling with the similar issue but I came across an example here:
https://github.com/vercel/next.js/blob/canary/examples/with-mongodb/util/mongodb.js
Apparently the trick is to use the global variable:
let cached = global.mongo
if (!cached) {
cached = global.mongo = { conn: null, promise: null }
}
Related
I've built a wee program that works fine when I run it locally. I've deployed the backend to Heroku, and I can access that either by going straight to the URL (http://gymbud-tracker.herokuapp.com/users) or when running the frontend locally. So far so good.
However, when I run npm run-script build and deploy it to Netlify, something goes wrong, and any attempt to access the server gives me the following error in the console:
auth.js:37 Error: Network Error
at e.exports (createError.js:16)
at XMLHttpRequest.p.onerror (xhr.js:99)
The action that is pushing that error is the following, if it is relevant:
export const signin = (formData, history) => async (dispatch) => {
try {
const { data } = await api.signIn(formData);
dispatch({ type: AUTH, data });
history.push("../signedin");
} catch (error) {
console.log(error);
}
};
I've been tearing my hair out trying to work out what is changing when I build and deploy, but cannot work it out.
As I say, if I run the front end locally then it access the Heroku backend no problem - no errors, and working exactly as I'd expect. The API call is correct, I believe: const API = axios.create({baseURL: 'http://gymbud-tracker.herokuapp.com/' });
I wondered if it was an issue with network access to the MongoDB database that Heroku is linked to, but it's open to "0.0.0.0/0" (I've not taken any security precautions yet, don't kill me!). The MDB database is actually in the same collection as other projects I've used, that haven't had this problem at all.
Any ideas what I need to do?
The front end is live here: https://gym-bud.netlify.app/
And the whole thing is deployed to GitHub here: https://github.com/gordonmaloney/gymbud
Your issue is CORS (Cross-Origin Resource Sharing). When I visit your site and inspect the page, I see the following error in the JavaScript console which is how I know this:
This error essentially means that your public-facing application (running live on Netlify) is trying to make an HTTP request from your JavaScript front-end to your Heroku backend deployed on a different domain.
CORS dictates which requests from a frontend application are ALLOWED to make a request to your backend API.
What you need to do to fix this is to modify your Heroku application and have it return the appropriate Access-Control-Allow-Origin header. This article on MDN explains the header and how you can use it.
Here's a simple example of the header you could set on your Heroku backend to allow this to work:
Access-Control-Allow-Origin: *
Please be sure to read the MDN documentation, however, as this example will allow any front-end application to make requests to your Heroku backend when in reality, you'll likely want to restrict it to just the front-end domains you build.
God I feel so daft, but at least I've worked it out.
I looked at the console on a different browser (Edge), and it said it was blocking it because it was mixed origin, and I realised I had just missed out the s in the https on my API call, so it wasn't actually a cors issue (I don't think?), but just a typo on my part!
So I changed:
const API = axios.create({baseURL: 'http://gymbud-tracker.herokuapp.com' });
To this:
const API = axios.create({baseURL: 'https://gymbud-tracker.herokuapp.com' });
And now it is working perfectly ☺️
Thanks for your help! Even if it wasn't the issue here, I've definitely learned a lot more about cors on the way, so that's good
Why i need to pass { useUnifiedTopology: true } in my app.js .When i dont't pass the { useUnifiedTopology: true } still everything works. SO is it okay to not pass it in my server file.
Is it going to effect my project.
There are several deprecations in the MongoDB Node.js driver that Mongoose users should be aware of. Mongoose provides options to work around these deprecation warnings, but you need to test whether these options cause any problems for your application.
MongoDB driver 3.3.x, which introduced a significant refactor of how it handles monitoring all the servers in a replica set or sharded cluster. In MongoDB parlance, this is known as server discovery and monitoring.
To opt in to using the new topology engine, uses the below line:
('useUnifiedTopology', true);
The useUnifiedTopology option removes support for several connection options that are no longer relevant with the new topology engine:
autoReconnect
reconnectTries
reconnectInterval
When you enable useUnifiedTopology, please remove those options from your mongoose.connect() or createConnection() calls.
Reference: https://mongoosejs.com/docs/deprecations.html
I am trying to migrate my Node/Express REST API to Google Cloud Functions, and was noticing some performance issues. I am receiving 404 errors on all my API routes while waiting for my Functions to "spin up" after a period of inactivity. I was curious if this was related to my implementation. Here is my Express serverless "server", written in Typescript (index.ts):
import * as functions from 'firebase-functions'
import * as express from 'express'
import { MyApi } from './server'
const app: express.Application = MyApi.bootstrap().app
export const myApp = functions.https.onRequest(app)
Next, here is server.ts
import * as express from 'express'
import * as mongodb from 'mongodb'
require('dotenv').config({ path: '.env' })
export class MyApi {
app: express.Application = express()
mongoDbUri: string = process.env.MONGO_URI
static bootstrap(): MyApi {
return new MyApi()
}
constructor() {
this.connectToDb(this.mongoDbUri)
}
connectToDb(uri: string) {
mongodb.MongoClient.connect(uri, (err, db) => {
if (err) {
this.handleNoDbError(err)
}
setApiRoutes(app: express.Application, db)
})
}
}
I've stripped a lot of the redundant code for the sake of simplicity, but hopefully this is enough for you to get the idea. I am asking Functions to expose some API endpoints. First, I am using connection pooling to make a single Mongo connection, then I pass that connection (db) down to my routes. These route endpoints in turn make a find() request to my MongoDB Atlas database, and pass those results on to my app.
I deployed a version of this code and it is functioning ok, in that it fetches results properly. However I am concerned about the slow performance and intermittent 404 errors (compared to a dedicated Node/Express server on Heroku, for example).
I was wondering if my problems are related to the Mongo Client. Is it connecting to my database every time a request is made to Functions? Once my Functions wake up after inactivity, do they persist the same Mongo DB connection across all future requests? I'm new to serverless so I guess I'm confused about whether my Functions start up and stay up during execution, then "shut down" after going idle.
Can supply live links if needed.
The first time your function is executed in a new instance, it will have to connect to the Mongo server.
This means that the reconnect will at least happen:
After a period of inactivity, if Cloud Functions has spun down your instances.
When there is an increase in activity, as Cloud Functions spins up additional instances.
It may also happen intermediately if your client library does connection management. But since that doesn't depend on the Cloud Functions environment, I can't comment on it.
It seems to be a common and safer practice to host the database separately from Meteor apps. That is to say, have an EC2 instance for your Meteor app, and an EC2 instance for your MongoDB, and make them talk to one another.
From what I understand, people do this because it's more secure, and it allows them to deploy newer versions of their app without touching the database.
I'd like to do this with Amazon EC2 alone, as opposed to using another 3rd party service, like Compose.io.
How can I host a Meteor app and its database separately on two EC2 instances, and have them communicate with one another?
It is common practice, and people mostly do it because it offers you the ability to scale them both independently.
As to the how, you'll want to obviously configure each of your Amazon EC2 instances, installing meteor on one, and MongoDB on the other. You'll also need to configure your VPC (Amazon Virtual Private Cloud) so that your MongoDB instance accepts incoming connections on whatever port you specify (default is 27017), so that your Meteor Application can connect.
After that it's just a matter of telling your meteor app where to go to get the database connection. The most secure way of doing this will be to set a couple Environment Variables, named MONGODBSERVER and MONGODBPORT, DBUSER, DBPASSWORD, etc.
You'll then want to set some variables in your server Meteor code, using something like:
Meteor.startup(function() {
var DbUser = process.env.DBUSER;
var DbPassword = process.env.DBPASSWORD;
var MongoDBServer = process.env.MONGODBSERVER;
var MongoDBPort = process.env.MONGODBPORT;
});
And if you're using the native MongoDB Driver, connecting becomes trivial:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://DbUser:DbPassword#MongoDBServer:MongoDBPort/databasename', function(err, db) {
...
});
Then it's just a matter of constructing your Mongo models using something like:
Temperatures = new Mongo.Collection('temperatures');
Temperatures._ensureIndex({temp: 1, time: 1});
And then taking action on those models in regard to the database:
Temperatures.insert({temp: ftemp, time: Math.floor(Date.now() / 1000)});
I'll also mention that http://modulus.io is a really decent Meteor hosting solution. I'd recommend them, unless you are stuck on using Amazon EC2 instances, which is fine, but more complicated for a simple application.
You need to set an Environment Variable for Mongo where it is hosted
MONGO_URL
mongodb://:#hostingproviderurl:port/xxx?autoReconnect=true&connectTimeoutMS=60000
the correct mongodb:// url string would be provided by the mongodb hosting provider.
Apologies in advance for any failing with my terminology and understanding with Meteor/Mongo, I've just started learning and developing with it.
I am trying to connect my local meteor app to a remote mongodb which is hosted elsewhere.
My code looks like this:
Bills = new Mongo.Collection("bills");
if (Meteor.isClient) {
Meteor.subscribe("bills");
// This code only runs on the client
Template.body.helpers({
documentContent: function () {
return Bills.find();
}
});
Template.documentBody.helpers({
documentContent: function ()
{
var thingy = Bills.find();
console.log(thingy);
return Bills.find({_id: "784576346gf874"});
}
});
}
I have connected to the DB via the shell using the following:
$ MONGO_URL="mongodb://mysite.net:27017/legislation" meteor
In my browser I receive no errors and within my defined template I see [object Object]. The console shows a local miniCollection but doesn't return any of my documents from the subscribed collection.
I guess what I am asking is; if you were connecting to a remote MongoDB within your local app, how would you do it?
Thank you for taking the time to read, any helps is massively appreciated.
Rex, If you're not seeing errors in the output on the browser, or in the console where you're running the server then you may be setup ok. That's exactly how I'm doing it.
Run meteor list in server directory and look for insecure and autopublish
You should understand these two packages They are for rapid prototyping. If they are present, then keep digging into MongoDB and the connection.
I recommend Robomongo for viewing documents directly in MongoDB.
If they are absent, then you need to go about publishing data (getting it from the server to the client) and securing it (letting clients only modify their data).
I recommend these two packages for that.
reywood:publish-composite
ongoworks:security
If you haven't read an introduction to meteor book, it's really worth the time. I've been developing for some time and learned meteor recently. It was invaluable.