Can I use Nuxt.js to render data from database?

Viewed 6254

I am in the process of learning nuxt.js, so I've decided to create a small project with it. I read couple of documentation. There's something that I did not fully understand though.

If Nuxt can use several backend framework (express, hapi, koa, others), can I use something like sequelize and create a fullstack app with it?

For example, I use express and sequelize to access a database. Then using nuxt's asyncData to rendered it to my component without fetching using axios. Is it possible? Need some information about this

2 Answers

Nuxt.js is backend agnostic — meaning you can use any backend technology to power your Nuxt.js (or Vue.js) application. In your case you can create your backend using express and sequelize. You cant directly access your database from your nuxt, you need to create interfaces that will provide data in your asyncdata.

<script>
import Customers from '~/plugins/Customers.js'
export default{
  asyncData ({ params }) {
    return Customers.getCustomers()
    .then(result => { customers: result.users})
  } 
}
</script>

In the following example, getCustomers() returns a Promise which contains the users. In the Customers.js you create an interfaces which will access your database. Hope this gives you an idea how you can implement, it is always recommended you abstract away your frontend and backend so that in future if you wish to change your backend stack your it will be easy to update, also making API requests to your express server in your asyndata would be good.

You can't call the database directly from asyncData because that wouldn't work when running in the browser.

The very first page you visit on the site will be server-rendered so you could theoretically make a database request from your Vue code. But all subsequent pages are rendered in the browser (including running asyncData) so that would no longer work.

Perhaps it could work for fully static sites where asyncData is run during the build process only. When I tried it I had problems getting the database access code to play nicely with the Webpack build and I gave up.

Related