2
3 Comments

Server side rendering from DB on NextJS?

I have looked over the web multiple times for fixes and workarounds for doing (SSR) like this in NextJS (9.2) and finally found this great example on how to do it. Big love to the Zeit team.

If you have struggled with this too. Basically you need to move the code you have from your pages/api function to the getStaticProps() on the Page Component. AND THAT'S IT 🔥. You

The comment is by timneutkens who is a part of the NextJS core team:
https://github.com/zeit/next.js/issues/9524#issuecomment-589772756

on March 9, 2020
  1. 2

    The best thing for me is an API to serve the database data and use the api in getInitialProps

    I use mongoke to automatically generate the graphql api for my mongodb database
    https://github.com/remorses/mongoke

  2. 1

    I'm a little confused. According to the docs:

    If you export an async function called getStaticProps from a page, Next.js will pre-render this page at build time using the props returned by getStaticProps.

    So that's at build time (i.e. when you run next build). I don't think that happens at runtime, so if the values in your database change I don't think you'll see those changes unless you re-build and re-deploy your Next app.

    I haven't used getStaticProps, since it was just released today in 9.3 according to their blog post (you mentioned 9.2, but I think it was still a proposal).

    Am I not understanding correctly?

    1. 2

      Basically before they serve to the client they actually run the code first. So when it is sent to the client, all the data is there in the HTML like the traditional SSR.

      Example if you have a blog page. Instead of sending to client then fetch the blog details from the client side, they actually fetch the blog details server side then sent to the client in one request.