Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getServerSideProps functions times out when connecting to MongoDB #191

Closed
Jonzy3000 opened this issue Apr 3, 2021 · 3 comments
Closed
Labels
priority: medium type: bug code to address defects in shipped code

Comments

@Jonzy3000
Copy link

Jonzy3000 commented Apr 3, 2021

Describe the bug
Hi, I'm trying to port over a project from vercel, but having issues with functions timing out when trying to connect to mongo. I have a minimal github repository that reproduces this issue if that helps.

To Reproduce
Steps to reproduce the behavior:

// pages/mongo-check.tsx

import { connectToDatabase } from "../server/db/mongodb";

interface Props {
  isConnected: boolean;
}

const SSR = ({ isConnected }: Props) => {
  return (
    <div>
      {isConnected ? (
        <h2 className="subtitle">You are connected to MongoDB</h2>
      ) : (
        <h2 className="subtitle">
          You are NOT connected to MongoDB. Check the <code>README.md</code> for
          instructions.
        </h2>
      )}
    </div>
  );
};

export async function getServerSideProps() {
  const { client } = await connectToDatabase();

  console.log("ServerSideProps - connected to db");

  const isConnected = await client.isConnected();

  console.log(`ServerSideProps - connected: ${isConnected}`);

  return {
    props: { isConnected },
  };
}

export default SSR;
// server/db/mongodb.ts
// stolen from https://github.com/vercel/next.js/blob/canary/examples/with-mongodb/util/mongodb.js and added some basic types

import { Db, MongoClient } from "mongodb";

const { MONGODB_URI, MONGODB_DB } = process.env;

if (!MONGODB_URI) {
  throw new Error(
    "Please define the MONGODB_URI environment variable inside .env.local"
  );
}

if (!MONGODB_DB) {
  throw new Error(
    "Please define the MONGODB_DB environment variable inside .env.local"
  );
}

/**
 * Global is used here to maintain a cached connection across hot reloads
 * in development. This prevents connections growing exponentially
 * during API Route usage.
 */
let cached = global["mongo"];

if (!cached) {
  cached = global["mongo"] = { conn: null, promise: null };
}

export async function connectToDatabase(): Promise<{
  db: Db;
  client: MongoClient;
}> {
  if (cached.conn) {
    console.log("Using cached mongodb connection");
    return cached.conn;
  }

  if (!cached.promise) {
    const opts = {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    };

    console.log("Creating new mongodb connection");
    cached.promise = MongoClient.connect(MONGODB_URI, opts).then((client) => {
      return {
        client,
        db: client.db(MONGODB_DB),
      };
    });
  }

  console.log("waiting for mongodb connection");
  cached.conn = await cached.promise;
  return cached.conn;
}
  1. Create a fresh create-next-app with these files added
  2. Deploy via netlify with correct mongodb env vars
  3. go to your-url/mongo-check

This produces {"errorMessage":"2021-04-03T16:41:18.229Z aa9a8258-e195-4e9c-89c9-b4026e000da1 Task timed out after 10.00 seconds"}

With logs that look like

5:39:46 PM: cac3f717 INFO   [request] /mongo-check
5:39:46 PM: cac3f717 INFO   Creating new mongodb connection
5:39:46 PM: cac3f717 INFO   waiting for mongodb connection
5:39:47 PM: cac3f717 INFO   ServerSideProps - connected to db
5:39:47 PM: cac3f717 INFO   ServerSideProps - connected: true
5:39:56 PM: cac3f717 Duration: 10010.45 ms	Memory Usage: 90 MB	Init Duration: 343.70 ms	

From the logs, it seems that the connection to mongo is successful (around 1 second) then just sits there doing nothing before it times out.

Expected behavior
A page with You are connected to MongoDB appears

Page is - https://mongo-nextjs.netlify.app/mongo-check

Versions

  • Next.js: 10.1.3
  • plugin (if installed at fixed version): auto one

Possibly related - netlify/next-on-netlify#172

Thanks in advance, let me know if there is anything else I can provide :)

@Jonzy3000
Copy link
Author

Jonzy3000 commented Apr 3, 2021

Ah, after a bit of digging it was fixed by this - netlify/next-on-netlify#66 (comment)

export async function getServerSideProps({ req }) {
  // Get event and context from Netlify Function
  const { context } = req.netlifyFunctionParams || {};

  // If we are currently in a Netlify function (deployed on netlify.app or
  // locally with netlify dev), do not wait for empty event loop.
  // See: https://stackoverflow.com/a/39215697/6451879
  // Skip during next dev.
  if (context) {
    console.log("Setting callbackWaitsForEmptyEventLoop: false");
    context.callbackWaitsForEmptyEventLoop = false;
  }

  ...
}

Will be interested to hear the outcome of this - #190. I guess this will also mean any non-predefined getStaticPaths with fallback: true pages won't work if interacting with mongo as the page is SSRed - netlify/next-on-netlify#7 (comment).

Out of interest is there a way to disable this for all functions created by the plugin? Possibly with some sort of patch?

@lindsaylevine lindsaylevine added type: bug code to address defects in shipped code priority: medium labels Apr 5, 2021
@lindsaylevine
Copy link

@Jonzy3000 thanks so much for opening this and reporting back with what you discovered yourself! i'll be exploring internally any implications of finn's suggestion in #190. in the meantime, you absolutely could use patch-package to patch the plugin by adding the context.callbackWaitsForEmptyEventLoop = false; in templates/netlifyFunction.js. let me know if that helps!

@lindsaylevine
Copy link

this should be resolved now per v3.4.0! will close but please let us know if you continue to have function timeout issues!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
priority: medium type: bug code to address defects in shipped code
Projects
None yet
Development

No branches or pull requests

2 participants