Next.js: How to connect to a database?

Created on 9 Dec 2016  路  5Comments  路  Source: vercel/next.js

In my app I have a database that stores data. It can only be connected to from the backend, not the browser, and the code to connect to that database includes some stuff like auth secrets that shouldn't be shipped to the frontend. How should I set this up in next.js, is there a recommended way? I initially thought I could stick something in getInitialProps but then it would get shipped to the client as well.

Most helpful comment

Would be very good to have a tutorial on the nextjs documentation on possible ways to connect to a database, and how you could use sockets to have realtime apps that update on changes to database.

All 5 comments

We recommend to run API server which connects to database, and access to it on getInitialProps.
Additionally, you would be able to use database by https://github.com/zeit/next.js/issues/291

Ah, that makes sense, thanks for answering my question!

To expand this question, I'm curious how you would connect next.js to a database for your typical CRUD app.

Are you making http requests to an api server in getInitialProps or is the api and client handled by the same server with direct access to the db in getInitialProps?

The former would make 2 http requests to render the ui (browser -> client server -> api server) whereas the latter it seems like you'd be creating a more monolithic-style project.

Would be very good to have a tutorial on the nextjs documentation on possible ways to connect to a database, and how you could use sockets to have realtime apps that update on changes to database.

@arasha you can e.g look at my app: https://github.com/relatenow/relate. Just doesn't yet have realtime subscriptions but you get the idea.

Was this page helpful?
0 / 5 - 0 ratings