title: Expose mongodb database connection to pages in Next.js 6 app
body: <p>I am building an app with <a href="https://nextjs.org/" rel="nofollow noreferrer">Next.js v6</a>, and I would like to fill pages with results from a local mongodb database.</p>
  
  <p>Ideally, I would like to do something as simple as <a href="https://nextjs.org/learn/basics/fetching-data-for-pages/fetching-batman-shows" rel="nofollow noreferrer">this example from the tutorial</a>, but <strong>instead of using an api fetch, just send a query to my mongodb on localhost.</strong></p>
  
  <p><em>Example from Next.js tutorial</em></p>
  
  <pre><code>import Layout from '../components/MyLayout.js'
  import Link from 'next/link'
  import fetch from 'isomorphic-unfetch'
  
  const Index = (props) =&gt; (
    &lt;Layout&gt;
      &lt;h1&gt;Batman TV Shows&lt;/h1&gt;
      &lt;ul&gt;
        {props.shows.map(({show}) =&gt; (
          &lt;li key={show.id}&gt;
            &lt;Link as={`/p/${show.id}`} href={`/post?id=${show.id}`}&gt;
              &lt;a&gt;{show.name}&lt;/a&gt;
            &lt;/Link&gt;
          &lt;/li&gt;
        ))}
      &lt;/ul&gt;
    &lt;/Layout&gt;
  )
  
  Index.getInitialProps = async function() {
    const res = await fetch('https://api.tvmaze.com/search/shows?q=batman')
    const data = await res.json()
  
    console.log(`Show data fetched. Count: ${data.length}`)
  
    return {
      shows: data
    }
  }
  
  export default Index
  </code></pre>
  
  <p>My problem is in trying to get my database connected and exposed to the app so that I can do something like this on a page names resources.js:</p>
  
  <pre><code>import Layout from '../components/Layout'
  import Link from 'next/link'
  
  const Resources = (props) =&gt; {
      &lt;Layout&gt;
          &lt;h3&gt;Resources&lt;/h3&gt;
          &lt;ul style={listStyle}&gt;
              {props.resources.map(({resource}) =&gt; (
                  &lt;li key={resource._id}&gt;
                      &lt;Link href={resource.link}&gt;
                          &lt;a&gt;{resource.title}&lt;/a&gt;
                      &lt;/Link&gt;
                  &lt;/li&gt;
              ))}
          &lt;/ul&gt;
      &lt;/Layout&gt;
  };
  
  Resources.getInitialProps = async function() {  
  
      // get query from mongo DB
      // req is 'undefined' -- I want to see the db here
      const list = await req.db.get('resources').find();
      return list;
  
  }
  
  export default Resources;
  </code></pre>
  
  <p>But I don't know how I can expose the database in a function that could be accessed from pages anywhere in the app. It seems that older tutorials of examples used something like <code>server.use((req, res, next) =&gt; { req.db = dbToExpose });</code> in the main <code>index.js</code> file, but this doesn't seem to be working with Next.js v. 6?? </p>
  
  <p><em>For example, <a href="https://github.com/vkarpov15/reading-list" rel="nofollow noreferrer">this sample repo</a> from <a href="http://thecodebarbarian.com/building-a-nextjs-app-with-mongodb.html" rel="nofollow noreferrer">this tutorial</a> doesn't seem to work for me with the latest version of Next.js. The db exposed trough <code>req.db</code> comes up as 'undefined' when you try to access it from a a page. But perhaps I am missing some other problem.</em></p>
  
  <p>Here's my attempt in my base server file at exposing the db so I can access it from files in <code>pages/</code>:</p>
  
  <pre><code>const express = require('express')
  const next = require('next')
  const monk = require('monk')('localhost/myDatabase')
  
  const dev = process.env.NODE_ENV !== 'production'
  const app = next({ dev })
  const handle = app.getRequestHandler()
  
  app.prepare()
  .then(() =&gt; {
    const server = express()
  
    // This is not working to expose the db!
    server.use((req, res, next) =&gt; {
      req.db = monk
      next()
    });
  
    server.get('*', (req, res) =&gt; {
      return handle(req, res)
    })
  
    server.listen(3000, (err) =&gt; {
      if (err) throw err
      console.log('&gt; Ready on http://localhost:3000')
    })
  })
  .catch((ex) =&gt; {
    console.error(ex.stack)
    process.exit(1)
  })
  </code></pre>